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
|
ZijingMao/baselineeegtest-master
|
pop_topoplot.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_topoplot.m
| 15,339 |
utf_8
|
3fd3a5f63febf3a3a010be6092594f69
|
% pop_topoplot() - Plot scalp map(s) in a figure window. If number of input
% arguments is less than 3, pop up an interactive query window.
% Makes (possibly repeated) calls to topoplot().
% Usage:
% >> pop_topoplot( EEG); % pops up a parameter query window
% >> pop_topoplot( EEG, typeplot, items, title, plotdip, options...); % no pop-up
%
% Inputs:
% EEG - Input EEG dataset structure (see >> help eeglab)
% typeplot - 1-> Plot channel ERP maps; 0-> Plot component maps {default:1}.
%
% Commandline inputs also set in pop-up window:
% items - [array] If typeplot==1 (ERP maps), within-epoch latencies
% (ms) at which to plot the maps. If typeplot==0 (component
% maps), component indices to plot. In this case,
% negative map indices -> invert map polarity, or
% NaN -> leave a blank subplot. (Ex: [1 -3 NaN 4])
% title - Plot title.
% rowscols - Vector of the form [m,n] giving [rows, cols] per page.
% If the number of maps exceeds m*n, multiple figures
% are produced {default|0 -> one near-square page}.
% plotdip - [0|1] plot associated dipole(s) for scalp map if present
% in dataset.
%
% Optional Key-Value Pair Inputs
% 'colorbar' - ['on' or 'off'] Switch to turn colorbar on or off. {Default: 'on'}
% options - optional topoplot() arguments. Separate using commas.
% Example 'style', 'straight'. See >> help topoplot
% for further details. {default: none}
%
% Note:
% A new figure is created automatically only when the pop_up window is
% called or when more than one page of maps are plotted. Thus, this
% command may be used to draw topographic maps in a figure sub-axis.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: topoplot(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 02-15-02 text interface editing -sm & ad
% 02-16-02 added axcopy -ad & sm
% 03-18-02 added title -ad & sm
function com = pop_topoplot( EEG, typeplot, arg2, topotitle, rowcols, varargin);
com = '';
if nargin < 1
help pop_topoplot;
return;
end;
if nargin < 2
typeplot = 1;
end;
if typeplot == 0 & isempty(EEG.icasphere)
disp('Error: no ICA data for this set, first run ICA'); return;
end;
if isempty(EEG.chanlocs)
disp('Error: cannot plot topography without channel location file'); return;
end;
if nargin < 3
% which set to save
% -----------------
if typeplot
txtwhat2plot1 = 'Plotting ERP scalp maps at these latencies';
txtwhat2plot2 = sprintf('(range: %d to %d ms, NaN -> empty):', ...
round(EEG.xmin*1000), round(EEG.xmax*1000));
editwhat2plot = [''];
else
txtwhat2plot1 = 'Component numbers';
txtwhat2plot2 = '(negate index to invert component polarity; NaN -> empty subplot; Ex: -1 NaN 3)';
editwhat2plot = ['1:' int2str(size(EEG.icaweights,1))];
end;
if EEG.nbchan > 64,
elecdef = ['''electrodes'', ''off'''];
else,
elecdef = ['''electrodes'', ''on'''];
end;
uilist = { { 'style' 'text' 'string' txtwhat2plot1 } ...
{ 'style' 'edit' 'string' editwhat2plot } ...
{ 'style' 'text' 'string' txtwhat2plot2 } ...
{ } ...
{ 'style' 'text' 'string' 'Plot title' } ...
{ 'style' 'edit' 'string' fastif(~isempty(EEG.setname), [EEG.setname], '') } ...
{ 'style' 'text' 'string' 'Plot geometry (rows,col.); [] -> near square' } ...
{ 'style' 'edit' 'string' '[]' } ...
{ 'style' 'text' 'string' 'Plot associated dipole(s) (if present)' } ...
{ 'style' 'checkbox' 'string' '' } { } ...
{ } ...
{ 'style' 'text' 'string' [ '-> Additional topoplot()' fastif(typeplot,'',' (and dipole)') ...
' options (see Help)' ] } ...
{ 'style' 'edit' 'string' elecdef } };
uigeom = { [1.5 1] [1] [1] [1.5 1] [1.5 1] [1.55 0.2 0.8] [1] [1] [1] };
if typeplot
uilist(9:11) = [];
uigeom(6) = [];
end;
guititle = fastif( typeplot, 'Plot ERP scalp maps in 2-D -- pop_topoplot()', ...
'Plot component scalp maps in 2-D -- pop_topoplot()');
result = inputgui( uigeom, uilist, 'pophelp(''pop_topoplot'')', guititle, [], 'normal');
if length(result) == 0 return; end;
% reading first param
% -------------------
arg2 = eval( [ '[' result{1} ']' ] );
if length(arg2) > EEG.nbchan
tmpbut = questdlg2(...
['This involves drawing ' int2str(length(arg2)) ' plots. Continue ?'], ...
'', 'Cancel', 'Yes', 'Yes');
if strcmp(tmpbut, 'Cancel'), return; end;
end;
if isempty(arg2), error('Nothing to plot; enter parameter in first edit box'); end;
% reading other params
% --------------------
topotitle = result{2};
rowcols = eval( [ '[' result{3} ']' ] );
if typeplot
plotdip = 0;
try, options = eval( [ '{ ' result{4} ' }' ]);
catch, error('Invalid scalp map options'); end;
else
plotdip = result{4};
try, options = eval( [ '{ ' result{5} ' }' ]);
catch, error('Invalid scalp map options'); end;
end;
if length(arg2) == 1,
figure('paperpositionmode', 'auto'); curfig=gcf;
try, icadefs;
set(curfig, 'color', BACKCOLOR);
catch, end;
end;
else
if ~isempty(varargin) & isnumeric(varargin{1})
plotdip = varargin{1};
varargin = varargin(2:end);
else
plotdip = 0;
end;
options = varargin;
end;
% additional options
% ------------------
outoptions = { options{:} }; % for command
options = { options{:} 'masksurf' 'on' };
% find maplimits
% --------------
maplimits = [];
for i=1:2:length(options)
if isstr(options{i})
if strcmpi(options{i}, 'maplimits')
maplimits = options{i+1};
options(i:i+1) = [];
break;
end;
end;
end;
nbgraph = size(arg2(:),1);
if ~exist('topotitle')
topotitle = '';
end;
if ~exist('rowcols') | isempty(rowcols) | rowcols == 0
rowcols(2) = ceil(sqrt(nbgraph));
rowcols(1) = ceil(nbgraph/rowcols(2));
end;
SIZEBOX = 150;
fprintf('Plotting...\n');
if isempty(EEG.chanlocs)
fprintf('Error: set has no channel location file\n');
return;
end;
% Check if pop_topoplot input 'colorbar' was called, and don't send it to topoplot
loc = strmatch('colorbar', options(1:2:end), 'exact');
loc = loc*2-1;
if ~isempty(loc)
colorbar_switch = strcmp('on',options{ loc+1 });
options(loc:loc+1) = [];
else
colorbar_switch = 1;
end
% determine the scale for plot of different times (same scales)
% -------------------------------------------------------------
if typeplot
SIGTMP = reshape(EEG.data, EEG.nbchan, EEG.pnts, EEG.trials);
pos = round( (arg2/1000-EEG.xmin)/(EEG.xmax-EEG.xmin) * (EEG.pnts-1))+1;
nanpos = find(isnan(pos));
pos(nanpos) = 1;
SIGTMPAVG = mean(SIGTMP(:,pos,:),3);
SIGTMPAVG(:, nanpos) = NaN;
if isempty(maplimits)
maxlim = max(SIGTMPAVG(:));
minlim = min(SIGTMPAVG(:));
maplimits = [ -max(maxlim, -minlim) max(maxlim, -minlim)];
end;
else
if isempty(maplimits)
maplimits = 'absmax';
end;
end;
if plotdip
if strcmpi(EEG.dipfit.coordformat, 'CTF')
disp('Cannot plot dipole on scalp map for CTF MEG data');
end;
end;
% plot the graphs
% ---------------
counter = 1;
countobj = 1;
allobj = zeros(1,1000);
curfig = get(0, 'currentfigure');
if isfield(EEG, 'chaninfo'), options = { options{:} 'chaninfo' EEG.chaninfo }; end
for index = 1:size(arg2(:),1)
if nbgraph > 1
if mod(index, rowcols(1)*rowcols(2)) == 1
if index> 1, figure(curfig); a = textsc(0.5, 0.05, topotitle); set(a, 'fontweight', 'bold'); end;
curfig = figure('paperpositionmode', 'auto');
pos = get(curfig,'Position');
posx = max(0, pos(1)+(pos(3)-SIZEBOX*rowcols(2))/2);
posy = pos(2)+pos(4)-SIZEBOX*rowcols(1);
set(curfig,'Position', [posx posy SIZEBOX*rowcols(2) SIZEBOX*rowcols(1)]);
try, icadefs; set(curfig, 'color', BACKCOLOR); catch, end;
end;
curax = subplot( rowcols(1), rowcols(2), mod(index-1, rowcols(1)*rowcols(2))+1);
set(curax, 'visible', 'off')
end;
% add dipole location if present
% ------------------------------
dipoleplotted = 0;
if plotdip && typeplot == 0
if isfield(EEG, 'dipfit') & isfield(EEG.dipfit, 'model')
if length(EEG.dipfit.model) >= index & ~strcmpi(EEG.dipfit.coordformat, 'CTF')
%curpos = EEG.dipfit.model(arg2(index)).posxyz/EEG.dipfit.vol.r(end);
curpos = EEG.dipfit.model(arg2(index)).posxyz;
curmom = EEG.dipfit.model(arg2(index)).momxyz;
try,
select = EEG.dipfit.model(arg2(index)).select;
catch select = 0;
end;
if ~isempty(curpos)
if strcmpi(EEG.dipfit.coordformat, 'MNI') % from MNI to sperical coordinates
transform = pinv( sph2spm );
tmpres = transform * [ curpos(1,:) 1 ]'; curpos(1,:) = tmpres(1:3);
tmpres = transform * [ curmom(1,:) 1 ]'; curmom(1,:) = tmpres(1:3);
try, tmpres = transform * [ curpos(2,:) 1 ]'; curpos(2,:) = tmpres(1:3); catch, end;
try, tmpres = transform * [ curmom(2,:) 1 ]'; curmom(2,:) = tmpres(1:3); catch, end;
end;
curpos = curpos / 85;
if size(curpos,1) > 1 && length(select) == 2
dipole_index = find(strcmpi('dipole',options),1);
if ~isempty(dipole_index) % if 'dipoles' is already defined in options{:}
options{dipole_index+1} = [ curpos(:,1:2) curmom(:,1:3) ];
else
options = { options{:} 'dipole' [ curpos(:,1:2) curmom(:,1:3) ] };
end
dipoleplotted = 1;
else
if any(curpos(1,:) ~= 0)
dipole_index = find(strcmpi('dipole',options),1);
if ~isempty(dipole_index) % if 'dipoles' is already defined in options{:}
options{dipole_index+1} = [ curpos(1,1:2) curmom(1,1:3) ];
else
options = { options{:} 'dipole' [ curpos(1,1:2) curmom(1,1:3) ] };
end
dipoleplotted = 1;
end
end
end
if nbgraph ~= 1
dipscale_index = find(strcmpi('dipscale',options),1);
if ~isempty(dipscale_index) % if 'dipscale' is already defined in options{:}
options{dipscale_index+1} = 0.6;
else
options = { options{:} 'dipscale' 0.6 };
end
end
%options = { options{:} 'dipsphere' max(EEG.dipfit.vol.r) };
end
end
end
% plot scalp map
% --------------
if index == 1
addopt = { 'verbose', 'on' };
else
addopt = { 'verbose', 'off' };
end;
%fprintf('Printing to figure %d.\n',curfig);
options = { 'maplimits' maplimits options{:} addopt{:} };
if ~isnan(arg2(index))
if typeplot
if nbgraph > 1, axes(curax); end;
tmpobj = topoplot( SIGTMPAVG(:,index), EEG.chanlocs, options{:});
if nbgraph == 1,
figure(curfig); if nbgraph > 1, axes(curax); end;
title( [ 'Latency ' int2str(arg2(index)) ' ms from ' topotitle]);
else
figure(curfig); if nbgraph > 1, axes(curax); end;
title([int2str(arg2(index)) ' ms'] );
end;
else
if arg2(index) < 0
figure(curfig); if nbgraph > 1, axes(curax); end;
tmpobj = topoplot( -EEG.icawinv(:, -arg2(index)), EEG.chanlocs, options{:} );
else
figure(curfig); if nbgraph > 1, axes(curax); end;
tmpobj = topoplot( EEG.icawinv(:, arg2(index)), EEG.chanlocs, options{:} );
end;
if nbgraph == 1, texttitle = [ 'IC ' int2str(arg2(index)) ' from ' topotitle];
else texttitle = ['' int2str(arg2(index))];
end;
if dipoleplotted, texttitle = [ texttitle ' (' num2str(EEG.dipfit.model(arg2(index)).rv*100,2) '%)']; end;
figure(curfig); if nbgraph > 1, axes(curax); end; title(texttitle);
end;
allobj(countobj:countobj+length(tmpobj)-1) = tmpobj;
countobj = countobj+length(tmpobj);
drawnow;
axis square;
else
axis off
end;
end
% Draw colorbar
if colorbar_switch
if nbgraph == 1
if ~isstr(maplimits)
ColorbarHandle = cbar(0,0,[maplimits(1) maplimits(2)]);
else
ColorbarHandle = cbar(0,0,get(gca, 'clim'));
end;
pos = get(ColorbarHandle,'position'); % move left & shrink to match head size
set(ColorbarHandle,'position',[pos(1)-.05 pos(2)+0.13 pos(3)*0.7 pos(4)-0.26]);
elseif ~isstr(maplimits)
cbar('vert',0,[maplimits(1) maplimits(2)]);
else cbar('vert',0,get(gca, 'clim'));
end
if ~typeplot % Draw '+' and '-' instead of numbers for colorbar tick labels
tmp = get(gca, 'ytick');
set(gca, 'ytickmode', 'manual', 'yticklabelmode', 'manual', 'ytick', [tmp(1) tmp(end)], 'yticklabel', { '-' '+' });
end
end
if nbgraph> 1,
figure(curfig); a = textsc(0.5, 0.05, topotitle);
set(a, 'fontweight', 'bold');
end;
if nbgraph== 1,
com = 'figure;';
end;
set(allobj(1:countobj-1), 'visible', 'on');
figure(curfig);
axcopy(curfig, 'set(gcf, ''''units'''', ''''pixels''''); postmp = get(gcf, ''''position''''); set(gcf, ''''position'''', [postmp(1) postmp(2) 560 420]); clear postmp;');
com = [com sprintf('pop_topoplot(%s,%d, %s);', ...
inputname(1), typeplot, vararg2str({arg2 topotitle rowcols plotdip outoptions{:} }))];
return;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_mergechan.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_mergechan.m
| 2,300 |
utf_8
|
48938c717d76faeab216bacf2ac08eaa
|
% eeg_mergechan() - merge channel structure while preserving channel
% order
%
% >> mergelocs = eeg_mergechan(locs1, locs2);
%
% Inputs:
% locs1 - EEGLAB channel location structure
% locs2 - second EEGLAB channel location structure
%
% Output:
% mergelocs - merged channel location structure
%
% Author: Arnaud Delorme, August 2006
% Copyright (C) Arnaud Delorme, CERCO, 2006, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% union of two channel location structure
% without loosing the order information
% ---------------------------------------
function alllocs = myunion(locs1, locs2)
labs1 = { locs1.labels };
labs2 = { locs2.labels };
count1 = 1;
count2 = 1;
count3 = 1;
alllocs = locs1; alllocs(:) = [];
while count1 <= length(locs1) | count2 <= length(locs2)
if count1 > length(locs1)
alllocs(count3) = locs2(count2);
count2 = count2 + 1;
count3 = count3 + 1;
elseif count2 > length(locs2)
alllocs(count3) = locs1(count1);
count1 = count1 + 1;
count3 = count3 + 1;
elseif strcmpi(labs1{count1}, labs2{count2})
alllocs(count3) = locs1(count1);
count1 = count1 + 1;
count2 = count2 + 1;
count3 = count3 + 1;
elseif isempty(strmatch(labs1{count1}, labs2))
alllocs(count3) = locs1(count1);
count1 = count1 + 1;
count3 = count3 + 1;
else
alllocs(count3) = locs2(count2);
count2 = count2 + 1;
count3 = count3 + 1;
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_interp.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_interp.m
| 7,599 |
utf_8
|
eeaf74ad67176964b6a8cb937a11371b
|
% pop_interp() - interpolate data channels
%
% Usage: EEGOUT = pop_interp(EEG, badchans, method);
%
% Inputs:
% EEG - EEGLAB dataset
% badchans - [integer array] indices of channels to interpolate.
% For instance, these channels might be bad.
% [chanlocs structure] channel location structure containing
% either locations of channels to interpolate or a full
% channel structure (missing channels in the current
% dataset are interpolated).
% method - [string] method used for interpolation (default is 'spherical').
% 'invdist'/'v4' uses inverse distance on the scalp
% 'spherical' uses superfast spherical interpolation.
% 'spacetime' uses griddata3 to interpolate both in space
% and time (very slow and cannot be interupted).
% Output:
% EEGOUT - data set with bad electrode data replaced by
% interpolated data
%
% Author: Arnaud Delorme, CERCO, CNRS, 2009-
% Copyright (C) Arnaud Delorme, CERCO, 2009, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG com] = pop_interp(EEG, bad_elec, method)
com = '';
if nargin < 1
help pop_interp;
return;
end;
if nargin < 2
disp('Warning: interpolation can be done on the fly in studies');
disp(' this function will actually create channels in the dataset');
disp('Warning: do not interpolate channels before running ICA');
disp('You may define channel location to interpolate in the channel');
disp('editor and declare such channels as non-data channels');
enablenondat = 'off';
if isfield(EEG.chaninfo, 'nodatchans')
if ~isempty(EEG.chaninfo.nodatchans)
enablenondat = 'on';
end;
end;
uilist = { { 'Style' 'text' 'string' 'What channel(s) do you want to interpolate' 'fontweight' 'bold' } ...
{ 'style' 'text' 'string' 'none selected' 'tag' 'chanlist' } ...
{ 'style' 'pushbutton' 'string' 'Select from removed channels' 'callback' 'pop_interp(''nondatchan'',gcbf);' 'enable' enablenondat } ...
{ 'style' 'pushbutton' 'string' 'Select from data channels' 'callback' 'pop_interp(''datchan'',gcbf);' } ...
{ 'style' 'pushbutton' 'string' 'Use specific channels of other dataset' 'callback' 'pop_interp(''selectchan'',gcbf);'} ...
{ 'style' 'pushbutton' 'string' 'Use all channels from other dataset' 'callback' 'pop_interp(''uselist'',gcbf);'} ...
{ } ...
{ 'style' 'text' 'string' 'Interpolation method'} ...
{ 'style' 'popupmenu' 'string' 'Spherical|Planar (slow)' 'tag' 'method' } ...
};
geom = { 1 1 1 1 1 1 1 [1.1 1] };
[res userdata tmp restag ] = inputgui( 'uilist', uilist, 'title', 'Interpolate channel(s) -- pop_interp()', 'geometry', geom, 'helpcom', 'pophelp(''pop_interp'')');
if isempty(res) | isempty(userdata), return; end;
if restag.method == 1
method = 'spherical';
else method = 'invdist';
end;
bad_elec = userdata.chans;
com = sprintf('EEG = pop_interp(EEG, %s, ''%s'');', userdata.chanstr, method);
if ~isempty(findstr('nodatchans', userdata.chanstr))
eval( [ userdata.chanstr '=[];' ] );
end;
elseif isstr(EEG)
command = EEG;
clear EEG;
fig = bad_elec;
userdata = get(fig, 'userdata');
if strcmpi(command, 'nondatchan')
global EEG;
tmpchaninfo = EEG.chaninfo;
[chanlisttmp chanliststr] = pop_chansel( { tmpchaninfo.nodatchans.labels } );
if ~isempty(chanlisttmp),
userdata.chans = EEG.chaninfo.nodatchans(chanlisttmp);
userdata.chanstr = [ 'EEG.chaninfo.nodatchans([' num2str(chanlisttmp) '])' ];
set(fig, 'userdata', userdata);
set(findobj(fig, 'tag', 'chanlist'), 'string', chanliststr);
end;
elseif strcmpi(command, 'datchan')
global EEG;
tmpchaninfo = EEG.chanlocs;
[chanlisttmp chanliststr] = pop_chansel( { tmpchaninfo.labels } );
if ~isempty(chanlisttmp),
userdata.chans = chanlisttmp;
userdata.chanstr = [ '[' num2str(chanlisttmp) ']' ];
set(fig, 'userdata', userdata);
set(findobj(fig, 'tag', 'chanlist'), 'string', chanliststr);
end;
else
global ALLEEG EEG;
tmpanswer = inputdlg2({ 'Dataset index' }, 'Choose dataset', 1, { '' });
if ~isempty(tmpanswer),
tmpanswernum = round(str2num(tmpanswer{1}));
if ~isempty(tmpanswernum),
if tmpanswernum > 0 & tmpanswernum <= length(ALLEEG),
TMPEEG = ALLEEG(tmpanswernum);
tmpchans1 = TMPEEG.chanlocs;
if strcmpi(command, 'selectchan')
chanlist = pop_chansel( { tmpchans1.labels } );
else
chanlist = 1:length(TMPEEG.chanlocs); % use all channels
end
% look at what new channels are selected
tmpchans2 = EEG.chanlocs;
[tmpchanlist chaninds] = setdiff_bc( { tmpchans1(chanlist).labels }, { tmpchans2.labels } );
if ~isempty(tmpchanlist),
if length(chanlist) == length(TMPEEG.chanlocs)
userdata.chans = TMPEEG.chanlocs;
userdata.chanstr = [ 'ALLEEG(' tmpanswer{1} ').chanlocs' ];
else
userdata.chans = TMPEEG.chanlocs(chanlist(sort(chaninds)));
userdata.chanstr = [ 'ALLEEG(' tmpanswer{1} ').chanlocs([' num2str(chanlist(sort(chaninds))) '])' ];
end;
set(fig, 'userdata', userdata);
tmpchanlist(2,:) = { ' ' };
set(findobj(gcbf, 'tag', 'chanlist'), 'string', [ tmpchanlist{:} ]);
else
warndlg2('No new channels selected');
end;
else
warndlg2('Wrong index');
end;
end;
end;
end;
return;
end;
EEG = eeg_interp(EEG, bad_elec, method);
|
github
|
ZijingMao/baselineeegtest-master
|
pop_importepoch.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_importepoch.m
| 20,310 |
utf_8
|
9bb19bf2478e05dd8fa4a86f6e7ffc51
|
% pop_importepoch() - Export epoch and/or epoch event information to the event
% structure array of an EEG dataset. If the dataset is
% the only input, a window pops up to ask for the relevant
% parameter values.
% Usage:
% >> EEGOUT = pop_importepoch( EEG ); % pop-up window mode
% >> EEGOUT = pop_importepoch( EEG, filename, fieldlist, 'key', 'val', ...);
%
% Graphic interface:
% "Epoch file or array" - [edit box] enter epoch text file name. Use "Browse"
% button to browse for a file. If a file with the given name
% can not be found, the function search for a variable with
% this name in the global workspace. Command line
% equivalent: filename.
% "File input field ..." - [edit box] enter a name for each of the column in the
% text file. If columns names are defined in the text file,
% they cannnot be used and you must copy their names
% in this edit box (and skip the rows). One column name
% for each column must be provided. The keywords "type" and
% "latency" should not be used. Columns names can be
% separated by comas, quoted or not. Command line
% equivalent: fieldlist.
% "Field name(s) containing event latencies" - [edit box] enter columns name(s)
% containing latency information. It is not necessary to
% define a latency field for epoch information. All fields
% that contain latencies will be imported as different event
% types. For instance, if field 'RT' contains latencies,
% events of type 'RT' will be created with latencies given
% in the RT field. See notes. Command line
% equivalent: 'latencyfields'.
% "Field name(s) containing event durations" - [edit box] enter columns name(s)
% containing duration information. It is not necessary to
% define a latency field for epoch information, but if you
% do, a duration field (or 0) must be entered for each
% latency field you define. For instance if the latency fields
% are "'rt1' 'rt2'", then you must have duration fields
% such as "'dr1' 'dr2'". If duration is not defined for event
% latency 'tr1', you may enter "0 'rt2'". Command line
% equivalent: 'durationfields'.
% "Field name containing time locking event type(s)" - [edit box] if one column
% contain the epoch type, its name must be defined in the
% previous edit box and copied here. It is not necessary to
% define a type field for the time-locking event (TLE). By
% default it is defined as type ''TLE'' at time 0 for all
% epochs. Command line equivalent: 'typefield'.
% "Latency time unit rel. to seconds" - [edit box] specify the time unit for
% latency columns defined above. Command line
% equivalent: 'timeunit'.
% "Number of header lines to ignore" - [edit box] for some text files, the first
% rows do not contain epoch information and have to be
% skipped. Command line equivalent: 'headerlines'.
% "Remove old epoch and event info" - [checkbox] check this checkbox
% to remove any prior event or epoch information. Command
% line equivalent: 'clearevents'.
%
% Inputs:
% EEG - Input EEG dataset
% filename - Name of an ascii file with epoch and/or epoch event
% information organised in columns. ELSE, name of a Matlab
% variable with the same information (either a Matlab array
% or cell array).
% fieldlist - {cell array} Label of each column (data field) in the file.
%
% Optional inputs:
% 'typefield' - ['string'] Name of the field containing the type(s)
% of the epoch time-locking events (at time 0).
% By default, all the time-locking events are assigned
% type 'TLE' (for "time-locking event").
% 'latencyfields' - {cell array} Field names that contain the latency
% of an event. These fields are transferred into
% events whose type will be the same as the name of
% the latency field. (Ex: field RT -> type 'RT' events).
% 'durationfields' - {cell array} Field names that contain the duration
% of an event.
% 'timeunit' - [float] Optional unit for latencies relative to seconds.
% Ex: sec -> 1, msec -> 1e-3. Default: Assume latencies
% are in time points (relative to the time-zero time point
% in the epoch).
% 'headerlines' - [int] Number of header lines in the input file to ignore.
% {Default 0}.
% 'clearevents' - ['on'|'off'], 'on'-> clear the old event array.
% {Default 'on'}
%
% Output:
% EEGOUT - EEG dataset with modified event structure
%
% FAQ:
% 1) Why is this function so complex? This function can handle as many events
% per epochs as needed, and the information is stored in terms of events
% rather than epoch information, which requires some conversion.
% 2) Can I access epoch information later? The epoch information is stored in
% "EEG.event" and the information is stored in terms of events only. For
% user convenience the "EEG.epoch" structure is generated automatically
% from the event structure. See EEGLAB manual for more information.
%
% Authors: Arnaud Delorme & Scott Makeig, CNL/Salk Institute, 11 March 2002
%
% See also: eeglab()
% Copyright (C) 15 Feb 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% graphic interface INFOS
% 03/18/02 debugging variable passing - ad & lf
% 03/18/02 adding event updates and incremental calls -ad
% 03/25/02 adding default event description -ad
% 03/28/02 fixed latency calculation -ad
function [EEG, com] = pop_importepoch( EEG, filename, fieldlist, varargin);
com ='';
if nargin < 1
help pop_importepoch
return;
end;
if nargin < 2
geometry = { [ 1 1 1.86] [1] [1 0.66] [2.5 1 0.6] [2.5 1 0.6] [2.5 1 0.6] [1] [2 0.5 0.5] [2 0.5 0.5] [2 0.17 0.86]};
commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
'if filename ~=0,' ...
' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ...
'end;' ...
'clear filename filepath tagtest;' ];
helpstrtype = ['It is not necessary to define a type field for the time-locking event.' 10 ...
'By default it is defined as type ''TLE'' at time 0 for all epochs'];
helpstrlat = ['It is not necessary to define a latency field for epoch information.' 10 ...
'All fields that contain latencies will be imported as different event types.' 10 ...
'For instance, if field ''RT'' contains latencies, events of type ''RT''' 10 ...
'will be created with latencies given in the RT field'];
helpstrdur = ['It is not necessary to define a duration for each event (default is 0).' 10 ...
'However if a duration is defined, a corresponding latency must be defined too' 10 ...
'(in the edit box above). For each latency field, you have define a duration field.' 10 ...
'if no duration field is defined for a specific event latency, enter ''0'' in place of the duration field' ];
uilist = { ...
{ 'Style', 'text', 'string', 'Epoch file or array', 'horizontalalignment', 'right', 'fontweight', 'bold' }, ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''globfile'';' commandload ] }, ...
{ 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'globfile' }, ...
{ }...
{ 'Style', 'text', 'string', 'File input field (col.) names', 'fontweight', 'bold' }, { 'Style', 'edit', 'string', '' }, ...
{ 'Style', 'text', 'string', ' Field name(s) containing event latencies', 'horizontalalignment', 'right', ...
'fontweight', 'bold', 'tooltipstring', helpstrlat }, ...
{ 'Style', 'edit', 'string', '' }, ...
{ 'Style', 'text', 'string', '(Ex: RT)', 'tooltipstring', helpstrlat }, ...
{ 'Style', 'text', 'string', ' Field name(s) containing event durations', 'horizontalalignment', 'right', ...
'fontweight', 'bold', 'tooltipstring', helpstrdur }, ...
{ 'Style', 'edit', 'string', '' }, ...
{ 'Style', 'text', 'string', 'NOTE', 'tooltipstring', helpstrdur }, ...
{ 'Style', 'text', 'string', ' Field name containing time-locking event type(s)', 'horizontalalignment', 'right', ...
'tooltipstring', helpstrtype }, ...
{ 'Style', 'edit', 'string', '' }, ...
{ 'Style', 'text', 'string', 'NOTE', 'tooltipstring', helpstrtype }, ...
{ } ...
{ 'Style', 'text', 'string', 'Latency time unit rel. to seconds. Ex: ms -> 1E-3 (NaN -> samples)', 'horizontalalignment', 'left' }, { 'Style', 'edit', 'string', '1' }, { } ...
{ 'Style', 'text', 'string', 'Number of file header lines to ignore', 'horizontalalignment', 'left' }, { 'Style', 'edit', 'string', '0' }, { },...
{ 'Style', 'text', 'string', 'Remove old epoch and event info (set = yes)', 'horizontalalignment', 'left' }, { 'Style', 'checkbox', 'value', isempty(EEG.event) }, { } };
result = inputgui( geometry, uilist, 'pophelp(''pop_importepoch'');', 'Import epoch info (data epochs only) -- pop_importepoch()');
if length(result) == 0, return; end;
filename = result{1};
fieldlist = parsetxt( result{2} );
options = {};
if ~isempty( result{3}), options = { options{:} 'latencyfields' parsetxt( result{3} ) }; end;
if ~isempty( result{4}), options = { options{:} 'durationfields' parsetxt( result{4} ) }; end;
if ~isempty( result{5}), options = { options{:} 'typefield' result{5} }; end;
if ~isempty( result{6}), options = { options{:} 'timeunit' eval(result{6}) }; end;
if ~isempty( result{7}), options = { options{:} 'headerlines' eval(result{7}) }; end;
if ~result{8}, options = { options{:} 'clearevents' 'off'}; end;
else
if ~isempty(varargin) & ~isstr(varargin{1})
% old call compatibility
options = { 'latencyfields' varargin{1} };
if nargin > 4
options = { options{:} 'timeunit' varargin{2} };
end;
if nargin > 5
options = { options{:} 'headerlines' varargin{3} };
end;
if nargin > 6
options = { options{:} 'clearevents' fastif(varargin{4}, 'on', 'off') };
end;
else
options = varargin;
end;
end;
g = finputcheck( options, { 'typefield' 'string' [] ''; ...
'latencyfields' 'cell' [] {}; ...
'durationfields' 'cell' [] {}; ...
'timeunit' 'real' [0 Inf] 1/EEG.srate; ...
'headerlines' 'integer' [0 Inf] 0; ...
'clearevents' 'string' {'on';'off'} 'on'}, 'pop_importepoch');
if isstr(g), error(g); end;
% check duration field
% --------------------
if ~isempty(g.durationfields)
if length(g.durationfields) ~= length(g.latencyfields)
error( [ 'If duration field(s) are defined, their must be as many duration' 10 ...
'fields as there are latency fields (or enter 0 instead of a field for no duration' ]);
end;
else
for index = 1:length(g.latencyfields)
g.durationfields{index} = 0;
end;
end;
% convert filename
% ----------------
fprintf('Pop_importepoch: Loading file or array...\n');
if isstr(filename)
% check filename
% --------------
if exist(filename) == 2 & evalin('base', ['exist(''' filename ''')']) == 1
disp('Pop_importepoch WARNING: FILE AND ARRAY WITH THE SAME NAME, LOADING FILE');
end;
values = load_file_or_array( filename, g.headerlines );
else
values = filename;
filename = inputname(2);
end;
% check parameters
% ----------------
if size(values,1) < size(values,2), values = values'; end;
if length(fieldlist) ~= size(values,2)
values = values';
if length(fieldlist) ~= size(values,2)
error('There must be as many field names as there are columsn in the file/array');
end;
end;
if ~iscell(fieldlist)
otherfieldlist = { fieldlist };
fieldlist = { fieldlist };
end;
otherfieldlist = setdiff_bc( fieldlist, g.latencyfields);
otherfieldlist = setdiff_bc( otherfieldlist, g.typefield);
for index = 1:length(g.durationfields)
if isstr(g.durationfields{index})
otherfieldlist = setdiff_bc( otherfieldlist, g.durationfields{index});
end;
end;
if size(values,1) ~= EEG.trials
error( [ 'Pop_importepoch() error: the number of rows in the input file/array does' 10 ...
'not match the number of trials. Maybe you forgot to specify the file header length?' ]);
end;
% create epoch array info
% -----------------------
if iscell( values )
for indexfield = 1:length(fieldlist)
for index=1:EEG.trials
eval( ['EEG.epoch(index).' fieldlist{ indexfield } '=values{ index, indexfield };'] );
end;
end;
else
for indexfield = 1:length(fieldlist)
for index=1:EEG.trials
eval( ['EEG.epoch(index).' fieldlist{ indexfield } '=values( index, indexfield);'] );
end;
end;
end;
if isempty( EEG.epoch )
error('Pop_importepoch: cannot process empty epoch structure');
end;
epochfield = fieldnames( EEG.epoch );
% determine the name of the non latency fields
% --------------------------------------------
tmpfieldname = {};
for index = 1:length(otherfieldlist)
if isempty(strmatch( otherfieldlist{index}, epochfield ))
error(['Pop_importepoch: field ''' otherfieldlist{index} ''' not found']);
end;
switch otherfieldlist{index}
case {'type' 'latency'}, tmpfieldname{index} = [ 'epoch' otherfieldlist{index} ];
otherwise, tmpfieldname{index} = otherfieldlist{index};
end;
end;
if ~isempty(EEG.event)
if ~isfield(EEG.event, 'epoch')
g.clearevents = 'on';
disp('Pop_importepoch: cannot add events to a non-epoch event structure, erasing old epoch structure');
end;
end;
if strcmpi(g.clearevents, 'on')
if ~isempty(EEG.event)
fprintf('Pop_importepoch: deleting old events if any\n');
end;
EEG.event = [];
else
fprintf('Pop_importepoch: appending new events to the existing event array\n');
end;
% add time locking event fields
% -----------------------------
if EEG.xmin <= 0
fprintf('Pop_importepoch: adding automatically Time Locking Event (TLE) events\n');
if ~isempty(g.typefield)
if isempty(strmatch( g.typefield, epochfield ))
error(['Pop_importepoch: type field ''' g.typefield ''' not found']);
end;
end;
for trial = 1:EEG.trials
EEG.event(end+1).epoch = trial;
if ~isempty(g.typefield)
eval( ['EEG.event(end).type = EEG.epoch(trial).' g.typefield ';'] );
else
EEG.event(end).type = 'TLE';
end;
EEG.event(end).latency = -EEG.xmin*EEG.srate+1+(trial-1)*EEG.pnts;
EEG.event(end).duration = 0;
end;
end;
% add latency fields
% ------------------
for index = 1:length(g.latencyfields)
if isempty(strmatch( g.latencyfields{index}, epochfield ))
error(['Pop_importepoch: latency field ''' g.latencyfields{index} ''' not found']);
end;
for trials = 1:EEG.trials
EEG.event(end+1).epoch = trials;
EEG.event(end).type = g.latencyfields{index};
EEG.event(end).latency = (getfield(EEG.epoch(trials), g.latencyfields{index})*g.timeunit-EEG.xmin)*EEG.srate+1+(trials-1)*EEG.pnts;
if g.durationfields{index} ~= 0 & g.durationfields{index} ~= '0'
EEG.event(end).duration = getfield(EEG.epoch(trials), g.durationfields{index})*g.timeunit*EEG.srate;
else
EEG.event(end).duration = 0;
end;
end;
end;
% add non latency fields
% ----------------------
if ~isfield(EEG.event, 'epoch') % no events added yet
for trial = 1:EEG.trials
EEG.event(end+1).epoch = trial;
end;
end;
for indexevent = 1:length(EEG.event)
if ~isempty( EEG.event(indexevent).epoch )
for index2 = 1:length(tmpfieldname)
eval( ['EEG.event(indexevent).' tmpfieldname{index2} ' = EEG.epoch(EEG.event(indexevent).epoch).' otherfieldlist{index2} ';' ] );
end;
end;
end;
% adding desciption to the fields
% -------------------------------
if ~isfield(EEG, 'eventdescription' ) | isempty( EEG.eventdescription )
allfields = fieldnames(EEG.event);
EEG.eventdescription{strmatch('epoch', allfields, 'exact')} = 'Epoch number';
if ~isempty(strmatch('type', allfields)), EEG.eventdescription{strmatch('type', allfields)} = 'Event type'; end;
if ~isempty(strmatch('latency', allfields)), EEG.eventdescription{strmatch('latency', allfields)} = 'Event latency'; end;
if ~isempty(strmatch('duration', allfields)), EEG.eventdescription{strmatch('duration', allfields)} = 'Event duration'; end;
end;
% checking and updating events
% ----------------------------
EEG = pop_editeventvals( EEG, 'sort', { 'epoch', 0 } ); % resort fields
EEG = eeg_checkset(EEG, 'eventconsistency');
EEG = eeg_checkset(EEG, 'makeur');
% generate the output command
% ---------------------------
if isempty(filename) & nargout == 2
disp('Pop_importepoch: cannot generate command string'); return;
else
com = sprintf('%s = pop_importepoch( %s, ''%s'', %s);', inputname(1), inputname(1), ...
filename, vararg2str( { fieldlist options{:} }));
end;
% interpret the variable name
% ---------------------------
function array = load_file_or_array( varname, skipline );
if exist( varname ) == 2
if exist(varname) ~= 2, error( [ 'Set error: no filename ' varname ] ); end;
fid=fopen(varname,'r','ieee-le');
if fid<0, error( ['Set error: file ''' varname ''' found but error while opening file'] ); end;
for index=1:skipline fgetl(fid); end; % skip lines ---------
inputline = fgetl(fid);
linenb = 1;
while inputline~=-1
colnb = 1;
while ~isempty(deblank(inputline))
[tmp inputline] = strtok(inputline);
tmp2 = str2num( tmp );
if isempty( tmp2 ), array{linenb, colnb} = tmp;
else array{linenb, colnb} = tmp2;
end;
colnb = colnb+1;
end;
inputline = fgetl(fid);
linenb = linenb +1;
end;
fclose(fid);
else % variable in the global workspace
% --------------------------
array = evalin('base', varname);
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_writeeeg.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_writeeeg.m
| 2,828 |
utf_8
|
f5cff379a7a655220154a4cc5234452e
|
% pop_writeeeg - write EEGLAB dataset to disk in EDF/GDF or BDF format
%
% pop_writeeeg( EEG ) % pops up a window
% pop_writeeeg( EEG, filename, 'key', 'val' )
%
% Inputs:
% EEG - EEGLAB dataset
% filename - [string] filename
%
% Optional keys (same as writeeeg):
% 'TYPE' - ['GDF'|'EDF'|'BDF'|'CFWB'|'CNT'] file format for writing
% default is 'EDF'.
% See writeeeg for more information
%
% Author: Arnaud Delorme, SCCN, UCSD/CERCO, 2009
% Based on BIOSIG, sopen and swrite
% Copyright (C) 22 March 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [command] = pop_writeeeg(EEG, filename, varargin);
command = '';
if nargin < 2
if EEG.trials > 1
res = questdlg2( [ 'This dataset contains data epochs.' 10 'Do you want to export the concatenated' 10 'data epochs?' ], '', 'No', 'Yes', 'Yes');
if strcmpi(res, 'No')
return;
end;
end;
% ask user
[filename, filepath] = uiputfile('*.*', 'Enter a file name -- pop_writeeeg()');
if filename == 0 return; end;
filename = fullfile(filepath,filename);
% file format
% -----------
fileformats = { 'EDF' 'GDF' 'BDF' };
uilist = { { 'style' 'text' 'String' 'File format' } ...
{ 'style' 'listbox' 'string' strvcat(fileformats) 'value' 1 } };
geom = [1 1];
result = inputgui( 'geometry', geom, 'uilist', uilist, 'helpcom', 'pophelp(''pop_writeeeg'')', ...
'title', 'Write data using BIOSIG -- pop_writeeeg()', 'geomvert', [1 2.5]);
if length(result) == 0 return; end;
options = { 'TYPE' fileformats{result{1}} };
else
options = varargin;
end;
warning('off', 'MATLAB:intConvertNonIntVal');
if ~isempty(EEG.chanlocs)
tmpchanlocs = EEG.chanlocs;
writeeeg(filename, EEG.data(:,:), EEG.srate, 'label', { tmpchanlocs.labels }, 'EVENT', EEG.event, options{:});
else
writeeeg(filename, EEG.data(:,:), EEG.srate, 'EVENT', EEG.event, options{:});
end;
warning('on', 'MATLAB:intConvertNonIntVal');
command = sprintf('pop_writeeeg(EEG, ''%s'', %s);', filename, vararg2str(options));
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_chancenter.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_chancenter.m
| 4,180 |
utf_8
|
83264735d5a2740c1458fc2b72f215f5
|
% pop_chancenter() - recenter cartesian X,Y,Z channel coordinates
%
% Usage:
% >> chanlocs = pop_chancenter(chanlocs); % pop up interactive window
% >> [chanlocs centerloc] = pop_chancenter(chanlocs, center, omitchan);
%
% Inputs:
% chanlocs = eeglab channel location structure (see readlocs())
% center = [X Y Z] known center different from [0 0 0]
% [] will optimize the center location according
% to the best sphere. Default is [0 0 0].
% omitchan = indices of channel to omit when computing center
%
% Outputs:
% chanlocs = updated channel location structure
% centerloc = 3-D location of the new center (in the old coordinate
% frame).
%
% Author: Arnaud Delorme, SCCN/INC/UCSD, La Jolla, Feb 2004
%
% See also: chancenter(), spherror(), cart2topo()
% Copyright (C) 2004, Arnaud Delorme, SCCN/INC/UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [ chanlocs, newcenter, com] = pop_chancenter( chanlocs, center, omitchans)
optim = 0;
if nargin<1
help pop_chancenter
return;
end;
com = '';
newcenter = [];
if nargin < 3
omitchans = [];
end;
if nargin < 2
cb_browse = [ 'tmpchans = get(gcbf, ''userdata'');' ...
'set(findobj(gcbf, ''tag'', ''chans''), ''string'', ' ...
'int2str(pop_chansel( { tmpchans.labels } )));' ];
cb_opt = [ 'if get(gcbo, ''value''), ' ...
' set(findobj(gcbf, ''tag'', ''center''), ''enable'', ''off'');' ...
'else,' ...
' set(findobj(gcbf, ''tag'', ''center''), ''enable'', ''on'');' ...
'end;' ];
geometry = { [1.3 0.28 1 1] [1] [1] [2 1] };
uilist = { { 'Style', 'text', 'string', 'Optimize center location', 'fontweight', 'bold' } ...
{ 'Style', 'checkbox', 'value', 1 'callback' cb_opt } ...
{ 'Style', 'text', 'string', 'or specify center', 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', '0 0 0', 'tag' 'center' 'enable' 'off' } ...
{ } ...
{ 'Style', 'text', 'string', 'Channel indices to ignore for best-sphere matching' } ...
{ 'Style', 'edit', 'string', '', 'tag', 'chans' } ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', cb_browse } };
results = inputgui( geometry, uilist, 'pophelp(''pop_chancenter'');', ...
'Convert channel locations -- pop_chancenter()', chanlocs );
if isempty(results), return; end;
if results{1}
center = [];
else
center = eval( [ '[' results{2} ']' ] );
end;
if ~isempty(results{3})
omitchans = eval( [ '[' results{3} ']' ] );
end;
end;
% remove channels
% ---------------
c = setdiff_bc([1:length(chanlocs)], union(omitchans, find(cellfun('isempty', { chanlocs.theta }))));
% optimize center
% ---------------
[X Y Z newcenter]= chancenter( [ chanlocs(c).X ]', [ chanlocs(c).Y ]', [ chanlocs(c).Z ]', center);
for index = 1:length(c)
chanlocs(c(index)).X = X(index);
chanlocs(c(index)).Y = Y(index);
chanlocs(c(index)).Z = Z(index);
end;
disp('Note: automatically convert XYZ coordinates to spherical and polar');
chanlocs = convertlocs(chanlocs, 'cart2all');
if ~isempty(omitchans)
disp('Important warning: the location of omitted channels has not been modified');
end;
com = sprintf('%s = pop_chancenter( %s, %s);', inputname(1), inputname(1), vararg2str({ center omitchans }));
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_rejsuperpose.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_rejsuperpose.m
| 4,163 |
utf_8
|
31ddb44aab055e8f1ae1b9307ade5b9b
|
% eeg_rejsuperpose() - superpose rejections of a EEG dataset.
%
% Usage:
% >> EEGOUT = eeg_rejsuperpose( EEGIN, typerej, Rmanual, Rthres, ...
% Rconst, Rent, Rkurt, Rfreq, Rothertype);
%
% Inputs:
% EEGIN - input dataset
% typerej - type of rejection (1=raw data; 0=ica).
% Rmanual - include manual rejection (0|1).
% Rthres - include threshold rejection (0|1).
% Rconst - include rejection of constant activity (0|1).
% Rent - include entropy rejection (0|1).
% Rkurt - include kurtosis rejection (0|1).
% Rfreq - include frequcy based rejection (0|1).
% Rothertype - include manual rejection (0|1).
%
% Outputs:
% EEGOUT - with rejglobal and rejglobalE fields updated
%
% See also: eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, com] = eeg_rejsuperpose( EEG, typerej, Rmanual, Rthres, Rconst, ...
Rent, Rkurt, Rfreq, Rothertype);
if nargin < 9
help eeg_rejsuperpose;
return;
end;
typerej = ~typerej;
rejglobal = zeros( 1, EEG.trials);
if typerej == 0
rejglobalE = zeros( EEG.nbchan, EEG.trials);
else
rejglobalE = zeros( size(EEG.icaweights,1), EEG.trials);
end
if typerej == 0 | Rothertype
if Rmanual
rejglobal = rejarray( rejglobal, EEG.reject.rejmanual); % see bottom for the
rejglobalE = rejarray( rejglobalE, EEG.reject.rejmanualE); % function rejarray
end;
if Rthres
rejglobal = rejarray( rejglobal, EEG.reject.rejthresh);
rejglobalE = rejarray( rejglobalE, EEG.reject.rejthreshE);
end;
if Rfreq
rejglobal = rejarray( rejglobal, EEG.reject.rejfreq);
rejglobalE = rejarray( rejglobalE, EEG.reject.rejfreqE);
end;
if Rconst
rejglobal = rejarray( rejglobal, EEG.reject.rejconst);
rejglobalE = rejarray( rejglobalE, EEG.reject.rejconstE);
end;
if Rent
rejglobal = rejarray( rejglobal, EEG.reject.rejjp);
rejglobalE = rejarray( rejglobalE, EEG.reject.rejjpE);
end;
if Rkurt
rejglobal = rejarray( rejglobal, EEG.reject.rejkurt);
rejglobalE = rejarray( rejglobalE, EEG.reject.rejkurtE);
end;
end;
% ---------------
if typerej == 1 | Rothertype
if Rmanual
rejglobal = rejarray( rejglobal, EEG.reject.icarejmanual);
rejglobalE = rejarray( rejglobalE, EEG.reject.icarejmanualE);
end;
if Rthres
rejglobal = rejarray( rejglobal, EEG.reject.icarejthresh);
rejglobalE = rejarray( rejglobalE, EEG.reject.icarejthreshE);
end;
if Rfreq
rejglobal = rejarray( rejglobal, EEG.reject.icarejfreq);
rejglobalE = rejarray( rejglobalE, EEG.reject.icarejfreqE);
end;
if Rconst
rejglobal = rejarray( rejglobal, EEG.reject.icarejconst);
rejglobalE = rejarray( rejglobalE, EEG.reject.icarejconstE);
end;
if Rent
rejglobal = rejarray( rejglobal, EEG.reject.icarejjp);
rejglobalE = rejarray( rejglobalE, EEG.reject.icarejjpE);
end;
if Rkurt
rejglobal = rejarray( rejglobal, EEG.reject.icarejkurt);
rejglobalE = rejarray( rejglobalE, EEG.reject.icarejkurtE);
end;
end;
EEG.reject.rejglobal = rejglobal;
EEG.reject.rejglobalE = rejglobalE;
com =sprintf('%s = eeg_rejsuperpose( %s, %d, %d, %d, %d, %d, %d, %d, %d);', ...
inputname(1), inputname(1), ~typerej, Rmanual, Rthres, Rconst, Rent, Rkurt, Rfreq, Rothertype);
return;
% subfunction rejecting an array ------
function dest = rejarray( dest, ori)
if isempty(dest)
dest = ori;
elseif ~isempty(ori)
dest = dest | ori;
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_rejcont.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_rejcont.m
| 14,137 |
utf_8
|
1bcb135e0cc0f260852867027268020b
|
% pop_rejcont() - reject continuous portions of data based on spectrum
% thresholding. First, contiguous data epochs are extracted
% and a standard spectrum thresholding algorithm is
% applied. Regions of contiguous epochs larger than a
% specified size are then labeled as artifactual.
%
% Usage:
% >> pop_rejcont( INEEG ) % pop-up interative window mode
% >> [OUTEEG, selectedregions] = pop_rejcont( INEEG, 'key', 'val');
%
% Inputs:
% INEEG - input dataset
%
% Optional inputs:
% 'elecrange' - [integer array] electrode indices {Default: all electrodes}
% 'epochlength' - [float] epoch length in seconds {Default: 0.5 s}
% 'overlap' - [float] epoch overlap in seconds {Default: 0.25 s}
% 'freqlimit' - [min max] frequency range too consider for thresholding
% Default is [35 128] Hz.
% 'threshold' - [float] frequency upper threshold in dB {Default: 10}
% 'contiguous' - [integer] number of contiguous epochs necessary to
% label a region as artifactual {Default: 4 }
% 'addlength' - [float] once a region of contiguous epochs has been labeled
% as artifact, additional trailing neighboring regions on
% each side may also be added {Default: 0.25 s}
% 'eegplot' - ['on'|'off'] plot rejected portions of data in a eegplot
% window. Default is 'off'.
% 'onlyreturnselection' - ['on'|'off'] this option when set to 'on' only
% return the selected regions and does not remove them
% from the datasets. This allow to perform quick
% optimization of the rejected portions of data.
% 'precompstruct' - [struct] structure containing precomputed spectrum (see
% Outputs) to be used instead of computing the spectrum.
% 'verbose' - ['on'|'off'] display information. Default is 'off'.
% 'taper' - ['none'|'hamming'] taper to use before FFT. Default is
% 'none' for backward compatibility but 'hamming' is
% recommended.
%
% Outputs:
% OUTEEG - output dataset with updated joint probability array
% selectedregions - frames indices of rejected electrodes. Array of n x 2
% n being the number of regions and 2 for the beginning
% and end of each region.
% precompstruct - structure containing precomputed data. This structure
% contains the spectrum, the frequencies and the EEGLAB
% dataset used as input with epochs extracted.
%
% Author: Arnaud Delorme, CERCO, UPS/CNRS, 2009-
%
% Example:
% EEG = pop_rejcont(EEG, 'elecrange',[1:32] ,'freqlimit',[20 40] ,'threshold',...
% 10,'epochlength',0.5,'contiguous',4,'addlength',0.25, 'taper', 'hamming');
%
% See also: eegthresh()
% Copyright (C) 2009 Arnaud Delorme, CERCO, UPS/CNRS
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG selectedregions precompstruct com ] = pop_rejcont(EEG, varargin);
com = '';
if nargin < 1
help pop_rejcont;
return;
end;
if nargin < 2
firstelec = 'EXG1'; % first non EEG channel
% take all scalp electrodes
% -------------------------
if ~isempty(EEG.chanlocs)
tmpchanlocs = EEG.chanlocs;
indelec = strmatch( firstelec, { tmpchanlocs.labels });
if isempty(indelec), elecrange = 1:EEG.nbchan;
else elecrange = 1:(indelec-1);
end;
else
elecrange = 1:EEG.nbchan;
end;
elecrange = deblank(vararg2str(elecrange));
%elecrange = elecrange(2:end-1);
% promptstr = { 'Channel range' ...
% 'Frequency range (Hz)' ...
% 'Frequency threshold in dB' ...
% 'Epoch segment length (s)' ...
% 'Minimum number of contiguous epochs' ...
% 'Add trails before and after regions (s)' ...
% };
% initstr = { elecrange '20 40' '10' '0.5' '4' '0.25' };
% result = inputdlg2(promptstr, 'Reject portions of continuous data - pop_rejcont', 1, initstr);
uilist = { { 'style' 'text' 'string' 'Channel range' } ...
{ 'style' 'edit' 'string' elecrange } ...
{ 'style' 'text' 'string' 'Frequency range (Hz)' } ...
{ 'style' 'edit' 'string' '20 40' } ...
{ 'style' 'text' 'string' 'Frequency threshold in dB' } ...
{ 'style' 'edit' 'string' '10' } ...
{ 'style' 'text' 'string' 'Epoch segment length (s)' } ...
{ 'style' 'edit' 'string' '0.5' } ...
{ 'style' 'text' 'string' 'Minimum number of contiguous epochs' } ...
{ 'style' 'edit' 'string' '4' } ...
{ 'style' 'text' 'string' 'Add trails before and after regions (s)' } ...
{ 'style' 'edit' 'string' '0.25' } ...
{ 'style' 'text' 'string' 'Use hanning window before computing FFT' } ...
{ 'style' 'checkbox' 'string' '' 'value' 1 } ...
};
geom = { [2 1] [2 1] [2 1] [2 1] [2 1] [2 1] [2 1] };
result = inputgui('uilist', uilist, 'geometry', geom);
if length( result ) == 0 return; end;
options = { 'elecrange' str2num(result{1}) ...
'freqlimit' str2num(result{2}) ...
'threshold' str2double(result{3}) ...
'epochlength' str2double(result{4}) ...
'contiguous' str2double(result{5}) ...
'addlength' str2double(result{6}) ...
'taper' fastif(result{7}, 'hamming', 'none') };
else
options = varargin;
end;
opt = finputcheck(options, { 'threshold' { 'real';'cell' } [] 10;
'freqlimit' { 'real';'cell' } [] [35 128];
'elecrange' 'real' [] [1:EEG.nbchan];
'rejectori' 'real' [] [];
'contiguous' 'real' [] 4;
'addlength' 'real' [] 0.25;
'precompstruct' 'struct' [] struct([]);
'eegplot' 'string' { 'on';'off' } 'off';
'onlyreturnselection' 'string' { 'on';'off' } 'off';
'verbose' 'string' { 'on';'off' } 'on';
'taper' 'string' { 'none' 'hamming' } 'none';
'overlap' 'real' [] 0.25;
'epochlength' 'real' [] 0.5 }, 'pop_rejcont');
if isstr(opt), error(opt); end;
if ~iscell(opt.threshold) && length(opt.threshold) == 2 && ...
iscell(opt.freqlimit) && length(opt.freqlimit) == 2
opt.threshold = { opt.threshold(1) opt.threshold(2) };
end;
if ~iscell(opt.threshold), opt.threshold = { opt.threshold }; end;
if ~iscell(opt.freqlimit), opt.freqlimit = { opt.freqlimit }; end;
%EEG.event = [];
grouplen = opt.contiguous/2*opt.epochlength*EEG.srate+1; % maximum number of points for grouping regions
color = [ 0 0.9 0]; % color of rejection window
NEWEEG = EEG;
if isempty(opt.precompstruct)
% compute power spectrum
% ----------------------
% average reference
% NEWEEG.data(opt.elecrange,:) = NEWEEG.data(opt.elecrange,:)-repmat(mean(NEWEEG.data(opt.elecrange,:),1), [length(opt.elecrange) 1]);
% only keep boundary events
% -------------------------
tmpevent = NEWEEG.event;
if ~isempty(tmpevent)
if isnumeric( tmpevent(1).type )
NEWEEG.event = [];
else
boundEvent = strmatch('boundary', { tmpevent.type }, 'exact');
NEWEEG.event = NEWEEG.event(boundEvent);
end;
end;
[TMPNEWEEG] = eeg_regepochs(NEWEEG, opt.overlap, [0 opt.epochlength], NaN);
%[TMPNEWEEG indices] = pop_rejspec(TMPNEWEEG, 1, [1:64], -100, 15, 30, 45, 0, 0);
%rejepoch = find(indices);
tmpdata = TMPNEWEEG.data;
if strcmpi(opt.taper, 'hamming'),
tmpdata = bsxfun(@times, tmpdata, hamming(size(TMPNEWEEG.data,2))');
end;
tmp = fft(tmpdata, [], 2);
freqs = linspace(0, TMPNEWEEG.srate/2, size(tmp,2)/2);
freqspectrum = freqs(2:end); % remove DC (match the output of PSD)
tmp = tmp(:,2:size(tmp,2)/2,:);
warning('off', 'MATLAB:log:logOfZero');
tmpspec = 10*log10(abs(tmp).^2);
warning('on', 'MATLAB:log:logOfZero');
tmpspec = tmpspec - repmat( mean(tmpspec,3), [1 1 TMPNEWEEG.trials]);
specdata = tmpspec;
% compute mean spectrum
% ---------------------
meanspectrum = nan_mean(specdata(opt.elecrange, :, :), 1);
precompstruct.spec = meanspectrum;
precompstruct.freqs = freqspectrum;
precompstruct.EEG = TMPNEWEEG;
else
meanspectrum = opt.precompstruct.spec;
freqspectrum = opt.precompstruct.freqs;
TMPNEWEEG = opt.precompstruct.EEG;
precompstruct = opt.precompstruct;
end;
% apply threshold to average of all electrodes
% --------------------------------------------
rejepoch = [];
for iReject = 1:length(opt.threshold)
threshold = opt.threshold{iReject};
freqLim = opt.freqlimit{iReject};
if length(threshold) == 1, threshold = [ -100 threshold ]; end;
[I1 tmpRejEpoch NS Erej] = eegthresh( meanspectrum, size(meanspectrum,2), 1, threshold(1), threshold(2), [freqspectrum(1) freqspectrum(end)], freqLim(1), freqLim(2));
rejepoch = union_bc(rejepoch, tmpRejEpoch);
if strcmpi(opt.verbose, 'on')
fprintf('%d regions selected for rejection, threshold %3.2f-%3.2f dB, frequency limits %3.1f-%3.1f\n', length(tmpRejEpoch), threshold(1), threshold(2), freqLim(1), freqLim(2));
end;
end;
% build the winrej array for eegplot
% ----------------------------------
winrej = [];
if ~isempty(find(cellfun(@isempty, { TMPNEWEEG.event.epoch }) == 1))
error('Some events are not associated with any epoch');
end;
tmpevent = TMPNEWEEG.event;
allepoch = [ tmpevent.epoch ];
if ~isempty(rejepoch)
for index = 1:length(rejepoch)
eventepoch = find( rejepoch(index) == allepoch );
if strcmpi(TMPNEWEEG.event(eventepoch(1)).type, 'X')
urevent = TMPNEWEEG.event(eventepoch(1)).urevent;
lat = TMPNEWEEG.urevent(urevent).latency;
winrej = [ winrej; lat lat+opt.epochlength*TMPNEWEEG.srate-1 color ]; %Erej(:,index)'];
else
error('Wrong type for epoch');
end;
end;
winrej(:,6:6+length(opt.elecrange)-1) = 0;
end;
% remove isolated regions and merge others
% ----------------------------------------
merged = 0;
isolated = 0;
for index = size(winrej,1):-1:1
if size(winrej,1) >= index && winrej(index,2) - winrej(index,1) > grouplen, winrej(index,:) = []; isolated = isolated + 1;
elseif index == 1 && size(winrej,1) > 1 && winrej(index+1,1) - winrej(index,2) > grouplen, winrej(index,:) = []; isolated = isolated + 1;
elseif index == size(winrej,1) && size(winrej,1) > 1 && winrej(index,1) - winrej(index-1,2) > grouplen, winrej(index,:) = []; isolated = isolated + 1;
elseif index > 1 && size(winrej,1) > 1 && index < size(winrej,1) && winrej(index+1,1) - winrej(index,2) > grouplen && ...
winrej(index,1) - winrej(index-1,2) > grouplen
winrej(index,:) = [];
isolated = isolated + 1;
elseif index < size(winrej,1) && size(winrej,1) > 1 && winrej(index+1,1) - winrej(index,2) <= grouplen
winrej(index,2) = winrej(index+1,2);
winrej(index+1,:) = [];
merged = merged + 1;
end;
end;
if strcmpi(opt.verbose, 'on')
fprintf('%d regions merged\n', merged);
fprintf('%d regions removed\n', isolated);
end;
% add time before and after each region
% -------------------------------------
for index = 1:size(winrej,1)
winrej(index,1) = max(1, winrej(index,1)-opt.addlength*EEG.srate);
winrej(index,2) = min(EEG.pnts, winrej(index,2)+opt.addlength*EEG.srate);
end;
% plot result
% -----------
if ~isempty(winrej)
selectedregions = winrej(:,1:2);
if strcmpi(opt.onlyreturnselection, 'off')
% merge with initial regions
if ~isempty(opt.rejectori)
winrej(:,3) = 1; % color
for iRow = 1:size(opt.rejectori,1)
winrej(end+1,1:2) = opt.rejectori(iRow,:);
winrej(end ,4) = 1; % color
winrej(end ,5) = 1; % color
end;
end;
command = '[EEG LASTCOM] = pop_select(EEG, ''nopoint'', TMPREJ(:,1:2)); eegh(LASTCOM); [ALLEEG EEG CURRENTSET LASTCOM] = pop_newset(ALLEEG, EEG, CURRENTSET, ''study'', ~isempty(STUDY)+0); eegh(LASTCOM); eeglab redraw';
if nargin < 2 || strcmpi(opt.eegplot, 'on')
eegplot(NEWEEG.data(opt.elecrange,:), 'srate', NEWEEG.srate, 'winrej', winrej, 'command', command, 'events', EEG.event, 'winlength', 50);
disp('Green is overlap');
disp('Light blue is ORIGINAL rejection');
disp('Yellow is AUTOMATIC rejection');
else
NEWEEG = pop_select(EEG, 'nopoint', round(selectedregions));
end;
EEG = NEWEEG;
else
EEG = [];
end;
else
selectedregions = [];
if strcmpi(opt.verbose, 'on')
disp('No region removed');
end;
end;
if nargout > 3
com = sprintf('EEG = pop_rejcont(EEG, %s);', vararg2str(options));
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_chansel.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_chansel.m
| 5,372 |
utf_8
|
4773a5a96563eba18577995430d93045
|
% pop_chansel() - pop up a graphic interface to select channels
%
% Usage:
% >> [chanlist] = pop_chansel(chanstruct); % a window pops up
% >> [chanlist strchannames cellchannames] = ...
% pop_chansel(chanstruct, 'key', 'val', ...);
%
% Inputs:
% chanstruct - channel structure. See readlocs()
%
% Optional input:
% 'withindex' - ['on'|'off'] add index to each entry. May also a be
% an array of indices
% 'select' - selection of channel. Can take as input all the
% outputs of this function.
% 'selectionmode' - selection mode 'multiple' or 'single'. See listdlg2().
%
% Output:
% chanlist - indices of selected channels
% strchannames - names of selected channel names in a concatenated string
% (channel names are separated by space characters)
% cellchannames - names of selected channel names in a cell array
%
% Author: Arnaud Delorme, CNL / Salk Institute, 3 March 2003
% Copyright (C) 3 March 2003 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [chanlist,chanliststr, allchanstr] = pop_chansel(chans, varargin);
if nargin < 1
help pop_chansel;
return;
end;
if isempty(chans), disp('Empty input'); return; end;
if isnumeric(chans),
for c = 1:length(chans)
newchans{c} = num2str(chans(c));
end;
chans = newchans;
end;
chanlist = [];
chanliststr = {};
allchanstr = '';
g = finputcheck(varargin, { 'withindex' { 'integer';'string' } { [] {'on' 'off'} } 'off';
'select' { 'cell';'string';'integer' } [] [];
'selectionmode' 'string' { 'single';'multiple' } 'multiple'});
if isstr(g), error(g); end;
if ~isstr(g.withindex), chan_indices = g.withindex; g.withindex = 'on';
else chan_indices = 1:length(chans);
end;
% convert selection to integer
% ----------------------------
if isstr(g.select) & ~isempty(g.select)
g.select = parsetxt(g.select);
end;
if iscell(g.select) & ~isempty(g.select)
if isstr(g.select{1})
tmplower = lower( chans );
for index = 1:length(g.select)
matchind = strmatch(lower(g.select{index}), tmplower, 'exact');
if ~isempty(matchind), g.select{index} = matchind;
else error( [ 'Cannot find ''' g.select{index} '''' ] );
end;
end;
end;
g.select = [ g.select{:} ];
end;
if ~isnumeric( g.select ), g.select = []; end;
% add index to channel name
% -------------------------
tmpstr = {chans};
if isnumeric(chans{1})
tmpstr = [ chans{:} ];
tmpfieldnames = cell(1, length(tmpstr));
for index=1:length(tmpstr),
if strcmpi(g.withindex, 'on')
tmpfieldnames{index} = [ num2str(chan_indices(index)) ' - ' num2str(tmpstr(index)) ];
else
tmpfieldnames{index} = num2str(tmpstr(index));
end;
end;
else
tmpfieldnames = chans;
if strcmpi(g.withindex, 'on')
for index=1:length(tmpfieldnames),
tmpfieldnames{index} = [ num2str(chan_indices(index)) ' - ' tmpfieldnames{index} ];
end;
end;
end;
[chanlist,tmp,chanliststr] = listdlg2('PromptString',strvcat('(use shift|Ctrl to', 'select several)'), ...
'ListString', tmpfieldnames, 'initialvalue', g.select, 'selectionmode', g.selectionmode);
if tmp == 0
chanlist = [];
chanliststr = '';
return;
else
allchanstr = chans(chanlist);
end;
% test for spaces
% ---------------
spacepresent = 0;
if ~isnumeric(chans{1})
tmpstrs = [ allchanstr{:} ];
if ~isempty( find(tmpstrs == ' ')) | ~isempty( find(tmpstrs == 9))
spacepresent = 1;
end;
end;
% get concatenated string (if index)
% -----------------------
if strcmpi(g.withindex, 'on') | spacepresent
if isnumeric(chans{1})
chanliststr = num2str(celltomat(allchanstr));
else
chanliststr = '';
for index = 1:length(allchanstr)
if spacepresent
chanliststr = [ chanliststr '''' allchanstr{index} ''' ' ];
else
chanliststr = [ chanliststr allchanstr{index} ' ' ];
end;
end;
chanliststr = chanliststr(1:end-1);
end;
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_importpres.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_importpres.m
| 7,397 |
utf_8
|
7bdcf2f321f530fa80e188b145a4807a
|
% pop_importpres() - append Presentation event file information into an EEGLAB dataset
% The Presentation stimulus presentation program outputs an ascii
% log file. This function merges existing EEG dataset events with
% additional field information (fields) about those events contained
% in the logfile.
% Usage:
% >> EEGOUT = pop_importpres( EEGIN, filename );
% >> EEGOUT = pop_importpres( EEGIN, filename, typefield, ...
% latfield, durfield, align, 'key', 'val', ... );
% Inputs:
% EEGIN - input dataset
% logfilename - Presentation logfile name
%
% typefield - [string] type fieldname {default: 'code'}
% latfield - [string] latency fieldname {default: 'time'}
% durfield - [string] duration fieldname {default: 'none'}
% align - [integer] alignment with pre-existing events
% See >> help pop_importevent
% 'key','val' - This function calls pop_importevent(). These are
% optional arguments for this function (for event
% alignment for instance).
% Outputs:
% EEGOUT - data structure with added Presentation logfile information
%
% Note: If there are pre-existing events in the input dataset,
% this function will recalculate the latencies of the events
% in the Presentation file, so that they match those
% of the pre-existing events.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 15 March 2002
%
% Note: This function is backward compatible with its early versions
% (before the input argument 'durfield' was introduced).
% It can read the 'align' value as its 5th (not 6th) paramater.
%
% See also: eeglab(), pop_importevent()
% Copyright (C) 13 March 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, command] = pop_importpres(EEG, filename, typefield, latfield, durfield, align, varargin);
command = '';
if nargin < 1
help pop_importpres;
return
end;
% decode input (and backward compatibility)
% -----------------------------------------
if nargin < 5
durfield = '';
end;
if nargin >= 5 & ~isstr(durfield)
if nargin >= 6
varargin = { align varargin{:} };
end;
align = durfield;
durfield = '';
else
if nargin < 6
align = 0;
end;
end;
if nargin < 2
% ask user
[filename, filepath] = uigetfile('*.log;*.LOG', 'Choose a Presentation file -- pop_importpres()');
drawnow;
if filename == 0 return; end;
filename = [filepath filename];
end;
fields = loadtxt(filename, 'delim', 9, 'skipline', -2, 'nlines', 1, 'verbose', 'off');
% finding fields
% --------------
if nargin > 1
if nargin < 3
typefield = 'code'; % backward compatibility
latfield = 'time';
end;
indtype = strmatch(lower(typefield), lower(fields));
indlat = strmatch(lower(latfield) , lower(fields));
if ~isempty(durfield)
inddur = strmatch(lower(durfield) , lower(fields));
else inddur = 0;
end;
else
indtype1 = strmatch('event type', lower(fields));
indtype2 = strmatch('code', lower(fields));
indtype = [ indtype1 indtype2 1];
indlatency = strmatch('time', lower(fields), 'exact');
indlatency = [ indlatency 1 ];
uilist = { { 'style' 'text' 'string' [ 'File field containing event types' 10 '' ] } ...
{ 'style' 'list' 'string' strvcat(fields) 'value' indtype(1) 'listboxtop' indtype(1)} ...
{ 'style' 'text' 'string' [ 'File field containing event latencies' 10 '' ] } ...
{ 'style' 'list' 'string' strvcat(fields) 'value' indlatency(1) 'listboxtop' indlatency(1) } ...
{ 'style' 'text' 'string' [ 'File field containing event durations' 10 '' ] } ...
{ 'style' 'list' 'string' strvcat({ 'None' fields{:} }) 'value' 1 'listboxtop' 1 } ...
{ } { 'style' 'text' 'string' 'Note: scroll lists then click to select field' } };
uigeom = { [2 1] [2 1] [2 1] 1 1 };
result = inputgui(uigeom, uilist, 'pophelp(''pop_importpres'')', 'Import presentation file - pop_importpres()', ...
[], 'normal', [2 2 2 1 1]);
if isempty(result), return; end;
indtype = result{1};
indlat = result{2};
inddur = result{3}-1;
typefield = fields{indtype};
latfield = fields{indlat};
if inddur ~= 0
durfield = fields{inddur};
else durfield = '';
end;
end;
if isempty(indtype)
error(['Could not detect field ''' typefield ''', try importing the file as ASCII (use delimiter=9 (tab))']);
end;
if isempty(indlat)
error(['Could not detect field ''' latfield ''', try importing the file as ASCII (use delimiter=9 (tab))']);
end;
disp(['Replacing field ''' typefield ''' by ''type'' for EEGLAB compatibility']);
disp(['Replacing field ''' latfield ''' by ''latency'' for EEGLAB compatibility']);
fields{indtype} = 'type';
fields{indlat} = 'latency';
if inddur ~= 0
fields{inddur} = 'duration';
end
% check inputs
% regularizing field names
% ------------------------
for index = 1:length(fields)
indspace = find(fields{index} == ' ');
fields{index}(indspace) = '_';
indparen = find(fields{index} == ')');
if ~isempty(indparen) & indparen == length(fields{index})
% remove text for parenthesis
indparen = find(fields{index} == '(');
if indparen ~= 1
disp([ 'Renaming ''' fields{index} ''' to ''' fields{index}(1:indparen-1) ''' for Matlab compatibility' ]);
fields{index} = fields{index}(1:indparen-1);
else
fields{index}(indspace) = '_';
end;
else
fields{index}(indspace) = '_';
indparen = find(fields{index} == '(');
fields{index}(indspace) = '_';
end;
end;
% find if uncertainty is duplicated
% ---------------------------------
induncert = strmatch('uncertainty', lower(fields), 'exact');
if length(induncert) > 1
fields{induncert(2)}= 'Uncertainty2';
disp('Renaming second ''Uncertainty'' field');
end;
% import file
% -----------
if isempty(EEG.event), align = NaN; end;
%EEG = pop_importevent(EEG, 'append', 'no', 'event', filename, 'timeunit', 1E-4, 'skipline', -3, ...
% 'delim', 9, 'align', align, 'fields', fields, varargin{:});
EEG = pop_importevent(EEG, 'event', filename, 'timeunit', 1E-4, 'skipline', -3, ...
'delim', 9, 'align', align, 'fields', fields, varargin{:});
command = sprintf('EEG = pop_importpres(%s, %s);', inputname(1), vararg2str({ filename typefield latfield durfield align }));
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_rejkurt.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_rejkurt.m
| 9,845 |
utf_8
|
030cc42f85545f1e6d2616e8173271d2
|
% pop_rejkurt() - rejection of artifact in a dataset using kurtosis
% of activity (i.e. to detect peaky distribution of
% activity).
%
% Usage:
% >> pop_rejkurt( INEEG, typerej) % pop-up interative window mode
% >> [OUTEEG, locthresh, globthresh, nrej] = ...
% = pop_rejkurt( INEEG, typerej, elec_comp, ...
% locthresh, globthresh, superpose, reject, vistype);
%
% Graphical interface:
% "Electrode" - [edit box] electrodes or components (number) to take into
% consideration for rejection. Same as the 'elec_comp'
% parameter from the command line.
% "Single-channel limit" - [edit box] pkurtosis limit in terms of
% standard-dev. Same as 'locthresh' command line
% parameter.
% "All-channel limit" - [edit box] kurtosis limit in terms of
% standard-dev (all channel regrouped). Same as
% 'globthresh' command line parameter.
% "Display with previous rejection" - [edit box] can be either YES or
% NO. This edit box corresponds to the command line input
% option 'superpose'.
% "Reject marked trials" - [edit box] can be either YES or NO. This edit
% box corresponds to the command line input option 'reject'.
% "visualization type" - [edit box] can be either REJECTRIALS or EEGPLOT.
% This edit box corresponds to the command line input
% option 'vistype'.
%
% Inputs:
% INEEG - input dataset
% typerej - type of rejection (0 = independent components; 1 = eeg
% data). Default is 1. For independent components, before
% thresholding, the activity is normalized for each
% component.
% elec_comp - [e1 e2 ...] electrodes (number) to take into
% consideration for rejection
% locthresh - activity kurtosis limit in terms of standard-dev.
% globthresh - global limit (for all channel). Same unit as above.
% superpose - 0=do not superpose pre-labelling with previous
% pre-labelling (stored in the dataset). 1=consider both
% pre-labelling (using different colors). Default is 0.
% reject - 0=do not reject labelled trials (but still store the
% labels. 1=reject labelled trials. Default is 1.
% vistype - visualization type. 0 calls rejstatepoch() and 1 calls eegplot()
% default is 0.
%
% Outputs:
% OUTEEG - output dataset with updated kurtosis array
% locthresh - electrodes probability of activity thresholds in terms
% of standard-dev.
% globthresh - global threshold (where all electrode activity are
% regrouped).
% nrej - number of rejected sweeps
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: rejkurt(), rejstatepoch(), pop_rejepoch(), eegplot(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 03-07-02 added srate argument to eegplot call -ad
% 03-08-02 add eeglab options -ad
function [EEG, locthresh, globthresh, nrej, com] = pop_rejkurt( EEG, icacomp, elecrange, ...
locthresh, globthresh, superpose, reject, vistype, topcommand);
com = '';
if nargin < 1
help pop_rejkurt;
return;
end;
if nargin < 2
icacomp = 1;
end;
if exist('reject') ~= 1
reject = 1;
end;
if icacomp == 0
if isempty( EEG.icasphere )
ButtonName=questdlg( 'Do you want to run ICA now ?', ...
'Confirmation', 'NO', 'YES', 'YES');
switch ButtonName,
case 'NO', disp('Operation cancelled'); return;
case 'YES', [ EEG com ] = pop_runica(EEG);
end % switch
end;
end;
if nargin < 3
% which set to save
% -----------------
promptstr = { [ fastif(icacomp, 'Electrode', 'Component') ' (number(s); Ex: 2 4 5):' ], ...
[ fastif(icacomp, 'Single-channel', 'Single-component') ' limit(s) (std. dev(s).: Ex: 2 2 2.5):'], ...
[ fastif(icacomp, 'All-channel', 'All-component') ' limit (std. dev(s).: Ex: 2.1 2 2):'], ...
'Display with previously marked rejections? (YES or NO)', ...
'Reject marked trial(s)? (YES or NO)', ...
'Visualization mode (REJECTTRIALS or EEGPLOT)' };
inistr = { fastif(icacomp, ['1:' int2str(EEG.nbchan)], ['1:' int2str(size(EEG.icaweights,1))])...
fastif(icacomp, '3', '5'), ...
fastif(icacomp, '3', '5'), ...
'YES', ...
'NO', ...
'REJECTTRIALS' };
result = inputdlg2( promptstr, fastif(~icacomp, 'Trial rejection using comp. kurtosis -- pop_rejkurt()', 'Trial rejection using data kurtosis -- pop_rejkurt()'), 1, inistr, 'pop_rejkurt');
size_result = size( result );
if size_result(1) == 0 return; end;
elecrange = result{1};
locthresh = result{2};
globthresh = result{3};
switch lower(result{4}), case 'yes', superpose=1; otherwise, superpose=0; end;
switch lower(result{5}), case 'yes', reject=1; otherwise, reject=0; end;
switch lower(result{6}), case 'rejecttrials', vistype=0; otherwise, vistype=1; end;
end;
if ~exist('vistype') vistype = 0; end;
if ~exist('reject') reject = 0; end;
if ~exist('superpose') superpose = 1; end;
if isstr(elecrange) % convert arguments if they are in text format
calldisp = 1;
elecrange = eval( [ '[' elecrange ']' ] );
locthresh = eval( [ '[' locthresh ']' ] );
globthresh = eval( [ '[' globthresh ']' ] );
else
calldisp = 0;
end;
if isempty(elecrange)
error('No electrode selectionned');
end;
% compute the joint probability
% -----------------------------
if icacomp == 1
fprintf('Computing kurtosis for channels...\n');
tmpdata = eeg_getdatact(EEG);
if isempty(EEG.stats.kurtE )
[ EEG.stats.kurtE rejE ] = rejkurt( tmpdata, locthresh, EEG.stats.kurtE, 1);
end;
[ tmp rejEtmp ] = rejkurt( tmpdata(elecrange, :,:), locthresh, EEG.stats.kurtE(elecrange, :), 1);
rejE = zeros(EEG.nbchan, size(rejEtmp,2));
rejE(elecrange,:) = rejEtmp;
fprintf('Computing all-channel kurtosis...\n');
tmpdata2 = permute(tmpdata, [3 1 2]);
tmpdata2 = reshape(tmpdata2, size(tmpdata2,1), size(tmpdata2,2)*size(tmpdata2,3));
[ EEG.stats.kurt rej ] = rejkurt( tmpdata2, globthresh, EEG.stats.kurt, 1);
else
fprintf('Computing joint probability for components...\n');
% test if ICA was computed
% ------------------------
icaacttmp = eeg_getica(EEG);
if isempty(EEG.stats.icakurtE )
[ EEG.stats.icakurtE rejE ] = rejkurt( icaacttmp, locthresh, EEG.stats.icakurtE, 1);
end;
[ tmp rejEtmp ] = rejkurt( icaacttmp(elecrange, :,:), locthresh, EEG.stats.icakurtE(elecrange, :), 1);
rejE = zeros(size(icaacttmp,1), size(rejEtmp,2));
rejE(elecrange,:) = rejEtmp;
fprintf('Computing global joint probability...\n');
tmpdata = permute(icaacttmp, [3 1 2]);
tmpdata = reshape(tmpdata, size(tmpdata,1), size(tmpdata,2)*size(tmpdata,3));
[ EEG.stats.icakurt rej] = rejkurt( tmpdata, globthresh, EEG.stats.icakurt, 1);
end;
rej = rej' | max(rejE, [], 1);
fprintf('%d/%d trials marked for rejection\n', sum(rej), EEG.trials);
if calldisp
if vistype == 1 % EEGPLOT -------------------------
if icacomp == 1 macrorej = 'EEG.reject.rejkurt';
macrorejE = 'EEG.reject.rejkurtE';
else macrorej = 'EEG.reject.icarejkurt';
macrorejE = 'EEG.reject.icarejkurtE';
end;
colrej = EEG.reject.rejkurtcol;
eeg_rejmacro; % script macro for generating command and old rejection arrays
if icacomp == 1
eegplot( tmpdata(elecrange,:,:), 'srate', ...
EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:});
else
eegplot( icaacttmp(elecrange,:,:), 'srate', ...
EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:});
end;
else % REJECTRIALS -------------------------
if icacomp == 1
[ rej, rejE, n, locthresh, globthresh] = ...
rejstatepoch( tmpdata, EEG.stats.kurtE(elecrange,:), 'global', 'on', 'rejglob', EEG.stats.kurt, ...
'threshold', locthresh, 'thresholdg', globthresh, 'normalize', 'off' );
else
[ rej, rejE, n, locthresh, globthresh] = ...
rejstatepoch( icaacttmp, EEG.stats.icakurtE(elecrange,:), 'global', 'on', 'rejglob', EEG.stats.icakurt, ...
'threshold', locthresh, 'thresholdg', globthresh, 'normalize', 'off' );
end;
nrej = n;
end;
else
% compute rejection locally
rejtmp = max(rejE(elecrange,:),[],1);
rej = rejtmp | rej;
nrej = sum(rej);
fprintf('%d trials marked for rejection\n', nrej);
end;
if ~isempty(rej)
if icacomp == 1
EEG.reject.rejkurt = rej;
EEG.reject.rejkurtE = rejE;
else
EEG.reject.icarejkurt = rej;
EEG.reject.icarejkurtE = rejE;
end;
if reject
EEG = pop_rejepoch(EEG, rej, 0);
end;
end;
nrej = sum(rej);
com = [ com sprintf('%s = pop_rejkurt(%s,%s);', inputname(1), ...
inputname(1), vararg2str({icacomp,elecrange,locthresh,globthresh,superpose,reject})) ];
if nargin < 3 & nargout == 2
locthresh = com;
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_writelocs.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_writelocs.m
| 8,336 |
utf_8
|
fe5e26b45aeae126898af6bfd87633bd
|
% pop_writelocs() - load a EGI EEG file (pop out window if no arguments).
%
% Usage:
% >> EEG = pop_writelocs(chanstruct); % a window pops up
% >> EEG = pop_writelocs(chanstruct, filename, 'key', val, ...);
%
% Inputs:
% chanstruct - channel structure. See readlocs()
% filename - Electrode location file name
% 'key',val - same as writelocs()
%
% Author: Arnaud Delorme, CNL / Salk Institute, 17 Dec 2002
%
% See also: writelocs()
% Copyright (C) Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function com = pop_writelocs(chans, filename, varargin);
com = '';
if nargin < 1
help pop_writelocs;
return;
end;
if isfield(chans, 'shrink')
chans = rmfield(chans, 'shrink');
disp('Warning: shrink factor ignored');
end;
disp('WARNING: ELECTRODE COORDINATES MUST BE WITH NOSE ALONG THE +X DIMENSION TO BE EXPORTED')
disp(' IF NOT, THE EXPORTED FILE COORDINATES MAY BE INNACURATE')
% get infos from readlocs
% -----------------------
[chanformat listcolformat] = readlocs('getinfos');
chanformat(end) = [];
listcolformat(end) = []; % remove chanedit
chanformat(end) = [];
listcolformat(end) = []; % remove chanedit
indformat = [];
for index = 1:length(chanformat),
if ~isstr(chanformat(index).importformat)
indformat = [ indformat index ];
end;
if isempty(chanformat(index).skipline), chanformat(index).skipline = 0; end;
end;
listtype = { chanformat(indformat).type };
formatinfo = { chanformat(indformat).importformat };
formatskip = [ chanformat(indformat).skipline ];
%[listtype formatinfo listcolformat formatskip] = readlocs('getinfoswrite');
listtype{end+1} = 'custom';
formatinfo{end+1} = {};
formatskip = [ formatskip 0];
if nargin < 2
updatefields = [ 'tmpdata = get(gcf, ''userdata'');' ...
'tmpobj = findobj(gcf, ''tag'', ''list2'');' ...
'set(tmpobj, ''string'', strvcat(tmpdata{2}));' ...
'clear tmpobj tmpdata;' ];
addfieldcom = [ 'tmpdata = get(gcbf, ''userdata'');' ...
'tmpobj = findobj(gcf, ''tag'', ''list1'');' ...
'tmpdata{2}{end+1} = tmpdata{1}{get(tmpobj, ''value'')};' ...
'set(gcbf, ''userdata'', tmpdata);' ...
updatefields ];
rmfieldcom = [ 'tmpdata = get(gcbf, ''userdata'');' ...
'tmpobj = findobj(gcbf, ''tag'', ''list2'');' ...
'try, tmpdata{2}(get(tmpobj, ''value'')) = [];' ...
' set(tmpobj, ''value'', 1);' ...
'catch, end;' ...
'set(gcbf, ''userdata'', tmpdata);' ...
updatefields ];
filetypecom = [ 'tmpdata = get(gcf, ''userdata'');' ...
'tmpobj = findobj(gcf, ''tag'', ''formatlist'');' ...
'tmpval = get(tmpobj, ''value'');' ...
'try, tmpdata{2} = tmpdata{3}{tmpval}; catch, end;' ... %try and catch for custom
'set(gcf, ''userdata'', tmpdata);' ...
updatefields ...
'tmpdata = get(gcf, ''userdata'');' ...
'tmpobj1 = findobj(gcf, ''tag'', ''insertcol'');' ... % the lines below
'tmpobj2 = findobj(gcf, ''tag'', ''inserttext'');' ... % update the checkbox
'try, ' ... % and the edit text box
' if tmpdata{4}(tmpval) == 2,' ...
' set(tmpobj1, ''value'', 1);' ...
' else,' ...
' set(tmpobj1, ''value'', 0);' ...
' end;' ...
' if tmpval == 1,' ... % besa only
' set(tmpobj2, ''string'', ''' int2str(length(chans)) ''');' ...
' else,' ...
' set(tmpobj2, ''string'', '''');' ...
' end;' ...
'catch, end;' ... % catch for custom case
'tmpobj = findobj(gcf, ''userdata'', ''setfield'');' ...
'if tmpval == ' int2str(length(listtype)) ',' ... % disable if non-custom type
' set(tmpobj, ''enable'', ''on'');' ...
'else,' ...
' set(tmpobj, ''enable'', ''off'');' ...
'end; clear tmpobj tmpobj2 tmpdata tmpval;' ];
geometry = { [1 1 1] [1 1] [1] [1 1 1] [1 1] [1 1 1] [1 0.3 0.7] [1] [1] };
listui = { ...
{ 'style' 'text' 'string' 'Filename' } ...
{ 'style' 'edit' 'string' '' 'tag' 'filename' 'horizontalalignment' 'left' } ...
{ 'style' 'pushbutton' 'string' 'Browse' 'callback' ...
[ '[tmpfile tmppath] = uiputfile(''*'', ''Exporting electrode location file -- pop_writelocs()'');' ...
'set(findobj(gcbf, ''tag'', ''filename''), ''string'', char([tmppath tmpfile ]));' ...
'clear tmpfile tmppath;' ] } ...
{ 'style' 'text' 'string' strvcat('Select output file type', ' ', ' ') } ...
{ 'style' 'listbox' 'tag' 'formatlist' 'string' strvcat(listtype) ...
'value' length(listtype) 'callback' filetypecom } ...
{ 'style' 'text' 'string' 'Select fields to export below' } ...
{ } { 'style' 'pushbutton' 'string' '-> ADD' 'callback' addfieldcom 'userdata' 'setfield' } { } ...
{ 'style' 'listbox' 'tag' 'list1' 'string' strvcat(fieldnames(chans)) 'userdata' 'setfield' } ...
{ 'style' 'listbox' 'tag' 'list2' 'string' '' 'userdata' 'setfield2' } ...
{ } { 'style' 'pushbutton' 'string' 'REMOVE <-' 'callback' rmfieldcom 'userdata' 'setfield' } { } ...
{ 'style' 'text' 'string' 'Insert column names' } ...
{ 'style' 'checkbox' 'tag' 'insertcol' 'value' 1 'userdata' 'setfield' } { } ...
{ 'style' 'text' 'string' 'Enter custom header below' } ...
{ 'style' 'edit' 'userdata' 'setfield' 'tag' 'inserttext' 'horizontalalignment' 'left' 'max' 2 } ...
};
inputgui(geometry, listui, 'pophelp(''writelocs'');', ...
'Exporting electrode location file -- pop_writelocs()', { fieldnames(chans) {} formatinfo formatskip }, 'plot', [1 3 1 1 3 1 1 1 3 ]);
fig = gcf;
% set default format
tmpobj = findobj(fig, 'tag', 'formatlist');
set(tmpobj, 'value', 6);
eval(get(tmpobj, 'callback'));
res = inputgui(geometry, listui, 'pophelp(''writelocs'');', ...
'Exporting electrode location file -- pop_writelocs()', { listcolformat {} formatinfo formatskip }, fig, [1 3 1 1 3 1 1 1 3 ]);
if gcf ~= fig, return; end;
exportfields = get(fig, 'userdata');
exportfields = exportfields{2};
close(fig);
% decode the inputs
filename = res{1};
if isempty(filename),
errordlg2('Error: Empty file name', 'Error');
return;
end;
options = { 'filetype' listtype{res{2}} 'format' exportfields ...
'header' fastif(res{5}, 'on', 'off') 'customheader' res{6} };
else
options = varargin;
end;
% generate history
% ----------------
if isempty(inputname(1)) % not a variable name -> probably the structure from pop_chanedit
writelocs(chans, filename, options{:});
com = sprintf('pop_writelocs( EEG.chanlocs, ''%s'', %s);', filename, vararg2str(options));
else
if strcmpi(inputname(1), 'chantmp')
% do not write file (yet)
com = sprintf('pop_writelocs( chans, ''%s'', %s);', filename, vararg2str(options));
else
writelocs(chans, filename, options{:});
com = sprintf('pop_writelocs( %s, ''%s'', %s);', inputname(1), filename, vararg2str(options));
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_mergelocs.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_mergelocs.m
| 4,179 |
utf_8
|
a8146d5e7944cc5d9b473d7c71c960b4
|
% eeg_mergelocs() - merge channel structure while preserving channel
% order
%
% >> mergedlocs = eeg_mergelocs(loc1, loc2, loc3, ...);
%
% Inputs:
% loc1 - EEGLAB channel location structure
% loc2 - second EEGLAB channel location structure
%
% Output:
% mergedlocs - merged channel location structure
% warning - [0|1] dissimilar structures found (0=false, 1=true)
%
% Author: Arnaud Delorme, August 2006
% Copyright (C) Arnaud Delorme, CERCO, 2006, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [alllocs warn] = eeg_mergelocs(varargin)
persistent warning_shown;
warn = 0;
try
% sort by length
% --------------
len = cellfun(@length, varargin);
[tmp so] = sort(len, 2, 'descend');
varargin = varargin(so);
alllocs = varargin{1};
for index = 2:length(varargin)
% fuse while preserving order (assumes the same channel order)
% ------------------------------------------------------------
tmplocs = varargin{index};
newlocs = myunion(alllocs, tmplocs);
if length(newlocs) > length(union({ alllocs.labels }, { tmplocs.labels }))
warn = 1;
if isempty(warning_shown)
disp('Warning: different channel montage or electrode order for the different datasets');
warning_shown = 1;
end;
% trying to preserve order of the longest array
%----------------------------------------------
if length(alllocs) < length(tmplocs)
tmp = alllocs;
alllocs = tmplocs;
tmplocs = tmp;
end;
allchans = { alllocs.labels tmplocs.labels };
[uniquechan ord1 ord2 ] = unique_bc( allchans );
[tmp rminds] = intersect_bc( uniquechan, { alllocs.labels });
ord1(rminds) = [];
tmplocsind = ord1-length(alllocs);
newlocs = [ alllocs tmplocs(tmplocsind) ];
end;
alllocs = newlocs;
end;
catch,
% temporary fix for dissimilar structures
% should check channel structure consistency instead
% using checkchan function
disp('Channel merging warning: dissimilar fields in the two structures');
[alllocs warn ] = eeg_mergelocs_diffstruct(varargin{:});
end;
% union of two channel location structure
% without loosing the order information
% ---------------------------------------
function alllocs = myunion(locs1, locs2)
labs1 = { locs1.labels };
labs2 = { locs2.labels };
count1 = 1;
count2 = 1;
count3 = 1;
alllocs = locs1; alllocs(:) = [];
while count1 <= length(locs1) || count2 <= length(locs2)
if count1 > length(locs1)
alllocs(count3) = locs2(count2);
count2 = count2 + 1;
count3 = count3 + 1;
elseif count2 > length(locs2)
alllocs(count3) = locs1(count1);
count1 = count1 + 1;
count3 = count3 + 1;
elseif strcmpi(labs1{count1}, labs2{count2})
alllocs(count3) = locs1(count1);
count1 = count1 + 1;
count2 = count2 + 1;
count3 = count3 + 1;
elseif isempty(strmatch(labs1{count1}, labs2, 'exact'))
alllocs(count3) = locs1(count1);
count1 = count1 + 1;
count3 = count3 + 1;
else
alllocs(count3) = locs2(count2);
count2 = count2 + 1;
count3 = count3 + 1;
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_plottopo.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_plottopo.m
| 4,700 |
utf_8
|
dc19c8e12f6b42f992ddfe25d0489039
|
% pop_plottopo() - plot one or more concatenated multichannel data epochs
% in a topographic array format using plottopo()
% Usage:
% >> pop_plottopo( EEG ); % pop-up
% >> pop_plottopo( EEG, channels );
% >> pop_plottopo( EEG, channels, title, singletrials);
% >> pop_plottopo( EEG, channels, title, singletrials, axsize, ...
% 'color', ydir, vert);
%
% Inputs:
% EEG - input dataset
% channels - indices of channels to plot
% title - plot title. Default is none.
% singletrials - [0|1], 0 plot average, 1 plot individual
% single trials. Default is 0.
% others... - additional plottopo arguments {'axsize', 'color', 'ydir'
% 'vert'} (see >> help plottopo)
%
% Author: Arnaud Delorme, CNL / Salk Institute, 10 March 2002
%
% See also: plottopo()
% Copyright (C) 10 March 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 02-16-02 text interface editing -sm & ad
% 03-18-02 added title -ad & sm
% 03-30-02 added single trial capacities -ad
function com = pop_plottopo( EEG, channels, plottitle, singletrials, varargin);
com = '';
if nargin < 1
help pop_plottopo;
return;
end;
if isempty(EEG.chanlocs)
fprintf('Cannot plot without knowing channel locations. Use Edit/Dataset info\n');
return;
end;
if nargin < 2
uilist = { { 'style' 'text' 'string' 'Channels to plot' } ...
{ 'style' 'edit' 'string' [ '1:' num2str( EEG.nbchan ) ] 'tag' 'chan' } ...
{ 'style' 'text' 'string' 'Plot title' } ...
{ 'style' 'edit' 'string' fastif(isempty(EEG.setname), '',EEG.setname) 'tag' 'title' } ...
{ 'style' 'text' 'string' 'Plot single trials' } ...
{ 'style' 'checkbox' 'string' '(set=yes)' 'tag' 'cbst' } ...
{ 'style' 'text' 'string' 'Plot in rect. array' } ...
{ 'style' 'checkbox' 'string' '(set=yes)' 'tag' 'cbra' } ...
{ 'style' 'text' 'string' 'Other plot options (see help)' } ...
{ 'style' 'edit' 'string' '''ydir'', 1' 'tag' 'opt' } };
geometry = { [1 1] [1 1] [1 1] [1 1] [1 1] };
[result userdata tmphalt restag ] = inputgui( 'uilist', uilist, 'geometry', geometry, 'helpcom', 'pophelp(''pop_plottopo'')', 'title', 'Topographic ERP plot - pop_plottopo()');
if length(result) == 0 return; end;
channels = eval( [ '[' restag.chan ']' ] );
plottitle = restag.title;
singletrials = restag.cbst;
addoptions = eval( [ '{' restag.opt '}' ] );
rect = restag.cbra;
figure('name', ' plottopo()');
options ={ 'frames' EEG.pnts 'limits' [EEG.xmin EEG.xmax 0 0]*1000 ...
'title' plottitle 'chans' channels addoptions{:} };
if ~rect
options = { options{:} 'chanlocs' EEG.chanlocs };
end;
else
options ={ 'chanlocs' EEG.chanlocs 'frames' EEG.pnts 'limits' [EEG.xmin EEG.xmax 0 0]*1000 ...
'title' plottitle 'chans' channels varargin{:}};
addoptions = {};
end;
% adapt frames to time limit.
if any(strcmp(addoptions,'limits'))
addoptions{end+1} = 'frames';
ilimits = find(strcmp(addoptions,'limits'))+1;
timelims = addoptions{ilimits}(1:2);
addoptions{end+1} = round(diff(timelims/1000)*EEG.srate);
end
try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
if exist('plottitle') ~= 1
plottitle = '';
end;
if exist('singletrials') ~= 1
singletrials = 0;
end;
if singletrials
plottopo( EEG.data, options{:} );
else
plottopo( mean(EEG.data,3), options{:} );
end;
if ~isempty(addoptions)
com = sprintf('figure; pop_plottopo(%s, %s, ''%s'', %d, %s);', ...
inputname(1), vararg2str(channels), plottitle, singletrials, vararg2str(addoptions));
else
com = sprintf('figure; pop_plottopo(%s, %s, ''%s'', %d);', ...
inputname(1), vararg2str(channels), plottitle, singletrials);
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_loaddat.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_loaddat.m
| 3,543 |
utf_8
|
fe210f46e8ff2314b39fb77ae8b3945b
|
% pop_loaddat() - merge a neuroscan DAT file with input dataset
% (pop out window if no arguments).
%
% Usage:
% >> OUTEEG = pop_loaddat( INEEG ); % pop-up window mode
% >> OUTEEG = pop_loaddat( INEEG, filename, no_rt);
%
% Graphic interfance:
% "Code signifying no event ..." - [edit box] reaction time
% no event code. See 'no_rt' command line equivalent
% help.
% Inputs:
% filename - file name
% INEEG - input EEGLAB data structure
% no_rt - no reaction time integer code (ex: 1000). Since
% a number has to be defined for each reaction
% time, epochs with no reaction time usually have
% a stereotyped reaction time value (such as 1000).
% Default none.
% Outputs:
% OUTEEG - EEGLAB data structure
%
% Author: Arnaud Delorme, CNL/Salk Institute, 2001
%
% See also: loaddat(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 13/02/02 removed the no latency option -ad
function [EEG, command] = pop_loaddat(EEG, filename, no_rt);
command = '';
if nargin < 1
help pop_loaddat;
return;
end;
if nargin < 2
% ask user
[filename, filepath] = uigetfile('*.DAT', 'Choose a DAT file -- pop_loaddat');
drawnow;
if filename == 0 return; end;
result = inputdlg2( { strvcat('Code signifying no event in a trial ([]=none)', ...
'(none=all latencies are imported)')}, ...
'Load Neuroscan DATA file -- pop_loaddat()', 1, {'1000'}, 'pop_loaddat');
if length(result) == 0 return; end;
no_rt = eval( result{1} );
end;
if exist('no_rt') ~= 1 | isempty(no_rt)
no_rt = NaN;
end;
% load datas
% ----------
if exist('filepath')
fullFileName = sprintf('%s%s', filepath, filename);
else
fullFileName = filename;
end;
disp('Loading dat file...');
[typeeeg, rt, response, n] = loaddat( fullFileName );
if n ~= EEG.trials
error('pop_loaddat, number of trials in input dataset and DAT file different, aborting');
end;
for index = 1:length(EEG.event)
EEG.event(index).eegtype = typeeeg (EEG.event(index).epoch);
EEG.event(index).response = response(EEG.event(index).epoch);
end;
for index = 1:n
if rt(index) ~= no_rt
EEG.event(end+1).type = 'rt';
EEG.event(end).latency = eeg_lat2point(rt(index)/1000, index, EEG.srate, [EEG.xmin EEG.xmax]);
EEG.event(end).epoch = index;
EEG.event(end).eegtype = typeeeg(index);
EEG.event(end).response = response(index);
end
end;
tmpevent = EEG.event;
tmp = [ tmpevent.latency ];
[tmp indexsort] = sort(tmp);
EEG.event = EEG.event(indexsort);
EEG = eeg_checkset(EEG, 'eventconsistency');
command = sprintf('%s = pop_loaddat(%s, %s, %d);', inputname(1), inputname(1), fullFileName, no_rt);
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_crossf.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_crossf.m
| 8,682 |
utf_8
|
12df1d32f46458d3c4a9ed985725dd22
|
% pop_crossf() - Return estimates and plots of event-related spectral coherence
%
% Usage:
% >> pop_crossf(EEG, typeproc, num1, num2, tlimits,cycles,
% 'key1',value1,'key2',value2, ... );
% Inputs:
% INEEG - Input EEG dataset
% typeproc - Type of processing:
% 1 = process two raw-data channels,
% 0 = process two ICA components
% num1 - First component or channel number
% num2 - Second component or channel number
% tlimits - [mintime maxtime] Sub-epoch time limits in ms
% cycles - >0 -> Number of cycles in each analysis wavelet
% 0 -> Use FFTs (with constant window length)
%
% Optional inputs: As for crossf(). See >> help crossf
%
% Outputs: Same as crossf(). No outputs are returned when a
% window pops-up to ask for additional arguments
%
% Author: Arnaud Delorme, CNL / Salk Institute, 11 March 2002
%
% See also: timef(), eeglab()
% Copyright (C) 11 March 2002 [email protected], Arnaud Delorme, CNL / Salk Institute
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 03-18-02 added title -ad & sm
% 04-04-02 added outputs -ad & sm
function varargout = pop_crossf(EEG, typeproc, num1, num2, tlimits, cycles, varargin );
varargout{1} = '';
% display help if not enough arguments
% ------------------------------------
if nargin < 2
help pop_crossf;
return;
end;
lastcom = [];
if nargin < 3
popup = 1;
else
popup = isstr(num1) | isempty(num1);
if isstr(num1)
lastcom = num1;
end;
end;
% pop up window
% -------------
if popup
[txt vars] = gethelpvar('timef.m');
geometry = { [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [1 0.5 0.5] [0.92 0.1 0.78] [1 0.5 0.5] [1 0.8 0.2] [1] [1 1]};
uilist = { { 'Style', 'text', 'string', fastif(typeproc, 'First channel number', 'First component number'), 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') } {} ...
{ 'Style', 'text', 'string', fastif(typeproc, 'Second channel number', 'Second component number'), 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,4,[],'2') } {} ...
{ 'Style', 'text', 'string', 'Epoch time range [min max] (msec)', 'fontweight', 'bold', ...
'tooltipstring', 'Sub epoch time limits' } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,5,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) } {} ...
{ 'Style', 'text', 'string', 'Wavelet cycles (0->FFT, see >> help timef)', 'fontweight', 'bold', ...
'tooltipstring', context('cycles',vars,txt) } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,6,[],'3 0.5') } {} ...
{ 'Style', 'text', 'string', '[set]->Linear coher / [unset]->Phase coher', 'fontweight', 'bold', ...
'tooltipstring', ['Compute linear inter-trial coherence (coher)' 10 ...
'OR Amplitude-normalized inter-trial phase coherence (phasecoher)'] } ...
{ 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'phasecoher','present',1) } { } ...
{ 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold', ...
'tooltipstring', context('alpha',vars,txt) } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') } {} ...
{ 'Style', 'text', 'string', 'Optional timef() arguments (see Help)', 'fontweight', 'bold', ...
'tooltipstring', 'See crossf() help via the Help button on the right...' } ...
{ 'Style', 'edit', 'string', '''padratio'', 4' } ...
{ 'Style', 'pushbutton', 'string', 'Help', 'callback', 'pophelp(''crossf'');' } ...
{} ...
{ 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ...
'Plot coherence amplitude', 'tooltipstring', ...
'Plot coherence ampltitude image in the upper panel' } ...
{ 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',0), 'string', ...
'Plot coherence phase', 'tooltipstring', ...
'Plot coherence phase image in the lower panel' } ...
};
result = inputgui( geometry, uilist, 'pophelp(''pop_crossf'');', ...
fastif(typeproc, 'Plot channel cross-coherence -- pop_crossf()', ...
'Plot component cross-coherence -- pop_crossf()'));
if length( result ) == 0 return; end;
num1 = eval( [ '[' result{1} ']' ] );
num2 = eval( [ '[' result{2} ']' ] );
tlimits = eval( [ '[' result{3} ']' ] );
cycles = eval( [ '[' result{4} ']' ] );
if result{5}
options = [',''type'', ''coher''' ];
else
options = [',''type'', ''phasecoher''' ];
end;
% add topoplot
% ------------
if isfield(EEG.chanlocs, 'theta')
if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end;
if typeproc == 1
options = [options ', ''topovec'', [' int2str([num1 num2]) ...
'], ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ];
else % typeproc == 0
options = [options ', ''topovec'', EEG.icawinv(:, [' int2str([num1 num2]) ...
'])'', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo' ];
end;
end;
% add title
% ---------
if isempty( findstr( 'title', result{7}))
if ~isempty(EEG.chanlocs) & typeproc
chanlabel1 = EEG.chanlocs(num1).labels;
chanlabel2 = EEG.chanlocs(num2).labels;
else
chanlabel1 = int2str(num1);
chanlabel2 = int2str(num2);
end;
if result{5}
options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel1 '-' chanlabel2 ...
' Coherence'''];
else
options = [options ', ''title'',' fastif(typeproc, '''Channel ', '''Component ') chanlabel1 '-' chanlabel2 ...
' Phase Coherence''' ];
end;
end;
if ~isempty( result{6} )
options = [ options ', ''alpha'',' result{6} ];
end;
if ~isempty( result{7} )
options = [ options ',' result{7} ];
end;
if ~result{8}
options = [ options ', ''plotersp'', ''off''' ];
end;
if ~result{9}
options = [ options ', ''plotphase'', ''off''' ];
end;
figure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
else
options = [ ',' vararg2str(varargin) ];
end;
% compute epoch limits
% --------------------
if isempty(tlimits)
tlimits = [EEG.xmin, EEG.xmax]*1000;
end;
pointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1));
pointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate, EEG.pnts));
pointrange = [pointrange1:pointrange2];
% call function sample either on raw data or ICA data
% ---------------------------------------------------
if typeproc == 1
tmpsig1 = EEG.data(num1,pointrange,:);
tmpsig2 = EEG.data(num2,pointrange,:);
else
if ~isempty( EEG.icasphere )
tmpsig1 = eeg_getdatact(EEG, 'component', num1, 'samples', pointrange);
tmpsig2 = eeg_getdatact(EEG, 'component', num2, 'samples', pointrange);
else
error('You must run ICA first');
end;
end;
tmpsig1 = reshape( tmpsig1, 1, size(tmpsig1,2)*size(tmpsig1,3));
tmpsig2 = reshape( tmpsig2, 1, size(tmpsig2,2)*size(tmpsig2,3));
% outputs
% -------
outstr = '';
if ~popup
for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end;
if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end;
end;
% plot the datas and generate output command
% --------------------------------------------
if length( options ) < 2
options = '';
end;
varargout{1} = sprintf('figure; pop_crossf( %s, %d, %d, %d, [%s], [%s] %s);', ...
inputname(1), typeproc, num1, num2, int2str(tlimits), num2str(cycles), options);
%options = [ options ', ''ydir'', ''norm''' ];
com = sprintf( '%s crossf( tmpsig1, tmpsig2, length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options);
eval(com)
return;
% get contextual help
% -------------------
function txt = context(var, allvars, alltext);
loc = strmatch( var, allvars);
if ~isempty(loc)
txt= alltext{loc(1)};
else
disp([ 'warning: variable ''' var ''' not found']);
txt = '';
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_timtopo.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_timtopo.m
| 4,061 |
utf_8
|
83935198482b3bf9e34948c08e8aef23
|
% pop_timtopo() - call the timtopo() function for epoched EEG datasets.
% Plots the epoch mean for each channel on a single axis,
% plus scalp maps of the data at specified latencies.
% Usage:
% >> pop_timtopo( EEG, timerange, topotimes, title, 'key', 'val', ...);
%
% Inputs:
% EEG - input dataset
% timerange - [min max] epoch time range (in ms) to plot
% topotimes - array of times to plot scalp maps {Default: NaN
% = display scalp map at frame of max var()}
%
% Optional inputs:
% title - optional plot title
% 'key','val' - optional topoplot() arguments (see >> help topoplot)
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: timtopo()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 02-16-02 text interface editing -sm & ad
% 03-15-02 add all topoplot options -ad
% 03-18-02 added title -ad & sm
function com = pop_timtopo( EEG, timerange, topotime, plottitle, varargin);
com = '';
if nargin < 1
help pop_timtopo;
return;
end;
if nargin < 3
promptstr = { 'Plotting time range (ms):', ...
['Scalp map latencies (ms, NaN -> max-RMS)'], ...
'Plot title:' ...
'Scalp map options (see >> help topoplot):' };
inistr = { [num2str( EEG.xmin*1000) ' ' num2str(EEG.xmax*1000)], ...
'NaN', ...
['ERP data and scalp maps' fastif(~isempty(EEG.setname), [' of ' EEG.setname ], '') ], ...
'' };
result = inputdlg2( promptstr, 'ERP data and scalp maps -- pop_timtopo()', 1, inistr, 'pop_timtopo');
if size(result,1) == 0 return; end;
timerange = eval( [ '[' result{1} ']' ] );
topotime = eval( [ '[' result{2} ']' ] );
plottitle = result{3};
options = [ ',' result{4} ];
figure;
else
options = [];
for i=1:length( varargin )
if isstr( varargin{ i } )
options = [ options ', ''' varargin{i} '''' ];
else
options = [ options ', [' num2str(varargin{i}) ']' ];
end;
end;
end;
try, icadefs; set(gcf, 'color', BACKCOLOR, 'Name', ' timtopo()'); catch, end;
if exist('plottitle') ~= 1
plottitle = ['ERP data and scalp maps' fastif(~isempty(EEG.setname), [' of ' EEG.setname ], '') ];
end;
if ~isempty(EEG.chanlocs)
if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end;
SIGTMP = reshape(EEG.data, size(EEG.data,1), EEG.pnts, EEG.trials);
posi = round( (timerange(1)/1000-EEG.xmin)/(EEG.xmax-EEG.xmin) * (EEG.pnts-1))+1;
posf = round( (timerange(2)/1000-EEG.xmin)/(EEG.xmax-EEG.xmin) * (EEG.pnts-1))+1;
if length( options ) < 2
timtopo( mean(SIGTMP(:,posi:posf,:),3), EEG.chanlocs, 'limits', [timerange(1) timerange(2) 0 0], 'plottimes', topotime, 'chaninfo', EEG.chaninfo);
com = sprintf('figure; pop_timtopo(%s, [%s], [%s], ''%s'');', inputname(1), num2str(timerange), num2str(topotime), plottitle);
else
com = sprintf('timtopo( mean(SIGTMP(:,posi:posf,:),3), EEG.chanlocs, ''limits'', [timerange(1) timerange(2) 0 0], ''plottimes'', topotime, ''chaninfo'', EEG.chaninfo %s);', options);
eval(com)
com = sprintf('figure; pop_timtopo(%s, [%s], [%s], ''%s'' %s);', inputname(1), num2str(timerange), num2str(topotime), plottitle, options);
end;
else
fprintf('Cannot make plot without channel locations\n');
return;
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_multieegplot.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_multieegplot.m
| 4,358 |
utf_8
|
16fe8e9b9e5bff89de4ed0ebe4dd8ec5
|
% eeg_multieegplot() - Produce an eegplot() of a the average of an epoched dataset
% (with optional pre-labelling of specific trials).
% Usage:
% >> eeg_multieegplot( data,trialrej, elecrej, ...
% 'key1', value, 'key2', value ... );
% Inputs:
% data - input data (channels x points or channels x points x trials).
% trialrej - array of 0s and 1s (depicting rejected trials) (size sweeps)
% elecrej - array of 0s and 1s (depicting electrodes rejected in
% all trials) (size nbelectrodes x sweeps )
% oldtrialrej - array of 0s and 1s (depicting rejected trials) (size sweeps)
% oldelecrej - array of 0s and 1s (depicting electrodes rejected in
% all trials) (size nbelectrodes x sweeps )
%
% Note: 1) {'Key', value } Arguments are passed on to eegplot()
% 2) To ignore previous rejections simply set 'oldtrialrej' and
% 'oldelecrej' arguments to empty ([]).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eegplot(), eegplot2event(), eegplot2trial(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 03-07-02 corrected help -ad
function eeg_multieegplot( data, rej, rejE, oldrej, oldrejE, varargin);
if nargin < 1
help eeg_multieegplot;
return;
end;
if nargin < 4
oldrej = [];
end;
if nargin < 5
oldrejE = [];
end;
if ~exist('command')
command = '';
end;
chans = size(data,1);
pnts = size(data,2);
colnew = [0.8 0.8 1];
colold = [0.8 1 0.8];
if ndims(data) > 2 % --------------- considering epoched EEG data
rejeegplot = [];
% concatenate old rejection if not empty
% --------------------------------------
if ~isempty( oldrej )
oldrej = find( oldrej > 0);
oldrejE = oldrejE(:, oldrej)';
rejeegplot = trial2eegplot( oldrej, oldrejE, pnts, colold);
end;
% convert for eegplot
% -------------------
if ~isempty( rej )
rej = find( rej > 0);
rejE = rejE(:,rej)';
secondrejeegplot = trial2eegplot( rej, rejE, pnts, colnew); % see bottom of code for this function
rejeegplot = [ rejeegplot' secondrejeegplot' ]';
% remove duplicates
% -----------------
%[tmp I] = unique_bc( rejeegplot(:,1) );
%rejeegplot = rejeegplot(I,:);
end;
else % ---------------------------------------- considering continuous EEG
% for continuous EEG, electrodes (rejE and oldrejE) are not considered yet
% because there would be a format problem (these rejection are stored in
% the event array).
rejeegplot = [];
if ~isempty(rej) %assuming nrejection x 2 (2 = begin end)
s = size(rej, 1);
rejeegplot = [ rej(3:4) colnew*ones(s,1) zeros(s, chans) ];
end;
% pooling previous rejections
if ~isempty(oldrej)
tmp = [ oldrej(:, 3:4) colold*ones(s,1) zeros(size(oldrej,1), chans) ];
rejeegplot = [rejeegplot; tmp];
end;
end;
if isempty(varargin)
eegplot(data, 'winlength', 5, 'position', [100 300 800 500], 'winrej', rejeegplot, 'xgrid', 'off');
else
eegplot(data, 'winlength', 5, 'position', [100 300 800 500], 'winrej', rejeegplot, 'xgrid', 'off', varargin{:} );
end;
return;
% convert eeglab format to eeplot format of rejection window
% ----------------------------------------------------------
function rejeegplot = trial2eegplot( rej, rejE, pnts, color)
rejeegplot = zeros(length(rej), size(rejE,2)+5);
rejeegplot(:, 6:end) = rejE;
rejeegplot(:, 1) = (rej(:)-1)*pnts;
rejeegplot(:, 2) = rej(:)*pnts-1;
rejeegplot(:, 3:5) = ones(size(rejeegplot,1),1)*color;
return
|
github
|
ZijingMao/baselineeegtest-master
|
pop_chancoresp.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_chancoresp.m
| 17,056 |
utf_8
|
fd71daf5fecf686e892f204c0f95cf38
|
% pop_chancoresp() - define correspondances between two channel locations structures
% (EEG.chanlocs) automatically (by matching channel labels)
% else using a user input gui.
% Usage:
% >> [chanlist1 chanlist2] = pop_chancoresp(chanstruct1, chanstruc2, 'key', 'val', ...);
%
% Inputs:
% chanstruct1 - first (new) channel locations structure (EEG.chanlocs).
% For details, >> help readlocs
% chanstruct2 - second (reference) chanlocs structure.
%
% Optional parameters:
% 'gui' - ['on'|'off'] display gui or not ('on' -> yes)
% 'autoselect' - ['none'|'fiducials'|'all'] automatically pair channels
% 'chaninfo1' - EEG.chaninfo structure for first (new) EEG.chanlocs
% 'chaninfo2' - EEG.chaninfo structure for second (reference) EEG.chanlocs
% 'chanlist1' - [integer] selected channel to pair in the graphic interface
% for the first channel structure. This requires the input
% 'chanlist2' below.
% 'chanlist2' - [integer] selected channel to pair in the graphic interface
% for the first channel structure. This requires the input
% requires the input 'chanlist1' that must be of the same length.
% Output:
% chanlist1 - [int vector] indices of selected channels from first (new) EEG.chanlocs
% chanlist2 - [int vector] selected channels from second (reference) EEG.chanlocs
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2005
% Copyright (C) 2005 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [chanlistout1, chanlistout2, thirdout, outfourth] = pop_chancoresp(chans1, chans2, varargin);
if nargin < 2
help pop_chancoresp;
return;
end;
chanlistout1 = [];
chanlistout2 = [];
% process sub command
% -------------------
if isstr(chans1)
if strcmpi(chans1, 'pair')
[chanlistout1, chanlistout2, thirdout, outfourth] = pair(chans2, varargin{:});
elseif strcmpi(chans1, 'unpair')
[chanlistout1, chanlistout2, thirdout, outfourth] = unpair(chans2, varargin{:});
elseif strcmpi(chans1, 'clear')
[chanlistout1, chanlistout2, thirdout, outfourth] = clearchans(chans2, varargin{:});
elseif strcmpi(chans1, 'auto')
[chanlistout1, chanlistout2, thirdout, outfourth] = autoselect(chans2, varargin{:});
end;
return;
end;
g = finputcheck(varargin, { 'autoselect' 'string' {'none';'fiducials';'all'} 'all';
'chanlist1' 'integer' [1 Inf] [];
'chanlist2' 'integer' [1 Inf] [];
'chaninfo1' '' [] [];
'chaninfo2' '' [] [];
'gui' 'string' { 'on';'off' } 'on' } );
if isstr(g), error(g); end;
g.chanstruct1 = chans1;
g.chanstruct2 = chans2;
if length(g.chanlist1) ~= length(g.chanlist2)
error('input arguments ''chanlist1'' and ''chanlist2'' must have the same length');
end;
% decode different input formats
% ------------------------------
if isstruct(chans1)
if isfield(chans1, 'label') % fieldtrip
chanstr1 = chans1.label;
chanstr2 = chans2.label;
else % EEGLAB
chanstr1 = { chans1.labels };
chanstr2 = { chans2.labels };
end;
else % only channel labels
chanstr1 = chans1;
chanstr2 = chans2;
end;
% convert selection to integer
% ----------------------------
if isempty(g.chanlist1)
if strcmpi(g.autoselect, 'fiducials')
% find fiducials in both channel location strustures
% --------------------------------------------------
naz1 = strmatch('nz', lower( chanstr1 ), 'exact'); if isempty(naz1), naz1 = strmatch('nasion', lower( chanstr1 ), 'exact'); end; if isempty(naz1), naz1 = strmatch('fidnz', lower( chanstr1 ), 'exact'); end;
naz2 = strmatch('nz', lower( chanstr2 ), 'exact'); if isempty(naz2), naz2 = strmatch('nasion', lower( chanstr2 ), 'exact'); end; if isempty(naz2), naz2 = strmatch('fidnz', lower( chanstr2 ), 'exact'); end;
lpa1 = strmatch('lpa', lower( chanstr1 ), 'exact'); if isempty(lpa1), lpa1 = strmatch('left', lower( chanstr1 ), 'exact'); end; if isempty(lpa1), lpa1 = strmatch('fidt10', lower( chanstr1 ), 'exact'); end;
lpa2 = strmatch('lpa', lower( chanstr2 ), 'exact'); if isempty(lpa2), lpa2 = strmatch('left', lower( chanstr2 ), 'exact'); end; if isempty(lpa2), lpa2 = strmatch('fidt10', lower( chanstr2 ), 'exact'); end;
rpa1 = strmatch('rpa', lower( chanstr1 ), 'exact'); if isempty(rpa1), rpa1 = strmatch('right', lower( chanstr1 ), 'exact'); end; if isempty(rpa1), rpa1 = strmatch('fidt9', lower( chanstr1 ), 'exact'); end;
rpa2 = strmatch('rpa', lower( chanstr2 ), 'exact'); if isempty(rpa2), rpa2 = strmatch('right', lower( chanstr2 ), 'exact'); end; if isempty(rpa2), rpa2 = strmatch('fidt9', lower( chanstr2 ), 'exact'); end;
g.chanlist1 = [ naz1 lpa1 rpa1 ];
g.chanlist2 = [ naz2 lpa2 rpa2 ];
if length(g.chanlist1) ~= length(g.chanlist2) | length(g.chanlist1) == 0
disp('Warning: could not find fiducials in at least one of the channel location structure');
g.chanlist1 = [];
g.chanlist2 = [];
end;
elseif strcmpi(g.autoselect, 'all')
% find common channels in both channel location strustures
% --------------------------------------------------------
chanstr2low = lower( chanstr2 );
chanstr1low = lower( chanstr1 );
for index = 1:length( chanstr1 )
ind = strmatch(chanstr1low{index}, chanstr2low, 'exact' );
if ~isempty(ind)
g.chanlist1(end+1) = index;
g.chanlist2(end+1) = ind;
end;
end;
end;
end;
% plot
% ----
if strcmpi(g.gui, 'off')
chanlistout1 = g.chanlist1;
chanlistout2 = g.chanlist2;
return;
end;
try, g.promptstring; catch, g.promptstring = ''; end;
try, g.selectionmode; catch, g.selectionmode = 'multiple'; end;
try, g.listsize; catch, g.listsize = []; end;
try, g.initialvalue; catch, g.initialvalue = []; end;
try, g.name; catch, g.name = ''; end;
g.chanstr1 = chanstr1;
g.chanstr2 = chanstr2;
fig = figure('visible', 'off');
set(fig, 'name', 'Select corresponding channels to pair');
% make text for list
% ------------------
[ g.newchanstr1 g.newchanstr2 ] = makelisttext( chanstr1, chanstr2, g.chanlist1, g.chanlist2);
% callback for paring and unpairing
% ---------------------------------
cb_pair = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'tmpval1 = get(findobj(gcbf, ''tag'', ''list1''), ''value'');' ...
'tmpval2 = get(findobj(gcbf, ''tag'', ''list2''), ''value'');' ...
'[tmpdat.newchanstr1{tmpval1}, tmpdat.newchanstr2{tmpval2}, tmpdat.chanlist1, tmpdat.chanlist2] = pop_chancoresp(''pair'', tmpval1, tmpval2, tmpdat.chanstr1, tmpdat.chanstr2, tmpdat.chanlist1, tmpdat.chanlist2, tmpdat.newchanstr1{tmpval1}, tmpdat.newchanstr2{tmpval2});' ...
'set(findobj(gcbf, ''tag'', ''list1''), ''string'', tmpdat.newchanstr1);' ...
'set(findobj(gcbf, ''tag'', ''list2''), ''string'', tmpdat.newchanstr2);' ...
'set(gcbf, ''userdata'', tmpdat);' ...
'clear tmpdat tmpval1 tmpval2;' ];
cb_unpair = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'tmpval1 = get(findobj(gcbf, ''tag'', ''list1''), ''value'');' ...
'tmpval2 = get(findobj(gcbf, ''tag'', ''list2''), ''value'');' ...
'[tmpdat.newchanstr1{tmpval1}, tmpdat.newchanstr2{tmpval2}, tmpdat.chanlist1, tmpdat.chanlist2] = pop_chancoresp(''unpair'', tmpval1, tmpval2, tmpdat.chanstr1, tmpdat.chanstr2, tmpdat.chanlist1, tmpdat.chanlist2, tmpdat.newchanstr1{tmpval1}, tmpdat.newchanstr2{tmpval2});' ...
'set(findobj(gcbf, ''tag'', ''list1''), ''string'', tmpdat.newchanstr1);' ...
'set(findobj(gcbf, ''tag'', ''list2''), ''string'', tmpdat.newchanstr2);' ...
'set(gcbf, ''userdata'', tmpdat);' ...
'clear tmpdat tmpval1 tmpval2;' ];
cb_plot1 = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'figure; topoplot([], tmpdat.chanstruct1, ''style'', ''blank'', ''drawaxis'', ''on'', ' ...
'''electrodes'', ''labelpoint'', ''chaninfo'', tmpdat.chaninfo1);' ];
cb_plot2 = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'figure; topoplot([], tmpdat.chanstruct2, ''style'', ''blank'', ''drawaxis'', ''on'', ' ...
'''electrodes'', ''labelpoint'', ''chaninfo'', tmpdat.chaninfo2);' ];
cb_list1 = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'tmpval = get(findobj(gcbf, ''tag'', ''list1''), ''value'');' ...
'tmppos = find(tmpdat.chanlist1 == tmpval);' ...
'if ~isempty(tmppos), set(findobj(gcbf, ''tag'', ''list2''), ''value'', tmpdat.chanlist2(tmppos)); end;' ...
'clear tmpdat tmpval tmppos;' ];
cb_list2 = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'tmpval = get(findobj(gcbf, ''tag'', ''list2''), ''value'');' ...
'tmppos = find(tmpdat.chanlist2 == tmpval);' ...
'if ~isempty(tmppos), set(findobj(gcbf, ''tag'', ''list1''), ''value'', tmpdat.chanlist1(tmppos)); end;' ...
'clear tmpdat tmpval tmppos;' ];
cb_clear = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'[tmpdat.newchanstr1, tmpdat.newchanstr2, tmpdat.chanlist1, tmpdat.chanlist2] = pop_chancoresp(''clear'', tmpdat.chanstr1, tmpdat.chanstr2);' ...
'set(gcbf, ''userdata'', tmpdat);' ...
'set(findobj(gcbf, ''tag'', ''list1''), ''string'', tmpdat.newchanstr1);' ...
'set(findobj(gcbf, ''tag'', ''list2''), ''string'', tmpdat.newchanstr2);' ...
'set(gcbf, ''userdata'', tmpdat);' ...
'clear tmpdat;' ];
cb_auto = [ 'tmpdat = get(gcbf, ''userdata'');' ...
'[tmpdat.newchanstr1, tmpdat.newchanstr2, tmpdat.chanlist1, tmpdat.chanlist2] = pop_chancoresp(''auto'', tmpdat.chanstr1, tmpdat.chanstr2, tmpdat.newchanstr1, tmpdat.newchanstr2, tmpdat.chanlist1, tmpdat.chanlist2);' ...
'set(gcbf, ''userdata'', tmpdat);' ...
'set(findobj(gcbf, ''tag'', ''list1''), ''string'', tmpdat.newchanstr1);' ...
'set(findobj(gcbf, ''tag'', ''list2''), ''string'', tmpdat.newchanstr2);' ...
'set(gcbf, ''userdata'', tmpdat);' ...
'clear tmpdat;' ];
geometry = {[1 1] [1 1] [1 1] [1 1] [1 1]};
geomvert = [ 1 min(max(length(chanstr1),length(chanstr2)), 10) 1 1 1];
listui = { ...
{ 'Style', 'pushbutton', 'string', 'Plot new montage', 'callback', cb_plot1 } ...
{ 'Style', 'pushbutton', 'string', 'Plot ref montage', 'callback', cb_plot2 } ...
{ 'Style', 'listbox', 'tag', 'list1', 'string', g.newchanstr1, 'value', 1, 'min', 1, 'max', 2, 'callback', cb_list1 } ...
{ 'Style', 'listbox', 'tag', 'list2', 'string', g.newchanstr2, 'value', 1, 'min', 1, 'max', 2, 'callback', cb_list2 } ...
{ 'Style', 'pushbutton', 'string', 'Pair channels' , 'callback', cb_pair } ...
{ 'Style', 'pushbutton', 'string', 'Clear this pair', 'callback', cb_unpair } ...
{ 'Style', 'pushbutton', 'string', 'Clear all pairs' , 'callback', cb_clear } ...
{ 'Style', 'pushbutton', 'string', 'Auto select', 'callback', cb_auto } ...
{ 'Style', 'pushbutton', 'string', 'Cancel', 'callback', 'close(gcbf);' } ...
{ 'Style', 'pushbutton', 'string', 'Ok' , 'tag', 'ok', 'callback', ['set(gcbo, ''userdata'', ''ok'');'] } };
[tmp tmp2 allobj] = supergui( fig, geometry, geomvert, listui{:} );
set(fig, 'userdata', g);
% decode output
% -------------
okbut = findobj( 'parent', fig, 'tag', 'ok');
figure(fig);
drawnow;
waitfor( okbut, 'userdata');
try,
tmpdat = get(fig, 'userdata');
chanlistout1 = tmpdat.chanlist1;
chanlistout2 = tmpdat.chanlist2;
close(fig);
drawnow;
end;
% unpair channels
% ---------------
function [ str1, str2, chanlist1, chanlist2 ] = unpair(ind1, ind2, chanstr1, chanstr2, chanlist1, chanlist2, str1, str2);
if nargin > 4
if isempty(find(chanlist2 == ind2)), disp('Channels not associated'); return; end;
if isempty(find(chanlist1 == ind1)), disp('Channels not associated'); return; end;
end;
str1 = sprintf('%2d - %3s', ind1, chanstr1{ind1});
str2 = sprintf('%2d - %3s', ind2, chanstr2{ind2});
if nargout > 2
tmppos = find( chanlist1 == ind1);
chanlist1(tmppos) = [];
chanlist2(tmppos) = [];
end;
% pair channels
% -------------
function [ str1, str2, chanlist1, chanlist2 ] = pair(ind1, ind2, chanstr1, chanstr2, chanlist1, chanlist2, str1, str2);
if nargin > 4
if ~isempty(find(chanlist2 == ind2)), disp('Channel in second structure already associated'); return; end;
if ~isempty(find(chanlist1 == ind1)), disp('Channel in first structure already associated'); return; end;
end;
str1 = sprintf('%2d - %3s -> %2d - %3s', ind1, chanstr1{ind1}, ind2, chanstr2{ind2});
str2 = sprintf('%2d - %3s -> %2d - %3s', ind2, chanstr2{ind2}, ind1, chanstr1{ind1});
if nargout > 2
chanlist1 = [ chanlist1 ind1 ];
chanlist2 = [ chanlist2 ind2 ];
end;
% make full channel list
% ----------------------
function [ newchanstr1, newchanstr2 ] = makelisttext( chanstr1, chanstr2, chanlist1, chanlist2);
for index = 1:length(chanstr1)
if ismember(index, chanlist1)
pos = find(chanlist1 == index);
newchanstr1{index} = pair( chanlist1(pos), chanlist2(pos), chanstr1, chanstr2 );
else
newchanstr1{index} = sprintf('%2d - %3s', index, chanstr1{index});
end;
end;
for index = 1:length(chanstr2)
if ismember(index, chanlist2)
pos = find(chanlist2 == index);
[tmp newchanstr2{index}] = pair( chanlist1(pos), chanlist2(pos), chanstr1, chanstr2 );
else
newchanstr2{index} = sprintf('%2d - %3s', index, chanstr2{index});
end;
end;
% clear channel pairs
% -------------------
function [ newchanstr1, newchanstr2, chanlist1, chanlist2 ] = clearchans(chanstr1, chanstr2);
chanlist1 = [];
chanlist2 = [];
[ newchanstr1, newchanstr2 ] = makelisttext( chanstr1, chanstr2, chanlist1, chanlist2);
% autoselect channel pairs
% ------------------------
function [ newchanstr1, newchanstr2, chanlist1, chanlist2 ] = autoselect(chanstr1, chanstr2, newchanstr1, newchanstr2, chanlist1, chanlist2);
% GUI for selecting pairs
% -----------------------
listoptions = { 'All channels (same labels)' 'Fiducials (same labels)' 'BIOSEMI -> 10-20' ...
'EGI -> 10-20' };
listui = { { 'style' 'text' 'string' [ 'How to pair channels (click to select)' 10 ] } ...
{ 'style' 'listbox' 'string' listoptions 'value' 1 } };
results = inputgui({ [1 1] }, listui, '', 'Auto select channel pairs', [], 'normal', 2);
% decode results
% --------------
if isempty(results), return; end;
if results{1} == 1 % select all pairs
[chanlist1 chanlist2] = pop_chancoresp(chanstr1, chanstr2, 'autoselect', 'all', 'gui', 'off');
elseif results{1} == 2
[chanlist1 chanlist2] = pop_chancoresp(chanstr1, chanstr2, 'autoselect', 'fiducials', 'gui', 'off');
else
disp('Not implemented yet'); return;
end;
[ newchanstr1, newchanstr2 ] = makelisttext( chanstr1, chanstr2, chanlist1, chanlist2);
|
github
|
ZijingMao/baselineeegtest-master
|
pop_select.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_select.m
| 28,922 |
utf_8
|
b2a1ca749eeecfce5d79c2017bcb7621
|
% pop_select() - given an input EEG dataset structure, output a new EEG data structure
% retaining and/or excluding specified time/latency, data point, channel,
% and/or epoch range(s).
% Usage:
% >> OUTEEG = pop_select(INEEG, 'key1', value1, 'key2', value2 ...);
%
% Graphic interface:
% "Time range" - [edit box] RETAIN only the indicated epoch latency or continuous data
% time range: [low high] in ms, inclusive. For continuous data, several
% time ranges may be specified, separated by semicolons.
% Example: "5 10; 12 EEG.xmax" will retain the indicated
% stretches of continuous data, and remove data portions outside
% the indicated ranges, e.g. from 0 s to 5 s and from 10 s to 12 s.
% Command line equivalent: 'time' (or 'notime' - see below)
% "Time range" - [checkbox] EXCLUDE the indicated latency range(s) from the data.
% For epoched data, it is not possible to remove a range of latencies
% from the middle of the epoch, so either the low and/or the high values
% in the specified latency range (see above) must be at an epoch boundary
% (EEG.xmin, EEGxmax). Command line equivalent: [if checked] 'notime'
% "Point range" - [edit box] RETAIN the indicated data point range(s).
% Same options as for the "Time range" features (above).
% Command line equivalent: 'point' (or 'nopoint' - see below).
% "Point range" - [checkbox] EXCLUDE the indicated point range(s).
% Command line equivalent: [if checked] 'nopoint'
% "Epoch range" - [edit box] RETAIN the indicated data epoch indices in the dataset.
% This checkbox is only visible for epoched datasets.
% Command line equivalent: 'trial' (or 'notrial' - see below)
% "Epoch range" - [checkbox] EXCLUDE the specified data epochs.
% Command line equivalent: [if checked] 'notrial'
% "Channel range" - [edit box] RETAIN the indicated vector of data channels
% Command line equivalent: 'channel' (or 'nochannel' - see below)
% "Channel range" - [checkbox] EXCLUDE the indicated channels.
% Command line equivalent: [if checked] 'nochannel'
% "..." - [button] select channels by name.
% "Scroll dataset" - [button] call the eegplot() function to scroll the
% channel activities in a new window for visual inspection.
% Commandline equivalent: eegplot() - see its help for details.
% Inputs:
% INEEG - input EEG dataset structure
%
% Optional inputs
% 'time' - [min max] in seconds. Epoch latency or continuous data time range
% to retain in the new dataset, (Note: not ms, as in the GUI text entry
% above). For continuous data (only), several time ranges can be specified,
% separated by semicolons. Example: "5 10; 12 EEG.xmax" will retain
% the indicated times ranges, removing data outside the indicated ranges
% e.g. here from 0 to 5 s and from 10 s to 12 s. (See also, 'notime')
% 'notime' - [min max] in seconds. Epoch latency or continuous dataset time range
% to exclude from the new dataset. For continuous data, may be
% [min1 max1; min2 max2; ...] to exclude several time ranges. For epoched
% data, the latency range must include an epoch boundary, as latency
% ranges in the middle of epochs cannot be removed from epoched data.
% 'point' - [min max] epoch or continuous data point range to retain in the new
% dataset. For continuous datasets, this may be [min1 max1; min2 max2; ...]
% to retain several point ranges. (Notes: If both 'point'/'nopoint' and
% 'time' | 'notime' are specified, the 'point' limit values take precedence.
% The 'point' argument was originally a point vector, now deprecated).
% 'nopoint' - [min max] epoch or continuous data point range to exclude in the new dataset.
% For epoched data, the point range must include either the first (0)
% or the last point (EEG.pnts), as a central point range cannot be removed.
% 'trial' - array of trial indices to retain in the new dataset
% 'notrial' - array of trial indices to exclude from the new dataset
% 'sorttrial' - ['on'|'off'] sort trial indices before extracting them (default: 'on').
% 'channel' - vector of channel indices to retain in the new
% dataset. Can also be a cell array of channel names.
% 'nochannel' - vector of channel indices to exclude from the new
% dataset. Can also be a cell array of channel names.
% 'newname' - name for the new dataset (OUTEEG)
%
% Outputs:
% OUTEEG - new EEG dataset structure
%
% Note: This function performs a conjunction (AND) of all its optional inputs.
% Using negative counterparts of all options, any logical combination is
% possible.
%
% Author: Arnaud Delorme, CNL/Salk Institute, 2001; SCCN/INC/UCSD, 2002-
%
% see also: eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 01-26-02 changed the format for events and trial conditions -ad
% 02-04-02 changed display format and allow for negation of inputs -ad
% 02-17-02 removed the event removal -ad
% 03-17-02 added channel info subsets selection -ad
% 03-21-02 added event latency recalculation -ad
function [EEG, com] = pop_select( EEG, varargin);
com = '';
if nargin < 1
help pop_select;
return;
end;
if isempty(EEG(1).data)
disp('Pop_select error: cannot process empty dataset'); return;
end;
if nargin < 2
geometry = { [1 1 1] [1 1 0.25 0.23 0.51] [1 1 0.25 0.23 0.51] [1 1 0.25 0.23 0.51] ...
[1 1 0.25 0.23 0.51] [1] [1 1 1]};
uilist = { ...
{ 'Style', 'text', 'string', 'Select data in:', 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', 'Input desired range', 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', 'on->remove these', 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', 'Time range [min max] (s)', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') }, ...
{ 'Style', 'edit', 'string', '', 'enable', fastif(length(EEG)>1, 'off', 'on') }, ...
{ }, { 'Style', 'checkbox', 'string', ' ', 'enable', fastif(length(EEG)>1, 'off', 'on') },{ }, ...
...
{ 'Style', 'text', 'string', 'Point range (ex: [1 10])', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') }, ...
{ 'Style', 'edit', 'string', '', 'enable', fastif(length(EEG)>1, 'off', 'on') }, ...
{ }, { 'Style', 'checkbox', 'string', ' ', 'enable', fastif(length(EEG)>1, 'off', 'on') },{ }, ...
...
{ 'Style', 'text', 'string', 'Epoch range (ex: 3:2:10)', 'fontangle', fastif(length(EEG)>1, 'italic', 'normal') }, ...
{ 'Style', 'edit', 'string', '', 'enable', fastif(length(EEG)>1, 'off', 'on') }, ...
{ }, { 'Style', 'checkbox', 'string', ' ', 'enable', fastif(length(EEG)>1, 'off', 'on') },{ }, ...
...
{ 'Style', 'text', 'string', 'Channel range' }, ...
{ 'Style', 'edit', 'string', '', 'tag', 'chans' }, ...
{ }, { 'Style', 'checkbox', 'string', ' ' }, ...
{ 'style' 'pushbutton' 'string' '...', 'enable' fastif(isempty(EEG.chanlocs), 'off', 'on') ...
'callback' 'tmpchanlocs = EEG(1).chanlocs; [tmp tmpval] = pop_chansel({tmpchanlocs.labels}, ''withindex'', ''on''); set(findobj(gcbf, ''tag'', ''chans''), ''string'',tmpval); clear tmp tmpchanlocs tmpval' }, ...
{ }, { }, { 'Style', 'pushbutton', 'string', 'Scroll dataset', 'enable', fastif(length(EEG)>1, 'off', 'on'), 'callback', ...
'eegplot(EEG.data, ''srate'', EEG.srate, ''winlength'', 5, ''limits'', [EEG.xmin EEG.xmax]*1000, ''position'', [100 300 800 500], ''xgrid'', ''off'', ''eloc_file'', EEG.chanlocs);' } {}};
results = inputgui( geometry, uilist, 'pophelp(''pop_select'');', 'Select data -- pop_select()' );
if length(results) == 0, return; end;
% decode inputs
% -------------
args = {};
if ~isempty( results{1} )
if ~results{2}, args = { args{:}, 'time', eval( [ '[' results{1} ']' ] ) };
else args = { args{:}, 'notime', eval( [ '[' results{1} ']' ] ) }; end;
end;
if ~isempty( results{3} )
if ~results{4}, args = { args{:}, 'point', eval( [ '[' results{3} ']' ] ) };
else args = { args{:}, 'nopoint', eval( [ '[' results{3} ']' ] ) }; end;
end;
if ~isempty( results{5} )
if ~results{6}, args = { args{:}, 'trial', eval( [ '[' results{5} ']' ] ) };
else args = { args{:}, 'notrial', eval( [ '[' results{5} ']' ] ) }; end;
end;
if ~isempty( results{7} )
[ chaninds chanlist ] = eeg_decodechan(EEG.chanlocs, results{7});
if isempty(chanlist), chanlist = chaninds; end;
if ~results{8}, args = { args{:}, 'channel' , chanlist };
else args = { args{:}, 'nochannel', chanlist }; end;
end;
else
args = varargin;
end;
%----------------------------AMICA---------------------------------
if isfield(EEG.etc,'amica') && isfield(EEG.etc.amica,'prob_added')
for index = 1:2:length(args)
if strcmpi(args{index}, 'channel')
args{index+1} = [ args{index+1} EEG.nbchan-(0:2*EEG.etc.amica.num_models-1)];
end;
end;
end;
%--------------------------------------------------------------------
% process multiple datasets
% -------------------------
if length(EEG) > 1
[ EEG com ] = eeg_eval( 'pop_select', EEG, 'warning', 'on', 'params', args);
return;
end;
if isempty(EEG.chanlocs), chanlist = [1:EEG.nbchan];
else chanlocs = EEG.chanlocs; chanlist = { chanlocs.labels };
end;
g = finputcheck(args, { 'time' 'real' [] []; ...
'notime' 'real' [] []; ...
'trial' 'integer' [] [1:EEG.trials]; ...
'notrial' 'integer' [] []; ...
'point' 'integer' [] []; ...
'nopoint' 'integer' [] []; ...
'channel' { 'integer','cell' } [] chanlist;
'nochannel' { 'integer','cell' } [] [];
'trialcond' 'integer' [] []; ...
'notrialcond' 'integer' [] []; ...
'sort' 'integer' [] []; ...
'sorttrial' 'string' { 'on','off' } 'on' }, 'pop_select');
if isstr(g), error(g); end;
if ~isempty(g.sort)
if g.sort, g.sorttrial = 'on';
else g.sorttrial = 'off';
end;
end;
if strcmpi(g.sorttrial, 'on')
g.trial = sort(setdiff( g.trial, g.notrial ));
if isempty(g.trial), error('Error: dataset is empty'); end;
else
g.trial(ismember(g.trial,g.notrial)) = [];
% still warn about & remove duplicate trials (may be removed in the future)
[p,q] = unique_bc(g.trial);
if length(p) ~= length(g.trial)
disp('Warning: trial selection contained duplicated elements, which were removed.');
end
g.trial = g.trial(sort(q));
end
if isempty(g.channel) && ~iscell(g.nochannel) && ~iscell(chanlist)
g.channel = [1:EEG.nbchan];
end;
if iscell(g.channel) && ~iscell(g.nochannel) && ~isempty(EEG.chanlocs)
noChannelAsCell = {};
for nochanId = 1:length(g.nochannel)
noChannelAsCell{nochanId} = EEG.chanlocs(g.nochannel(nochanId)).labels;
end;
g.nochannel = noChannelAsCell;
end;
if strcmpi(g.sorttrial, 'on')
if iscell(g.channel)
g.channel = sort(setdiff( lower(g.channel), lower(g.nochannel) ));
else g.channel = sort(setdiff( g.channel, g.nochannel ));
end;
else
g.channel(ismember(lower(g.channel),lower(g.nochannel))) = [];
% still warn about & remove duplicate channels (may be removed in the future)
[p,q] = unique_bc(g.channel);
if length(p) ~= length(g.channel)
disp('Warning: channel selection contained duplicated elements, which were removed.');
end
g.channel = g.channel(sort(q));
end
if ~isempty(EEG.chanlocs)
if strcmpi(g.sorttrial, 'on')
g.channel = eeg_decodechan(EEG.chanlocs, g.channel);
else
% we have to protect the channel order against changes by eeg_decodechan
if iscell(g.channel)
% translate channel names into indices
[inds,names] = eeg_decodechan(EEG.chanlocs, g.channel);
% and sort the indices back into the original order of channel names
[tmp,I] = ismember_bc(lower(g.channel),lower(names));
g.channel = inds(I);
end
end
end;
if ~isempty(g.time) && (g.time(1) < EEG.xmin*1000) && (g.time(2) > EEG.xmax*1000)
error('Wrong time range');
end;
if min(g.trial) < 1 || max( g.trial ) > EEG.trials
error('Wrong trial range');
end;
if ~isempty(g.channel)
if min(double(g.channel)) < 1 || max(double(g.channel)) > EEG.nbchan
error('Wrong channel range');
end;
end;
if size(g.point,2) > 2,
g.point = [g.point(1) g.point(end)];
disp('Warning: vector format for point range is deprecated');
end;
if size(g.nopoint,2) > 2,
g.nopoint = [g.nopoint(1) g.nopoint(end)];
disp('Warning: vector format for point range is deprecated');
end;
if ~isempty( g.point )
g.time = zeros(size(g.point));
for index = 1:length(g.point(:))
g.time(index) = eeg_point2lat(g.point(index), 1, EEG.srate, [EEG.xmin EEG.xmax]);
end;
g.notime = [];
end;
if ~isempty( g.nopoint )
g.notime = zeros(size(g.nopoint));
for index = 1:length(g.nopoint(:))
g.notime(index) = eeg_point2lat(g.nopoint(index), 1, EEG.srate, [EEG.xmin EEG.xmax]);
end;
g.time = [];
end;
if ~isempty( g.notime )
if size(g.notime,2) ~= 2
error('Time/point range must contain 2 columns exactly');
end;
if g.notime(2) == EEG.xmax
g.time = [EEG.xmin g.notime(1)];
else
if g.notime(1) == EEG.xmin
g.time = [g.notime(2) EEG.xmax];
elseif EEG.trials > 1
error('Wrong notime range. Remember that it is not possible to remove a slice of time for data epochs.');
end;
end;
if floor(max(g.notime(:))) > EEG.xmax || min(g.notime(:)) < EEG.xmin
error('Time/point range out of data limits');
end;
end;
if ~isempty(g.time)
if size(g.time,2) ~= 2
error('Time/point range must contain 2 columns exactly');
end;
for index = 1:length(g.time)
if g.time(index) > EEG.xmax
g.time(index) = EEG.xmax;
disp('Upper time limits exceed data, corrected');
elseif g.time(index) < EEG.xmin
g.time(index) = EEG.xmin;
disp('Lower time limits exceed data, corrected');
end;
end;
end;
% select trial values
%--------------------
if ~isempty(g.trialcond)
try, tt = struct( g.trialcond{:} ); catch
error('Trial conditions format error');
end;
ttfields = fieldnames (tt);
for index = 1:length(ttfields)
if ~isfield( EEG.epoch, ttfields{index} )
error([ ttfields{index} 'is not a field of EEG.epoch' ]);
end;
tmpepoch = EEG.epoch;
eval( [ 'Itriallow = find( [ tmpepoch(:).' ttfields{index} ' ] >= tt.' ttfields{index} '(1) );' ] );
eval( [ 'Itrialhigh = find( [ tmpepoch(:).' ttfields{index} ' ] <= tt.' ttfields{index} '(end) );' ] );
Itrialtmp = intersect_bc(Itriallow, Itrialhigh);
g.trial = intersect_bc( g.trial(:)', Itrialtmp(:)');
end;
end;
if isempty(g.trial)
error('Empty dataset, no trial');
end;
if length(g.trial) ~= EEG.trials
fprintf('Removing %d trial(s)...\n', EEG.trials - length(g.trial));
end;
if length(g.channel) ~= EEG.nbchan
fprintf('Removing %d channel(s)...\n', EEG.nbchan - length(g.channel));
end;
try
% For AMICA probabilities...
%-----------------------------------------------------
if isfield(EEG.etc, 'amica') && ~isempty(EEG.etc.amica) && isfield(EEG.etc.amica, 'v_smooth') && ~isempty(EEG.etc.amica.v_smooth) && ~isfield(EEG.etc.amica,'prob_added')
if isfield(EEG.etc.amica, 'num_models') && ~isempty(EEG.etc.amica.num_models)
if size(EEG.data,2) == size(EEG.etc.amica.v_smooth,2) && size(EEG.data,3) == size(EEG.etc.amica.v_smooth,3) && size(EEG.etc.amica.v_smooth,1) == EEG.etc.amica.num_models
EEG = eeg_formatamica(EEG);
%-------------------------------------------
[EEG com] = pop_select(EEG,args{:});
%-------------------------------------------
EEG = eeg_reformatamica(EEG);
EEG = eeg_checkamica(EEG);
return;
else
disp('AMICA probabilities not compatible with size of data, probabilities cannot be rejected')
disp('Resuming rejection...')
end
end
end
% ------------------------------------------------------
catch
warnmsg = strcat('your dataset contains amica information, but the amica plugin is not installed. Continuing and ignoring amica information.');
warning(warnmsg)
end
% recompute latency and epoch number for events
% ---------------------------------------------
if length(g.trial) ~= EEG.trials & ~isempty(EEG.event)
if ~isfield(EEG.event, 'epoch')
disp('Pop_epoch warning: bad event format with epoch dataset, removing events');
EEG.event = [];
else
if isfield(EEG.event, 'epoch')
keepevent = [];
for indexevent = 1:length(EEG.event)
newindex = find( EEG.event(indexevent).epoch == g.trial );% For AMICA probabilities...
%-----------------------------------------------------
try
if isfield(EEG.etc, 'amica') && ~isempty(EEG.etc.amica) && isfield(EEG.etc.amica, 'v_smooth') && ~isempty(EEG.etc.amica.v_smooth) && ~isfield(EEG.etc.amica,'prob_added')
if isfield(EEG.etc.amica, 'num_models') && ~isempty(EEG.etc.amica.num_models)
if size(EEG.data,2) == size(EEG.etc.amica.v_smooth,2) && size(EEG.data,3) == size(EEG.etc.amica.v_smooth,3) && size(EEG.etc.amica.v_smooth,1) == EEG.etc.amica.num_models
EEG = eeg_formatamica(EEG);
%-------------------------------------------
[EEG com] = pop_select(EEG,args{:});
%-------------------------------------------
EEG = eeg_reformatamica(EEG);
EEG = eeg_checkamica(EEG);
return;
else
disp('AMICA probabilities not compatible with size of data, probabilities cannot be rejected')
disp('Resuming rejection...')
end
end
end
catch
warnmsg = strcat('your dataset contains amica information, but the amica plugin is not installed. Continuing and ignoring amica information.');
warning(warnmsg)
end;
% ------------------------------------------------------
if ~isempty(newindex)
keepevent = [keepevent indexevent];
if isfield(EEG.event, 'latency')
EEG.event(indexevent).latency = EEG.event(indexevent).latency - (EEG.event(indexevent).epoch-1)*EEG.pnts + (newindex-1)*EEG.pnts;
end;
EEG.event(indexevent).epoch = newindex;
end;
end;
diffevent = setdiff_bc([1:length(EEG.event)], keepevent);
if ~isempty(diffevent)
disp(['Pop_select: removing ' int2str(length(diffevent)) ' unreferenced events']);
EEG.event(diffevent) = [];
end;
end;
end;
end;
% performing removal
% ------------------
if ~isempty(g.time) | ~isempty(g.notime)
if EEG.trials > 1
% select new time window
% ----------------------
try, tmpevent = EEG.event;
tmpeventlatency = [ tmpevent.latency ];
catch, tmpeventlatency = [];
end;
alllatencies = 1-(EEG.xmin*EEG.srate); % time 0 point
alllatencies = linspace( alllatencies, EEG.pnts*(EEG.trials-1)+alllatencies, EEG.trials);
[EEG.data tmptime indices epochevent]= epoch(EEG.data, alllatencies, ...
[g.time(1) g.time(2)]*EEG.srate, 'allevents', tmpeventlatency);
tmptime = tmptime/EEG.srate;
if g.time(1) ~= tmptime(1) & g.time(2)-1/EEG.srate ~= tmptime(2)
fprintf('pop_select(): time limits have been adjusted to [%3.3f %3.3f] to fit data points limits\n', tmptime(1), tmptime(2)+1/EEG.srate);
end;
EEG.xmin = tmptime(1);
EEG.xmax = tmptime(2);
EEG.pnts = size(EEG.data,2);
alllatencies = alllatencies(indices);
% modify the event structure accordingly (latencies and add epoch field)
% ----------------------------------------------------------------------
allevents = [];
newevent = [];
count = 1;
if ~isempty(epochevent)
newevent = EEG.event(1);
for index=1:EEG.trials
for indexevent = epochevent{index}
newevent(count) = EEG.event(indexevent);
newevent(count).epoch = index;
newevent(count).latency = newevent(count).latency - alllatencies(index) - tmptime(1)*EEG.srate + 1 + EEG.pnts*(index-1);
count = count + 1;
end;
end;
end;
EEG.event = newevent;
% erase event-related fields from the epochs
% ------------------------------------------
if ~isempty(EEG.epoch)
fn = fieldnames(EEG.epoch);
EEG.epoch = rmfield(EEG.epoch,{fn{strmatch('event',fn)}});
end;
else
if isempty(g.notime)
if length(g.time) == 2 && EEG.xmin < 0
disp('Warning: negative minimum time; unchanged to ensure correct latency of initial boundary event');
end;
g.notime = g.time';
g.notime = g.notime(:);
if g.notime(1) ~= 0, g.notime = [EEG.xmin g.notime(:)'];
else g.notime = [g.notime(2:end)'];
end;
if g.time(end) == EEG.xmax, g.notime(end) = [];
else g.notime(end+1) = EEG.xmax;
end;
for index = 1:length(g.notime)
if g.notime(index) ~= 0 & g.notime(index) ~= EEG.xmax
if mod(index,2), g.notime(index) = g.notime(index) + 1/EEG.srate;
else g.notime(index) = g.notime(index) - 1/EEG.srate;
end;
end;
end;
g.notime = reshape(g.notime, 2, length(g.notime)/2)';
end;
nbtimes = length(g.notime(:));
[points,flag] = eeg_lat2point(g.notime(:)', ones(1,nbtimes), EEG.srate, [EEG.xmin EEG.xmax]);
points = reshape(points, size(g.notime));
% fixing if last region is the same
if flag
if ~isempty(find((points(end,1)-points(end,2))== 0)), points(end,:) = []; end;
end
EEG = eeg_eegrej(EEG, points);
end
end;
% performing removal
% ------------------
if ~isequal(g.channel,1:size(EEG.data,1)) || ~isequal(g.trial,1:size(EEG.data,3))
%EEG.data = EEG.data(g.channel, :, g.trial);
% this code belows is prefered for memory mapped files
diff1 = setdiff_bc([1:size(EEG.data,1)], g.channel);
diff2 = setdiff_bc([1:size(EEG.data,3)], g.trial);
if ~isempty(diff1)
EEG.data(diff1, :, :) = [];
end;
if ~isempty(diff2)
EEG.data(:, :, diff2) = [];
end;
end
if ~isempty(EEG.icaact), EEG.icaact = EEG.icaact(:,:,g.trial); end;
EEG.trials = length(g.trial);
EEG.pnts = size(EEG.data,2);
EEG.nbchan = length(g.channel);
if ~isempty(EEG.chanlocs)
EEG.chanlocs = EEG.chanlocs(g.channel);
end;
if ~isempty(EEG.epoch)
EEG.epoch = EEG.epoch( g.trial );
end;
if ~isempty(EEG.specdata)
if length(g.point) == EEG.pnts
EEG.specdata = EEG.specdata(g.channel, :, g.trial);
else
EEG.specdata = [];
fprintf('Warning: spectral data were removed because of the change in the numner of points\n');
end;
end;
% ica specific
% ------------
if ~isempty(EEG.icachansind)
rmchans = setdiff_bc( EEG.icachansind, g.channel ); % channels to remove
% channel sub-indices
% -------------------
icachans = 1:length(EEG.icachansind);
for index = length(rmchans):-1:1
chanind = find(EEG.icachansind == rmchans(index));
icachans(chanind) = [];
end;
% new channels indices
% --------------------
count = 1;
newinds = [];
for index = 1:length(g.channel)
if any(EEG.icachansind == g.channel(index))
newinds(count) = index;
count = count+1;
end;
end;
EEG.icachansind = newinds;
else
icachans = 1:size(EEG.icasphere,2);
end;
if ~isempty(EEG.icawinv)
EEG.icawinv = EEG.icawinv(icachans,:);
EEG.icaweights = pinv(EEG.icawinv);
EEG.icasphere = eye(size(EEG.icaweights,2));
end;
if ~isempty(EEG.specicaact)
if length(g.point) == EEG.pnts
EEG.specicaact = EEG.specicaact(icachans, :, g.trial);
else
EEG.specicaact = [];
fprintf('Warning: spectral ICA data were removed because of the change in the numner of points\n');
end;
end;
% check if only one epoch
% -----------------------
if EEG.trials == 1
if isfield(EEG.event, 'epoch')
EEG.event = rmfield(EEG.event, 'epoch');
end;
EEG.epoch = [];
end;
EEG.reject = [];
EEG.stats = [];
EEG.reject.rejmanual = [];
% for stats, can adapt remove the selected trials and electrodes
% in the future to gain time -----------------------------------
EEG.stats.jp = [];
EEG = eeg_checkset(EEG, 'eventconsistency');
% generate command
% ----------------
if nargout > 1
com = sprintf('EEG = pop_select( %s,%s);', inputname(1), vararg2str(args));
end
return;
% ********* OLD, do not remove any event any more
% ********* in the future maybe do a pack event to remove events not in the time range of any epoch
if ~isempty(EEG.event)
% go to array format if necessary
if isstruct(EEG.event), format = 'struct';
else format = 'array';
end;
switch format, case 'struct', EEG = eventsformat(EEG, 'array'); end;
% keep only events related to the selected trials
Indexes = [];
Ievent = [];
for index = 1:length( g.trial )
currentevents = find( EEG.event(:,2) == g.trial(index));
Indexes = [ Indexes ones(1, length(currentevents))*index ];
Ievent = union_bc( Ievent, currentevents );
end;
EEG.event = EEG.event( Ievent,: );
EEG.event(:,2) = Indexes(:);
switch format, case 'struct', EEG = eventsformat(EEG, 'struct'); end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_rmdat.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_rmdat.m
| 6,763 |
utf_8
|
578b5d17ed738f5495c81cd4d5665da2
|
% pop_rmdat() - Remove continuous data around specific events
%
% Usage:
% >> OUTEEG = pop_rmdat( EEG); % pop-up a data entry window
% >> OUTEEG = pop_rmdat( EEG, typerange, timelimits, invertselection);
%
% Graphic interface:
% "Time-locking event type(s)" - [edit box] Select 'Edit > Event values'
% to see a list of event.type values; else use the push button.
% To use event types containing spaces, enter in single-quotes.
% "..." - [push button] scroll event types.
% "Time limits" - [edit box] epoch latency range [start, end] in seconds relative
% to the event type latency.
%
% Inputs:
% EEG - Input dataset. Data may already be epoched; in this case,
% extract (shorter) subepochs time locked to epoch events.
% typerange - Cell array of event types to time lock to.
% (Note: An event field called 'type' must be defined in
% the 'EEG.event' structure).
% timelimits - Epoch latency limits [start end] in seconds relative to the time-locking event
% {default: [-1 2]}%
% invertselection - [0|1] Invert selection {default:0 is no}
%
% Outputs:
% OUTEEG - output dataset
%
% Authors: Arnaud Delorme, SCCN, INC, UCSD, 2009-
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, com] = pop_rmdat( EEG, events, timelims, invertsel );
if nargin < 1
help pop_rmdat;
return;
end;
com = '';
if isempty(EEG.event)
error( [ 'No event. This function removes data' 10 'based on event latencies' ]);
end;
if isempty(EEG.trials)
error( [ 'This function only works with continuous data' ]);
end;
if ~isfield(EEG.event, 'latency'),
error( 'Absent latency field in event array/structure: must name one of the fields ''latency''');
end;
if nargin < 3
% popup window parameters
% -----------------------
promptstr = { strvcat('Time-locking event type(s) ([]=all):', ...
'Select ''Edit > Event values'' to see type values.'), ...
'Epoch limits [start, end] in seconds:', ...
'Name for the new dataset:', ...
'Out-of-bounds EEG rejection limits ([min max], []=none):' };
cbevent = ['if ~isfield(EEG.event, ''type'')' ...
' errordlg2(''No type field'');' ...
'else' ...
' tmpevent = EEG.event;' ...
' if isnumeric(EEG.event(1).type),' ...
' [tmps,tmpstr] = pop_chansel(unique([ tmpevent.type ]));' ...
' else,' ...
' [tmps,tmpstr] = pop_chansel(unique({ tmpevent.type }));' ...
' end;' ...
' if ~isempty(tmps)' ...
' set(findobj(''parent'', gcbf, ''tag'', ''events''), ''string'', tmpstr);' ...
' end;' ...
'end;' ...
'clear tmps tmpv tmpstr tmpevent tmpfieldnames;' ];
geometry = { [2 1 1.2] [2 1 1.2] };
uilist = { { 'style' 'text' 'string' 'Event type(s) ([]=all)' } ...
{ 'style' 'edit' 'string' '' 'tag' 'events' } ...
{ 'style' 'pushbutton' 'string' '...' 'callback' cbevent } ...
{ 'style' 'text' 'string' 'Time limits [start, end] in sec.' } ...
{ 'style' 'edit' 'string' '-1 1' } ...
{ 'style' 'popupmenu' 'string' 'Keep selected|Remove selected' } };
result = inputgui( geometry, uilist, 'pophelp(''pop_rmdat'')', 'Remove data portions around events - pop_rmdat()');
if length(result) == 0 return; end;
if strcmpi(result{1}, '[]'), result{1} = ''; end;
if ~isempty(result{1})
if strcmpi(result{1}(1),'''') % If event type appears to be in single-quotes, use comma
% and single-quote as delimiter between event types. toby 2.24.2006
% fixed Arnaud May 2006
events = eval( [ '{' result{1} '}' ] );
else events = parsetxt( result{1});
end;
else events = {};
end
timelims = eval( [ '[' result{2} ']' ] );
invertsel = result{3}-1;
end;
tmpevent = EEG.event;
alltypes = { tmpevent.type };
% compute event indices
% ---------------------
allinds = [];
for index = 1:length(events)
inds = strmatch(events{index},alltypes, 'exact');
allinds = [allinds(:); inds(:) ]';
end;
allinds = sort(allinds);
if isempty(allinds)
disp('No event found');
return;
end;
% compute time limits
% -------------------
array = [];
tmpevent = EEG.event;
bnd = strmatch('boundary', lower({tmpevent.type }));
bndlat = [ tmpevent(bnd).latency ];
for bind = 1:length(allinds)
evtlat = EEG.event(allinds(bind)).latency;
evtbeg = evtlat+EEG.srate*timelims(1);
evtend = evtlat+EEG.srate*timelims(2);
if any(bndlat > evtbeg & bndlat < evtend)
% find the closer upper and lower boundaries
bndlattmp = bndlat(bndlat > evtbeg & bndlat < evtend);
diffbound = bndlattmp-evtlat;
allneginds = find(diffbound < 0);
allposinds = find(diffbound > 0);
if ~isempty(allneginds), evtbeg = bndlattmp(allneginds(1)); end;
if ~isempty(allposinds), evtend = bndlattmp(allposinds(1)); end;
fprintf('Boundary found: time limits for event %d reduced from %3.2f to %3.2f\n', allinds(bind), ...
(evtbeg-evtlat)/EEG.srate, (evtend-evtlat)/EEG.srate);
end
if ~isempty(array) && evtbeg < array(end)
array(end) = evtend;
else
array = [ array; evtbeg evtend];
end;
end;
array
if ~isempty(array) && array(1) < 1, array(1) = 1; end;
if ~isempty(array) && array(end) > EEG.pnts, array(end) = EEG.pnts; end;
if isempty(array)
disp('No event found');
return;
end;
if invertsel
EEG = pop_select(EEG, 'notime', (array-1)/EEG.srate);
else
EEG = pop_select(EEG, 'time', (array-1)/EEG.srate);
end;
% generate output command
% -----------------------
com = sprintf('EEG = pop_rmdat( EEG, %s);', vararg2str( { events timelims invertsel } ));
|
github
|
ZijingMao/baselineeegtest-master
|
pop_editeventfield.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_editeventfield.m
| 21,851 |
utf_8
|
71f72e83e89bf49e4935579619263775
|
% pop_editeventfield() - Add/remove/rename/modify a field in the event structure
% of an EEG dataset. Can also be used to append new events to the end of the
% event structure or to delete all current events. If the dataset is
% the only input, a window pops up to ask for relevant parameter values.
%
% Usage: >> [EEG] = pop_editeventfield( EEG, 'key1', 'value1', ...);
%
% Input:
% EEG - input dataset
%
% Optional inputs:
% 'FIELDNAME_X' - [ 'filename'|vector ]. Name of a current or new
% user-defined event field. The ascii file, vector variable,
% or explicit numeric vector should contain values for this field
% for all events specified in 'indices' (below) or in new events
% appended to the dataset (if 'indices' not specified). If one arg
% value is given, it will be used for all the specified events.
% If the arg is [], the named field is *removed* from all the
% specified (or new) events. Use this option to add a new field to
% all events in the dataset, or to modify the field values of specified
% events, to specify field information for new events appended to
% the event structure, or to remove an event field. For example,
% 'FIELDNAME_X' may be 'latency', 'type', 'duration'.
% 'latency' - [ 'filename'|vector ] example of field name (see description above).
% 'type' - [ 'filename'|vector ] example of field name (see description above).
% 'duration' - [ 'filename'|vector ] example of field name (see description above).
% 'FIELDNAME_X_info' - new comment string for field FIELDNAME_X.
% 'latency_info' - description string for the latency field.
% 'type_info' - description string for the type field.
% 'duration_info' - description string for the duration field.
% 'indices' - [vector of event indices] The indices of the events to modify.
% If adding a new event field, events not listed here
% will have an empty field value IF they are not in an epoch
% containing events whose field value is specified. However,
% if adding a new (FIELDNAME) field to an epoched dataset,
% and the field value for only one event in some data epoch is
% specified, then the other events in the same epoch will be given
% the specified value. If field values of more than one, but not all
% the events in an epoch are specified, then unspecified events at
% the beginning of the epoch will be given the value of the first
% specified event, unspecified epoch events after this event will
% be given the field value of the second specified epoch event, etc.
% {default|[]: modify all events in the dataset}
% 'rename' - ['FIELDNAME1->FIELDNAME2'] rename field 'FIELDNAME1' to
% field 'FIELDNAME2'. Ex: { 'rename', 'blocktype->condition' }.
% 'delold' - ['yes'|'no'] 'yes' = delete ALL previous events. {default: 'no'}
% 'timeunit' - [latency field time unit in fraction of seconds]. Ex: 1e-3 ->
% read specified latencies as msec {default: 1 (-->seconds)}
% 'skipline' - number of leading text file lines to skip in named text files.
% {default: 0}.
% 'delim' - delimiting characters in named text files {default: tabs and spaces}
%
% Outputs:
% EEG - dataset with updated event field
%
% Example: EEG = pop_editeventfield(EEG, 'type', 1, ...
% 'sleepstage', 'sleepstage_values.txt', ...
% 'latency', [100 130 123 400],'timeunit',1e-3);
% % Append 4 events to the EEG struct, all of type 1, at the latencies
% % given (in msec) with user-defined field ('sleepstage') values read
% % from a one-column ascii file ('sleepstage_values.txt').
%
% Example: EEG = pop_editeventfield(EEG, 'indices', 1:2:3277, ...
% 'sleepstage', 'sleepstage_values.txt');
% % Add a new 'sleepstage' field to all events in the EEG struct.
% % Read 'sleepstage' field values for odd-numbered events from a one-column
% % ascii file ('sleepstage_values.txt') -- even-numbered % events will have
% % an empty 'sleepstage' value (unless the data are epoched, see 'indices' above).
%
% Note: To save events into a readable table, first convert them to 'array' format,
% then save the array.
% >> events = eeg_eventformat(EEG.event, 'array');
% >> save -ascii myevents.txt events
%
% Author: Arnaud Delorme & Scott Makeig, CNL / Salk Institute, 9 Feb 2002-
%
% See also: pop_importevent(), eeg_eventformat(), pop_selectevent()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 9 Feb 2002, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%02/13/2001 fix bug if EEG.event is empty -ad
%03/12/2001 add timeunit option -ad
%03/18/2001 debug rename option -ad & sm
%03/18/2001 correct allignment problem -ad & ja
function [EEG, com] = pop_editeventfield(EEG, varargin);
com ='';
if nargin < 1
help pop_editeventfield;
return;
end;
if isempty(EEG.data)
error('Setevent error: cannot process empty dataset');
end;
I = [];
% remove the event field
% ----------------------
if ~isempty(EEG.event),
allfields = fieldnames(EEG.event);
ind1 = strmatch('urevent', allfields, 'exact');
ind2 = strmatch('epoch', allfields, 'exact');
allfields([ind1 ind2]) = [];
try, EEG.eventdescription([ind1 ind2]) = []; catch, end;
else
allfields = { 'type' 'latency' };
end;
if nargin<2
commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
'if filename ~=0,' ...
' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ...
'end;' ...
'clear filename filepath tagtest;' ];
uilist = { ...
{ 'Style', 'text', 'string', 'Edit fields:', 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', 'Edit description', 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', sprintf('New values (file or array containing %d values)', length(EEG.event)), 'fontweight', 'bold' }, ...
{ 'Style', 'text', 'string', 'Delete field', 'fontweight', 'bold' } ...
};
geometry = { [1.05 1.05 2 0.8] };
listboxtext = { 'No field selected' };
txt_warn = 'warndlg2(strvcat(''Warning: deleting/renaming this field might cause EEGLAB'', ''to be unstable. Some functionalities will also be lost.''));';
cb_warn2 = [ 'strtmp = get(gcbo, ''string''); if ~isempty(strmatch(strtmp(get(gcbo, ''value'')), { ''latency'' ''type''}, ''exact'')),' txt_warn 'end;' ];
for index = 1:length(allfields)
geometry = { geometry{:} [1 1 1 0.7 0.2 0.32 0.2] };
description = '';
try,
description = fastif(isempty(EEG.eventdescription{index}), '', EEG.eventdescription{index});
description = description(1,:);
tmplines = find(description == 10);
if ~isempty(tmplines), description = description(1:tmplines(1)-1); end;
catch, end;
if strcmp(allfields{index}, 'latency') || strcmp(allfields{index}, 'type')
cb_warn = { 'callback' [ 'if get(gcbo, ''value''),' txt_warn 'end;' ] };
else cb_warn = { };
end;
if strcmp(allfields{index}, 'latency')
tmpfield = [ allfields{index} '(s)' ];
elseif strcmp(allfields{index}, 'duration')
tmpfield = [ allfields{index} '(s)' ];
else
tmpfield = allfields{index};
end;
uilist = { uilist{:}, ...
{ 'Style', 'text', 'string', tmpfield }, ...
{ 'Style', 'pushbutton', 'string', description, 'callback', ...
[ 'tmpuserdata = get(gcf, ''userdata'');' ...
'tmpuserdata{' int2str(index) '} = pop_comments(tmpuserdata{' int2str(index) ...
'}, ''Comments on event field: ' allfields{index} ''');' ...
'set(gcbo, ''string'', tmpuserdata{' int2str(index) '});' ...
'set(gcf, ''userdata'', tmpuserdata); clear tmpuserdata;' ] }, ...
{ 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', allfields{index} }, ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', ['tagtest = ''' allfields{index} ''';' commandload ] }, ...
{ }, { 'Style', 'checkbox', 'string', ' ', cb_warn{:} }, { } };
listboxtext = { listboxtext{:} allfields{index} };
end;
index = length(allfields) + 1;
uilist = { uilist{:}, ...
{ 'Style', 'edit', 'string', ''}, ...
{ 'Style', 'pushbutton', 'string', '', 'callback', ...
[ 'tmpuserdata = get(gcf, ''userdata'');' ...
'tmpuserdata{' int2str(index) '} = pop_comments(tmpuserdata{' int2str(index) ...
'}, ''Comments on new event field:'');' ...
'set(gcbo, ''string'', tmpuserdata{' int2str(index) '});' ...
'set(gcf, ''userdata'', tmpuserdata); clear tmpuserdata;' ] }, ...
{ 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'newfield' }, ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', ['tagtest = ''newfield'';' commandload ] }, ...
{ 'Style', 'text', 'string', '-> add field'} ...
{ } ...
{ 'Style', 'text', 'string', 'Rename field', 'fontweight', 'bold' }, ...
{ 'Style', 'popupmenu', 'string', listboxtext 'callback' cb_warn2 }, ...
{ 'Style', 'text', 'string', 'as', 'fontweight', 'bold' }, ...
{ 'Style', 'edit', 'string', '' } ...
fastif(isunix,{ 'Style', 'text', 'string', '(Click on field name to select it!)' },{ })};
geometry = { geometry{:} [1 1 1 0.7 0.72] [1] [1 1.2 0.6 1 2] };
descriptions = EEG.eventdescription;
if isempty(descriptions), descriptions = { '' '' }; end;
[results userdat ]= inputgui( geometry, uilist, 'pophelp(''pop_editeventfield'');', ...
'Edit event field(s) -- pop_editeventfield()', { descriptions{:} '' } );
if length(results) == 0, return; end;
% decode top inputs
% -----------------
args = { };
% dealing with existing fields
%-----------------------------
for index = 1:length(allfields)
if results{index*2} == 1, args = { args{:}, allfields{index}, [] };
else
if ~isempty( results{index*2-1} )
if exist(results{index*2-1}) == 2, args = { args{:}, allfields{index}, [ results{index*2-1} ] }; % file
else args = { args{:}, allfields{index}, results{index*2-1} }; end;
end;
try,
if ~strcmp( userdat{index}, EEG.eventdescription{index})
args = { args{:}, [ allfields{index} 'info' ], userdat{index} };
end;
catch, end;
end;
end;
% dealing with the new field
%---------------------------
sub = 3;
if ~isempty( results{end-sub} )
args = { args{:}, results{end-sub}, results{end-sub+1} }; % file
end;
% handle rename
% -------------
if results{end-1} ~= 1, args = { args{:}, 'rename', [ allfields{results{end-1}-1} '->' results{end} ] }; end;
else % no interactive inputs
args = varargin;
% scan args to modify array/file format
% array are transformed into string
% files are transformed into string of string
% (this is usefull to build the string command for the function)
% --------------------------------------------------------------
for index=1:2:length(args)
if iscell(args{index+1}), args{index+1} = { args{index+1} }; end; % double nested
if isstr(args{index+1}) args{index+1} = args{index+1}; % string
end;
end;
end;
% create structure
% ----------------
try, g = struct(args{:});
catch, disp('pop_editeventfield(): wrong syntax in function arguments'); return;
end;
% test the presence of variables
% ------------------------------
try, g.skipline; catch, g.skipline = 0; end;
try, g.indices; catch, g.indices = [1:length(EEG.event)]; end;
try, g.delold; catch, g.delold = 'no'; end;
try, g.timeunit; catch, g.timeunit = 1; end;
try, g.delim; catch, g.delim = char([9 32]); end;
if isstr(g.indices), g.indices = eval([ '[' g.indices ']' ]); end;
tmpfields = fieldnames(g);
% scan all the fields of g
% ------------------------
for curfield = tmpfields'
if ~isempty(EEG.event), allfields = fieldnames(EEG.event);
else allfields = {}; end;
switch lower(curfield{1})
case { 'append' 'delold', 'fields', 'skipline', 'indices', 'timeunit', 'delim' }, ; % do nothing now
case 'rename',
if isempty( findstr('->',g.rename) ),
disp('warning pop_editeventfield() bad syntax for ''rename'', ignoring input');
else
oldname = g.rename(1:findstr('->',g.rename)-1);
newname = g.rename(findstr('->',g.rename)+2:end);
indexmatch = strmatch(oldname, allfields);
if isempty(indexmatch), disp('pop_editeventfield() warning: name not found for rename');
else
for index = 1:length(EEG.event)
eval([ 'EEG.event(index).' newname '=EEG.event(index).' oldname ';']);
end;
EEG.event = rmfield(EEG.event, oldname);
end;
if isfield(EEG, 'urevent')
disp('pop_editeventfield() warning: field name not renamed in urevent structure');
end;
end;
otherwise, % user defined field command
% --------------------------
infofield = findstr(curfield{1}, 'info');
if ~isempty(infofield) & infofield == length( curfield{1} )-3
% description of a field
% ----------------------
fieldname = curfield{1}(1:infofield-1);
indexmatch = strmatch( fieldname, allfields);
if isempty( indexmatch )
disp(['pop_editeventfield() warning: Field ' fieldname ' not found to add description, ignoring']);
else
EEG.eventdescription{indexmatch} = getfield(g, curfield{1});
end;
else
% not an field for description
% ----------------------------
if isempty( getfield(g, curfield{1}) ) % delete
indexmatch = strmatch( curfield{1}, allfields);
if isempty( indexmatch )
disp(['pop_editeventfield() warning: Field ''' curfield{1} ''' not found for deletion, ignoring']);
else
EEG.event = rmfield(EEG.event, curfield{1});
allfields(indexmatch) = [];
if isfield(EEG, 'urevent')
fprintf('pop_editeventfield() warning: field ''%s'' not deleted from urevent structure\n', curfield{1} );
end;
try,
EEG.eventdescription(indexmatch) = [];
catch, end;
end;
else % interpret
switch g.delold % delete old events
case 'yes'
EEG.event = load_file_or_array( getfield(g, curfield{1}), g.skipline, g.delim );
allfields = { curfield{1} };
EEG.event = eeg_eventformat(EEG.event, 'struct', allfields);
EEG.event = recomputelatency( EEG.event, 1:length(EEG.event), EEG.srate, g.timeunit);
EEG = eeg_checkset(EEG, 'makeur');
case 'no' % match existing fields
% ---------------------
tmparray = load_file_or_array( getfield(g, curfield{1}), g.skipline, g.delim );
if isempty(g.indices) g.indices = [1:size(tmparray(:),1)] + length(EEG.event); end;
indexmatch = strmatch(curfield{1}, allfields);
if isempty(indexmatch) % no match
disp(['pop_editeventfield(): creating new field ''' curfield{1} '''' ]);
end;
try
EEG.event = setstruct(EEG.event, curfield{1}, g.indices, [ tmparray{:} ]);
catch,
error('Wrong size for input array');
end;
if strcmp(curfield{1}, 'latency')
EEG.event = recomputelatency( EEG.event, g.indices, EEG.srate, g.timeunit);
end;
if strcmp(curfield{1}, 'duration')
for indtmp = 1:length(EEG.event)
EEG.event(indtmp).duration = EEG.event(indtmp).duration/EEG.srate;
end;
end;
if isfield(EEG, 'urevent')
disp('pop-editeventfield(): updating urevent structure');
try
tmpevent = EEG.event;
for indtmp = g.indices(:)'
if ~isempty(EEG.event(indtmp).urevent)
tmpval = getfield (EEG.event, {indtmp}, curfield{1});
EEG.urevent = setfield (EEG.urevent, { tmpevent(indtmp).urevent }, ...
curfield{1}, tmpval);
end;
end;
catch,
disp('pop_editeventfield(): problem while updating urevent structure');
end;
end;
end;
end;
end;
end;
end;
if isempty(EEG.event) % usefull 0xNB empty structure
EEG.event = [];
end;
EEG = eeg_checkset(EEG, 'eventconsistency');
% generate the output command
% ---------------------------
com = sprintf('%s = pop_editeventfield( %s, %s);', inputname(1), inputname(1), vararg2str(args));
% interpret the variable name
% ---------------------------
function str = str2str( array )
str = '';
for index = 1:size(array,1)
str = [ str ', ''' array(index,:) '''' ];
end;
if size(array,1) > 1
str = [ 'strvcat(' str(2:end) ')'];
else
str = str(2:end);
end;
return;
% interpret the variable name
% ---------------------------
function array = load_file_or_array( varname, skipline, delim );
if isstr(varname)
if exist(varname) == 2 % mean that it is a filename
% --------------------------
array = loadtxt( varname, 'skipline', skipline, 'delim', delim);
else % variable in the global workspace
% --------------------------
array = evalin('base', varname);
if ~iscell(array)
array = mattocell(array, ones(1, size(array,1)), ones(1, size(array,2)));
end;
end;
else
array = mattocell(varname);
end;
return;
% update latency values
% ---------------------
function event = recomputelatency( event, indices, srate, timeunit);
if ~isfield(event, 'latency'), return; end;
for index = indices
event(index).latency = event(index).latency*srate*timeunit+1;
end;
% create new field names
% ----------------------
function epochfield = getnewfields( epochfield, nbfields )
count = 1;
while nbfields > 0
if isempty( strmatch([ 'var' int2str(count) ], epochfield ) )
epochfield = { epochfield{:} [ 'var' int2str(count) ] };
nbfields = nbfields-1;
else count = count+1;
end;
end;
return;
function var = setstruct( var, fieldname, indices, values )
if exist('indices') ~= 1, indices = 1:length(var); end;
if length(values) > 1
for index = 1:length(indices)
var = setfield(var, {indices(index)}, fieldname, values(index));
end;
else
for index = 1:length(indices)
var = setfield(var, {indices(index)}, fieldname, values);
end;
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_mergelocs_diffstruct.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_mergelocs_diffstruct.m
| 5,083 |
utf_8
|
91e039a2591913d015acd76805b6b6ff
|
% eeg_mergelocs() - merge channel structure while preserving channel
% order
%
% >> mergedlocs = eeg_mergelocs(loc1, loc2, loc3, ...);
%
% Inputs:
% loc1 - EEGLAB channel location structure
% loc2 - second EEGLAB channel location structure
%
% Output:
% mergedlocs - merged channel location structure
%
% Author: Arnaud Delorme, August 2006
% Copyright (C) Arnaud Delorme, CERCO, 2006, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [alllocs warn] = eeg_mergelocs(varargin)
persistent warning_shown;
warn = 0;
% sort by length
% --------------
len = cellfun(@length, varargin);
[tmp so] = sort(len, 2, 'descend');
varargin = varargin(so);
alllocs = varargin{1};
for index = 2:length(varargin)
% fuse while preserving order (assumes the same channel order)
% ------------------------------------------------------------
tmplocs = varargin{index};
newlocs = myunion(alllocs, tmplocs);
if length(newlocs) > length(union({ alllocs.labels }, { tmplocs.labels }))
warn = 1;
if isempty(warning_shown)
disp('Warning: different channel montage order for the different datasets');
warning_shown = 1;
end;
% trying to preserve order of the longest array
%----------------------------------------------
if length(alllocs) < length(tmplocs)
tmp = alllocs;
alllocs = tmplocs;
tmplocs = tmp;
end;
allchans = { alllocs.labels tmplocs.labels };
[uniquechan ord1 ord2 ] = unique_bc( allchans );
[tmp rminds] = intersect_bc( uniquechan, { alllocs.labels });
ord1(rminds) = [];
tmplocsind = ord1-length(alllocs);
newlocs = concatlocs(alllocs, tmplocs(tmplocsind));
end;
alllocs = newlocs;
end;
% union of two channel location structure
% without loosing the order information
% ---------------------------------------
function alllocs = myunion(locs1, locs2)
labs1 = { locs1.labels };
labs2 = { locs2.labels };
count1 = 1;
count2 = 1;
count3 = 1;
alllocs = locs1; alllocs(:) = [];
while count1 <= length(locs1) | count2 <= length(locs2)
if count1 > length(locs1)
alllocs = copyfields(alllocs, count3, locs2(count2));
%alllocs(count3) = locs2(count2);
count2 = count2 + 1;
count3 = count3 + 1;
elseif count2 > length(locs2)
alllocs = copyfields(alllocs, count3, locs1(count1));
%alllocs(count3) = locs1(count1);
count1 = count1 + 1;
count3 = count3 + 1;
elseif strcmpi(labs1{count1}, labs2{count2})
alllocs = copyfields(alllocs, count3, locs1(count1));
%alllocs(count3) = locs1(count1);
count1 = count1 + 1;
count2 = count2 + 1;
count3 = count3 + 1;
elseif isempty(strmatch(labs1{count1}, labs2, 'exact'))
alllocs = copyfields(alllocs, count3, locs1(count1));
%alllocs(count3) = locs1(count1);
count1 = count1 + 1;
count3 = count3 + 1;
else
alllocs = copyfields(alllocs, count3, locs2(count2));
%alllocs(count3) = locs2(count2);
count2 = count2 + 1;
count3 = count3 + 1;
end;
end;
% concatenate channel structures with different fields
function loc3 = concatlocs(loc1, loc2);
fields1 = fieldnames(loc1);
fields2 = fieldnames(loc2);
if isequal(fields1, fields2)
% the try, catch clause is necessary
% below seems to be a Matlab bug
try, loc3 = [ loc1; loc2 ];
catch
try loc3 = [ loc1 loc2 ];
catch, loc3 = [ loc1(:)' loc2(:)' ];
end;
end;
else
loc3 = loc1;
for index = 1:length(loc2)
loc3 = copyfields(loc3, length(loc1)+index, loc2(index));
end;
end;
% copy fields of a structure to another one
function [struct1] = copyfields(struct1, index1, struct2)
fields1 = fieldnames(struct1);
fields2 = fieldnames(struct2);
if isequal(fields1, fields2)
struct1(index1) = struct2;
else
for index = 1:length(fields2)
struct1 = setfield(struct1, {index1}, fields2{index}, getfield(struct2, fields2{index}));
end;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_envtopo.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_envtopo.m
| 8,414 |
utf_8
|
c54a44246a6ff4f7cb2c5cc34139ff09
|
% pop_envtopo() - Plot envelope of an averaged EEG epoch, plus scalp maps
% of specified or largest contributing components referenced
% to their time point of maximum variance in the epoch or specified
% sub-epoch. Calls envtopo(). When nargin < 3, a query window
% pops-up to allow additional arguments.
% Usage:
% >> pop_envtopo( EEG ); % pop-up window mode
% >> pop_envtopo( EEG, timerange, 'key', 'val', ...);
%
% Inputs:
% EEG - input dataset. Can also be an array of two epoched datasets.
% In this case, the epoch mean (ERP) of the second is subtracted
% from the epoch mean (ERP) of the first. Note: The ICA weights
% must be the same for the two datasets.
% timerange - [min max] time range (in ms) in epoch to plot, or if [], from EEG
%
% Optional inputs:
% 'key','val' - optional envtopo() and topoplot() arguments
% (see >> help topoplot())
%
% Outputs: Same as envtopo(). When nargin < 3, a query window pops-up
% to ask for additional arguments and no outputs are returned.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: envtopo(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformatted help & license -ad
% 03-16-02 added all topoplot() options -ad
% 03-18-02 added title -ad & sm
function varargout = pop_envtopo( EEG, timerange, varargin);
varargout{1} = '';
if nargin < 1
help pop_envtopo;
return;
end;
if length(EEG) == 1 & isempty( EEG.icasphere )
disp('Error: cannot make plot without ICA weights. See "Tools > Run ICA".'); return;
end;
if length(EEG) == 1 & isempty(EEG.chanlocs)
fprintf('Cannot make plot without channel locations. See "Edit > Dataset info".\n');
return;
end;
if exist('envtitle') ~= 1
envtitle = 'Largest ERP components';
end;
options = ',';
if nargin < 3
% which set to save
% -----------------
promptstr = { 'Enter time range (in ms) to plot:', ...
'Enter time range (in ms) to rank component contributions:', ...
'Number of largest contributing components to plot (7):', ...
'Else plot these component numbers only (Ex: 2:4,7):', ...
'Component numbers to remove from data before plotting:' ...
'Plot title:' ...
'Optional topoplot() and envtopo() arguments:' };
inistr = { [num2str( EEG(end).xmin*1000) ' ' num2str(EEG(end).xmax*1000)], ...
[num2str( EEG(end).xmin*1000) ' ' num2str(EEG(end).xmax*1000)], ...
'7', ...
'', ...
'', ...
['Largest ERP components' fastif(isempty(EEG(end).setname), '',[' of ' EEG(end).setname])] ...
'''electrodes'',''off''' };
if length(EEG) > 1
promptstr = { 'Dataset indices to subtract (Ex: ''1 2''-> 1-2)' promptstr{:} };
inistr = { '2 1' inistr{:} };
end;
result = inputdlg2( promptstr, 'Plot component and ERP envelopes -- pop_envtopo()', 1, inistr, 'pop_envtopo');
if length(result) == 0 return; end;
if length(EEG) > 1
subindices = eval( [ '[' result{1} ']' ] );
result(1) = [];
EEG = EEG(subindices(1:2));
fprintf('pop_envtopo(): Subtracting the epoch mean of dataset %d from that of dataset %d\n', ...
subindices(2), subindices(1));
end;
timerange = eval( [ '[' result{1} ']' ] );
if ~isempty( result{2} ), options = [ options '''limcontrib'',[' result{2} '],' ]; end;
if ~isempty( result{3} ), options = [ options '''compsplot'',[' result{3} '],' ]; end;
if ~isempty( result{4} ), options = [ options '''compnums'',[' result{4} '],' ]; end;
if ~isempty(result{5}), options = [ options '''subcomps'',[' result{5} '],' ]; end;
if ~isempty(result{6}), options = [ options '''title'', ''' result{6} ''',' ]; end;
options = [ options result{7} ];
figure;
try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
else
if isempty(timerange)
timerange = [EEG.xmin*1000 EEG.xmax*1000];
end
options = [options vararg2str( varargin ) ];
end;
if length(EEG) > 2
error('Cannot process more than two datasets');
end;
if timerange(1) < max([EEG.xmin])*1000, timerange(1) = max([EEG.xmin])*1000; end;
if timerange(2) > min([EEG.xmax])*1000, timerange(2) = min([EEG.xmax])*1000; end;
EEG1 = eeg_checkset(EEG(1),'loaddata');
sigtmp = reshape(EEG1.data, EEG1.nbchan, EEG1.pnts, EEG1.trials);
if ~isempty(EEG1.icachansind), sigtmp = sigtmp(EEG1.icachansind,:,:); end;
if length(EEG) == 2
EEG2 = eeg_checkset(EEG(2),'loaddata');
if ~all(EEG1.icaweights(:) == EEG2.icaweights(:))
error('The ICA decomposition must be the same for the two datasets');
end;
sigtmp2 = reshape(EEG2.data, EEG2.nbchan, EEG2.pnts, EEG2.trials);
if ~isempty(EEG2.icachansind), sigtmp2 = sigtmp2(EEG2.icachansind,:,:); end;
end;
posi = round( (timerange(1)/1000-EEG1.xmin) * EEG1.srate) + 1;
posf = min(round( (timerange(2)/1000-EEG1.xmin) * EEG1.srate) + 1, EEG1.pnts);
% outputs
% -------
outstr = '';
if nargin >= 4
for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end;
if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end;
end;
% generate output command
% ------------------------
if length( options ) < 2, options = ''; end;
if length(EEG) == 1
varargout{1} = sprintf('figure; pop_envtopo(%s, [%s] %s);', ...
inputname(1), num2str(timerange), options);
else
if exist('subindices')
varargout{1} = sprintf('figure; pop_envtopo(%s([%s]), [%s] %s);', ...
inputname(1), int2str(subindices), num2str(timerange), options);
end;
end;
% plot the data
% --------------
options = [ options ', ''verbose'', ''off''' ];
if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end;
if any(isnan(sigtmp(:)))
disp('NaN detected: using nan_mean');
if length(EEG) == 2
com = sprintf(['%s envtopo(nan_mean(sigtmp(:,posi:posf,:),3)-nan_mean(sigtmp2(:,posi:posf,:),3),' ...
'EEG(1).icaweights*EEG(1).icasphere, ' ...
'''chanlocs'', EEG(1).chanlocs, ''chaninfo'', EEG(1).chaninfo, ''icawinv'', EEG(1).icawinv,' ...
'''timerange'', [timerange(1) timerange(2)] %s);' ] , outstr, options);
else % length(EEG) == 1
com = sprintf(['%s envtopo(nan_mean(sigtmp(:,posi:posf,:),3), EEG.icaweights*EEG.icasphere, ' ...
'''chanlocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo, ''icawinv'', EEG.icawinv,' ...
'''timerange'', [timerange(1) timerange(2)] %s);' ] , outstr, options);
end;
else
if length(EEG) == 2
com = sprintf(['%s envtopo(mean(sigtmp(:,posi:posf,:),3)-mean(sigtmp2(:,posi:posf,:),3),' ...
' EEG(1).icaweights*EEG(1).icasphere, ' ...
'''chanlocs'', EEG(1).chanlocs, ''chaninfo'', EEG(1).chaninfo, ''icawinv'', EEG(1).icawinv,' ...
'''timerange'', [timerange(1) timerange(2)] %s);' ] , outstr, options);
else % length(EEG) == 1
com = sprintf(['%s envtopo(mean(sigtmp(:,posi:posf,:),3), EEG.icaweights*EEG.icasphere, ' ...
'''chanlocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo, ''icawinv'', EEG.icawinv,' ...
'''timerange'', [timerange(1) timerange(2)] %s);' ] , outstr, options);
end;
end;
% fprintf(['\npop_envtopo(): Issuing command: ' com '\n\n']); % type the evntopo() call
eval(com); % make the plot using envtopo()
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_readlocs.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_readlocs.m
| 8,752 |
utf_8
|
ddf2ebd69a1b663a17650baa003d5b41
|
% pop_readlocs() - load a EGI-format EEG file (pop up an interactive window if no arguments).
%
% Usage:
% >> EEG = pop_readlocs; % a window pops up
% >> EEG = pop_readlocs( filename, 'key', val, ...); % no window
%
% Inputs:
% filename - Electrode location file name
% 'key',val - Same options as readlocs() (see >> help readlocs)
%
% Outputs: same as readlocs()
%
% Author: Arnaud Delorme, CNL / Salk Institute, 17 Dec 2002
%
% See also: readlocs()
% Copyright (C) 17 Dec 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [tmplocs, command] = pop_readlocs(filename, varargin);
tmplocs = [];
command = '';
% get infos from readlocs
% -----------------------
[chanformat listcolformat] = readlocs('getinfos');
listtype = { chanformat.type };
if nargin < 1
[filename, filepath] = uigetfile('*.*', 'Importing electrode location file -- pop_readlocs()');
%filename = 'chan32.locs';
%filepath = 'c:\eeglab\eeglab4.0\';
drawnow;
if filename == 0 return; end;
filename = [filepath filename];
tmpfile = loadtxt(filename);
nbcols = cellfun('isempty', tmpfile(end,:));
nbcols = ones(1,length(find(~nbcols)));
% decoding file type
% ------------------
periods = find(filename == '.');
fileextension = filename(periods(end)+1:end);
switch lower(fileextension),
case {'loc' 'locs' }, filetype = 'loc';
case 'xyz', filetype = 'xyz';
case 'sph', filetype = 'sph';
case 'txt', filetype = 'chanedit';
case 'elp', filetype = 'polhemus';
case 'eps', filetype = 'besa';
otherwise, filetype = '';
end;
indexfiletype = strmatch(filetype, listtype, 'exact');
% convert format info
% -------------------
formatinfo = { chanformat.importformat };
formatskipcell = { chanformat.skipline };
rmindex = [];
count = 1;
for index = 1:length(formatinfo)
if ~isstr(formatinfo{index})
for index2 = 1:length(formatinfo{index})
indexformat = strmatch(formatinfo{index}{index2}, listcolformat, 'exact');
indexlist(count, index2) = indexformat;
end;
if isempty(formatskipcell{index}), formatskip(count) = 0;
else formatskip(count) = formatskipcell{index};
end;
count = count+1;
else
rmindex = [ rmindex index ];
end;
end;
listtype(rmindex) = [];
listtype (end+1) = { 'custom' };
formatskip(end+1) = 0;
indexlist(end+1,:) = -1;
% ask user
formatcom = [ ...
'indexformat = get(findobj(gcf, ''tag'', ''format''), ''value'');' ...
'tmpformat = get(findobj(gcf, ''tag'', ''format''), ''userdata'');' ...
'for tmpindex=1:' int2str(length(nbcols)) ...
' tmpobj = findobj(gcf, ''tag'', [ ''col'' int2str(tmpindex) ]);' ...
' if tmpformat{1}(indexformat,tmpindex) == -1,' ...
' set(tmpobj, ''enable'', ''on'');' ...
' else ' ...
' set(tmpobj, ''enable'', ''off'');' ...
' set(tmpobj, ''value'', tmpformat{1}(indexformat,tmpindex));' ...
' end;' ...
'end;' ...
'strheaderline = fastif(tmpformat{2}(indexformat)<0, ''auto'', int2str(tmpformat{2}(indexformat)));' ...
'set(findobj(gcf, ''tag'', ''headlines''), ''string'', strheaderline);' ...
'eval(get(findobj(gcf, ''tag'', ''headlines''), ''callback''));' ...
'clear tmpindex indexformat tmpformat tmpobj strheaderline;' ];
headercom = [ ...
'tmpheader = str2num(get(findobj(gcf, ''tag'', ''headlines''), ''string''));' ...
'if ~isempty(tmpheader), ' ...
' for tmpindex=1:' int2str(length(nbcols)) ...
' tmpobj = findobj(gcf, ''tag'', [ ''text'' int2str(tmpindex) ]);' ...
' tmpstr = get(tmpobj, ''userdata'');' ...
' set(tmpobj, ''string'', tmpstr(tmpheader+1:min(tmpheader+10, size(tmpstr,1)),:));' ...
' end;' ...
'end;' ...
'clear tmpobj tmpstr tmpheader tmpindex;' ];
geometry = { [1 1 1] [1 2] [nbcols] [nbcols] [nbcols] [1] [1 1 1]};
listui = { ...
{ 'style' 'text' 'string' 'Predefined format' } ...
{ 'style' 'text' 'string' 'Header lines' } ...
{ 'style' 'edit' 'tag' 'headlines' 'string' '0' 'callback' headercom } ...
{ 'style' 'listbox' 'tag' 'format' 'string' strvcat(listtype{:}) ...
'callback' formatcom 'userdata' { indexlist;formatskip } } ...
{ 'style' 'pushbutton' 'string' 'preview' ...
'callback' 'set(findobj(gcbf, ''tag'', ''Import''), ''userdata'', ''preview'')'} };
% custom columns
% --------------
for index = 1:length(nbcols)
listui{end+1} = { 'style' 'text' 'string' [ 'column ' int2str(index) ] };
end;
for index = 1:length(nbcols)
listui{end+1} = { 'style' 'listbox' 'tag' [ 'col' int2str(index) ] 'string' ...
strvcat(listcolformat{:}) };
end;
for index = 1:length(nbcols)
listui{end+1} = { 'style' 'text' 'string' formatstr(tmpfile(1:min(10, size(tmpfile,1)),index)) ...
'tag' ['text' int2str(index) ] 'userdata' formatstr(tmpfile(:,index)) };
end;
listui = { listui{:} ...
{} ...
{ 'style' 'pushbutton' 'string' 'Cancel', 'callback', 'close gcbf;' } ...
{ 'style' 'pushbutton' 'string' 'Help', 'callback', 'pophelp(''pop_readlocs'');' } ...
{ 'style' 'pushbutton' 'string' 'Import' 'tag' 'Import' ...
'callback', 'set(findobj(gcbf, ''tag'', ''Import''), ''userdata'', ''import'')'} };
fig = figure('name', 'Importing electrode location file -- pop_readlocs()', 'visible', 'off');
supergui( fig, geometry, [1 2 1 3 7 1 1], listui{:});
% update figure
set(findobj(gcf, 'tag', 'format'), 'value', indexfiletype);
eval(formatcom);
% this loop is necessary for decoding Preview
cont = 1;
while cont
waitfor( findobj('parent', fig, 'tag', 'Import'), 'userdata');
if isempty( findobj('parent', fig, 'tag', 'Import') ), return; end;
% decode inputs
% -------------
tmpheader = str2num(get(findobj(fig, 'tag', 'headlines'), 'string'));
tmpobj = findobj(fig, 'tag', 'format');
tmpformatstr = get(tmpobj, 'string');
tmpformatstr = tmpformatstr(get(tmpobj, 'value'),:);
for tmpindex=1:length(nbcols)
tmpobj = findobj(fig, 'tag', [ 'col' int2str(tmpindex) ]);
tmpcolstr{tmpindex} = get(tmpobj, 'string');
tmpcolstr{tmpindex} = deblank(tmpcolstr{tmpindex}(get(tmpobj,'value'),:));
end;
% take appropriate measures
% -------------------------
res = get(findobj('parent', fig, 'tag', 'Import'), 'userdata');
set(findobj('parent', fig, 'tag', 'Import'), 'userdata', '');
if strcmp(res, 'preview')
try,
tmplocs = readlocs( filename, 'filetype', tmpformatstr, ...
'skiplines', tmpheader, 'format', tmpcolstr);
figure; topoplot([],tmplocs, 'style', 'blank', 'electrodes', 'labelpoint');
catch,
errordlg2(strvcat('Error while importing locations:', lasterr), 'Error');
end;
else
cont = 0;
end;
end;
close(fig);
% importing files
% ---------------
tmplocs = readlocs( filename, 'filetype', tmpformatstr, ...
'skiplines', tmpheader, 'format', tmpcolstr);
else
tmplocs = readlocs( filename, varargin{:});
end;
command = sprintf('EEG.chanlocs = pop_readlocs(''%s'', %s);', filename, vararg2str(varargin));
return;
% format string for text file
% ---------------------------
function alltxt = formatstr( celltxt )
for index1 = 1:size(celltxt,1)
alltxt{index1} = '';
for index2 = 1:size(celltxt,2)
alltxt{index1} = sprintf('%s\t%s', alltxt{index1}, num2str(celltxt{index1,index2}));
end;
alltxt{index1} = sprintf(alltxt{index1}, '%s\n', alltxt{index1});
end;
alltxt = strvcat( alltxt{:});
|
github
|
ZijingMao/baselineeegtest-master
|
pop_runica.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_runica.m
| 24,745 |
utf_8
|
450b6025e6c310f740bca53e1a99ee74
|
% pop_runica() - Run an ICA decomposition of an EEG dataset using runica(),
% binica(), or another ICA or other linear decomposition.
% Usage:
% >> OUT_EEG = pop_runica( EEG ); % pops-up a data entry window
% >> OUT_EEG = pop_runica( EEG, 'key', 'val' ); % no pop_up
%
% Graphic interface:
% "ICA algorithm to use" - [edit box] The ICA algorithm to use for
% ICA decomposition. Command line equivalent: 'icatype'
% "Commandline options" - [edit box] Command line options to forward
% to the ICA algorithm. Command line equivalent: 'options'
% Inputs:
% EEG - input EEG dataset or array of datasets
%
% Optional inputs:
% 'icatype' - ['runica'|'binica'|'jader'|'fastica'] ICA algorithm
% to use for the ICA decomposition. The nature of any
% differences in the results of these algorithms have
% not been well characterized. {default: binica(), if
% found, else runica()}
% 'dataset' - [integer array] dataset index or indices.
% 'chanind' - [integer array or cell array] subset of channel indices
% for running the ICA decomposition. Alternatively, you may
% also enter channel types here in a cell array.
% 'concatenate' - ['on'|'off'] 'on' concatenate all input datasets
% (assuming there are several). 'off' run ICA independently
% on each dataset. Default is 'off'.
% 'concatcond' - ['on'|'off'] 'on' concatenate conditions for input datasets
% of the same sessions and the same subject. Default is 'off'.
% 'key','val' - ICA algorithm options (see ICA routine help messages).
%
% Adding a new algorithm:
% Add the algorithm to the list of algorithms line 366 to 466, for example
%
% case 'myalgo', [EEG.icaweights] = myalgo( tmpdata, g.options{:} );
%
% where "myalgo" is the name of your algorithm (and Matlab function).
% tmpdata is the 2-D array containing the EEG data (channels x points) and
% g.options{} contains custom options for your algorithm (there is no
% predetermined format for these options). The output EEG.icaweights is the
% mixing matrix (or inverse of the unmixing matrix).
%
% Note:
% 1) Infomax (runica, binica) is the ICA algorithm we use most. It is based
% on Tony Bell's infomax algorithm as implemented for automated use by
% Scott Makeig et al. using the natural gradient of Amari et al. It can
% also extract sub-Gaussian sources using the (recommended) 'extended' option
% of Lee and Girolami. Function runica() is the all-Matlab version; function
% binica() calls the (1.5x faster) binary version (a separate download)
% translated into C from runica() by Sigurd Enghoff.
% 2) jader() calls the JADE algorithm of Jean-Francois Cardoso. This is
% included in the EEGLAB toolbox by his permission. See >> help jader
% 3) To run fastica(), download the fastICA toolbox from its website,
% http://www.cis.hut.fi/projects/ica/fastica/, and make it available
% in your Matlab path. According to its authors, default parameters
% are not optimal: Try args 'approach', 'sym' to estimate components
% in parallel.
%
% Outputs:
% OUT_EEG = The input EEGLAB dataset with new fields icaweights, icasphere
% and icachansind (channel indices).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: runica(), binica(), jader(), fastica()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 03-07-02 add the eeglab options -ad
% 03-18-02 add other decomposition options -ad
% 03-19-02 text edition -sm
function [ALLEEG, com] = pop_runica( ALLEEG, varargin )
com = '';
if nargin < 1
help pop_runica;
return;
end;
% find available algorithms
% -------------------------
allalgs = { 'runica' 'binica' 'jader' 'jadeop' 'jade_td_p' 'MatlabshibbsR' 'fastica' ...
'tica' 'erica' 'simbec' 'unica' 'amuse' 'fobi' 'evd' 'evd24' 'sons' 'sobi' 'ng_ol' ...
'acsobiro' 'acrsobibpf' 'pearson_ica' 'egld_ica' 'eeA' 'tfbss' 'icaML' 'icaMS' }; % do not use egld_ica => too slow
selectalg = {};
linenb = 1;
count = 1;
for index = length(allalgs):-1:1
if exist(allalgs{index}) ~= 2 & exist(allalgs{index}) ~= 6
allalgs(index) = [];
end;
end;
% special AMICA
% -------------
selectamica = 0;
defaultopts = [ '''extended'', 1' ] ;
if nargin > 1
if isstr(varargin{1})
if strcmpi(varargin{1}, 'selectamica')
selectamica = 1;
allalgs = { 'amica' allalgs{:} };
defaultopts = sprintf('''outdir'', ''%s''', fullfile(pwd, 'amicaout'));
elseif strcmpi(varargin{1}, 'selectamicaloc')
selectamica = 1;
allalgs = { 'amica' allalgs{:} };
defaultopts = sprintf('''outdir'', ''%s'', ''qsub'', ''off''', fullfile(pwd, 'amicaout'));
end;
end;
end;
% popup window parameters
% -----------------------
fig = [];
if nargin < 2 | selectamica
commandchans = [ 'tmpchans = get(gcbf, ''userdata'');' ...
'tmpchans = tmpchans{1};' ...
'set(findobj(gcbf, ''tag'', ''chantype''), ''string'', ' ...
' int2str(pop_chansel( tmpchans )));' ...
'clear tmpchans;' ];
commandtype = ['tmptype = get(gcbf, ''userdata'');' ...
'tmptype = tmptype{2};' ...
'if ~isempty(tmptype),' ...
' [tmps,tmpv, tmpstr] = listdlg2(''PromptString'',''Select type(s)'', ''ListString'', tmptype);' ...
' if tmpv' ...
' set(findobj(''parent'', gcbf, ''tag'', ''chantype''), ''string'', tmpstr);' ...
' end;' ...
'else,' ...
' warndlg2(''No channel type'', ''No channel type'');' ...
'end;' ...
'clear tmps tmpv tmpstr tmptype tmpchans;' ];
cb_ica = [ 'if get(gcbo, ''value'') < 3, ' ...
' set(findobj(gcbf, ''tag'', ''params''), ''string'', ''''''extended'''', 1'');' ...
'else set(findobj(gcbf, ''tag'', ''params''), ''string'', '''');' ...
'end;' ];
promptstr = { { 'style' 'text' 'string' 'ICA algorithm to use (click to select)' } ...
{ 'style' 'listbox' 'string' strvcat(allalgs{:}) 'callback', cb_ica } ...
{ 'style' 'text' 'string' 'Commandline options (See help messages)' } ...
{ 'style' 'edit' 'string' defaultopts 'tag' 'params' } ...
{ 'style' 'text' 'string' 'Channel type(s) or channel indices' } ...
{ 'style' 'edit' 'string' '' 'tag' 'chantype' } ...
{ 'style' 'pushbutton' 'string' '... types' 'callback' commandtype } ...
{ 'style' 'pushbutton' 'string' '... channels' 'callback' commandchans } };
geometry = { [2 1.5] [2 1.5] [2 1 1 1] };
if length(ALLEEG) > 1
cb1 = 'set(findobj(''parent'', gcbf, ''tag'', ''concat2''), ''value'', 0);';
cb2 = 'set(findobj(''parent'', gcbf, ''tag'', ''concat1''), ''value'', 0);';
promptstr = { promptstr{:}, ...
{ 'style' 'text' 'string' 'Concatenate all datasets (check=yes; uncheck=run ICA on each dataset)?' }, ...
{ 'style' 'checkbox' 'string' '' 'value' 0 'tag' 'concat1' 'callback' cb1 }, ...
{ 'style' 'text' 'string' 'Concatenate datasets for the same subject and session (check=yes)?' }, ...
{ 'style' 'checkbox' 'string' '' 'value' 1 'tag' 'concat2' 'callback' cb2 } };
geometry = { geometry{:} [ 2 0.2 ] [ 2 0.2 ]};
end;
% channel types
% -------------
if isfield(ALLEEG(1).chanlocs, 'type'),
tmpchanlocs = ALLEEG(1).chanlocs;
alltypes = { tmpchanlocs.type };
indempty = cellfun('isempty', alltypes);
alltypes(indempty) = '';
try,
alltypes = unique_bc(alltypes);
catch,
alltypes = '';
end;
else
alltypes = '';
end;
% channel labels
% --------------
if ~isempty(ALLEEG(1).chanlocs)
tmpchanlocs = ALLEEG(1).chanlocs;
alllabels = { tmpchanlocs.labels };
else
for index = 1:ALLEEG(1).nbchan
alllabels{index} = int2str(index);
end;
end;
% gui
% ---
result = inputgui( 'geometry', geometry, 'uilist', promptstr, ...
'helpcom', 'pophelp(''pop_runica'')', ...
'title', 'Run ICA decomposition -- pop_runica()', 'userdata', { alllabels alltypes } );
if length(result) == 0 return; end;
options = { 'icatype' allalgs{result{1}} 'dataset' [1:length(ALLEEG)] 'options' eval( [ '{' result{2} '}' ]) };
if ~isempty(result{3})
if ~isempty(str2num(result{3})), options = { options{:} 'chanind' str2num(result{3}) };
else options = { options{:} 'chanind' parsetxt(result{3}) };
end;
end;
if length(result) > 3
options = { options{:} 'concatenate' fastif(result{4}, 'on', 'off') };
options = { options{:} 'concatcond' fastif(result{5}, 'on', 'off') };
end;
else
if mod(length(varargin),2) == 1
options = { 'icatype' varargin{1:end} };
else
options = varargin;
end;
end;
% decode input arguments
% ----------------------
[ g addoptions ] = finputcheck( options, { 'icatype' 'string' allalgs 'runica'; ...
'dataset' 'integer' [] [1:length(ALLEEG)];
'options' 'cell' [] {};
'concatenate' 'string' { 'on','off' } 'off';
'concatcond' 'string' { 'on','off' } 'off';
'chanind' { 'cell','integer' } { [] [] } [];}, ...
'pop_runica', 'ignore');
if isstr(g), error(g); end;
if ~isempty(addoptions), g.options = { g.options{:} addoptions{:}}; end;
% select datasets, create new big dataset if necessary
% ----------------------------------------------------
if length(g.dataset) == 1
EEG = ALLEEG(g.dataset);
EEG = eeg_checkset(EEG, 'loaddata');
elseif length(ALLEEG) > 1 & ~strcmpi(g.concatenate, 'on') & ~strcmpi(g.concatcond, 'on')
[ ALLEEG com ] = eeg_eval( 'pop_runica', ALLEEG, 'warning', 'off', 'params', ...
{ 'icatype' g.icatype 'options' g.options 'chanind' g.chanind } );
return;
elseif length(ALLEEG) > 1 & strcmpi(g.concatcond, 'on')
allsubjects = { ALLEEG.subject };
allsessions = { ALLEEG.session };
allgroups = { ALLEEG.group };
alltags = zeros(1,length(allsubjects));
if any(cellfun('isempty', allsubjects))
disp('Aborting: Subject names missing from at least one dataset.');
return;
end;
dats = {};
for index = 1:length(allsubjects)
if ~alltags(index)
allinds = strmatch(allsubjects{index}, allsubjects, 'exact');
rmind = [];
% if we have different sessions they will not be concatenated
for tmpi = setdiff_bc(allinds,index)'
if ~isequal(allsessions(index), allsessions(tmpi)), rmind = [rmind tmpi];
%elseif ~isequal(allgroups(index), allgroups(tmpi)), rmind = [rmind tmpi];
end;
end;
allinds = setdiff_bc(allinds, rmind);
fprintf('Found %d datasets for subject ''%s''\n', length(allinds), allsubjects{index});
dats = { dats{:} allinds };
alltags(allinds) = 1;
end;
end;
fprintf('**************************\nNOW RUNNING ALL DECOMPOSITIONS\n****************************\n');
for index = 1:length(dats)
ALLEEG(dats{index}) = pop_runica(ALLEEG(dats{index}), 'icatype', g.icatype, ...
'options', g.options, 'chanind', g.chanind, 'concatenate', 'on');
for idat = 1:length(dats{index})
ALLEEG(dats{index}(idat)).saved = 'no';
pop_saveset(ALLEEG(dats{index}(idat)), 'savemode', 'resave');
ALLEEG(dats{index}(idat)).saved = 'yes';
end;
end;
com = sprintf('%s = pop_runica(%s, %s);', inputname(1),inputname(1), ...
vararg2str({ 'icatype' g.icatype 'concatcond' 'on' 'options' g.options }) );
return;
else
disp('Concatenating datasets...');
EEG = ALLEEG(g.dataset(1));
% compute total data size
% -----------------------
totalpnts = 0;
for i = g.dataset
totalpnts = totalpnts+ALLEEG(g.dataset(i)).pnts*ALLEEG(g.dataset(i)).trials;
end;
EEG.data = zeros(EEG.nbchan, totalpnts);
% copy data
% ---------
cpnts = 1;
for i = g.dataset
tmplen = ALLEEG(g.dataset(i)).pnts*ALLEEG(g.dataset(i)).trials;
TMP = eeg_checkset(ALLEEG(g.dataset(i)), 'loaddata');
EEG.data(:,cpnts:cpnts+tmplen-1) = reshape(TMP.data, size(TMP.data,1), size(TMP.data,2)*size(TMP.data,3));
cpnts = cpnts+tmplen;
end;
EEG.icaweights = [];
EEG.trials = 1;
EEG.pnts = size(EEG.data,2);
EEG.saved = 'no';
end;
% Store and then remove current EEG ICA weights and sphere
% ---------------------------------------------------
fprintf('\n');
if ~isempty(EEG.icaweights)
fprintf('Saving current ICA decomposition in "EEG.etc.oldicaweights" (etc.).\n');
if ~isfield(EEG,'etc'), EEG.etc = []; end;
if ~isfield(EEG.etc,'oldicaweights')
EEG.etc.oldicaweights = {};
EEG.etc.oldicasphere = {};
EEG.etc.oldicachansind = {};
end;
tmpoldicaweights = EEG.etc.oldicaweights;
tmpoldicasphere = EEG.etc.oldicasphere;
tmpoldicachansind = EEG.etc.oldicachansind;
EEG.etc.oldicaweights = { EEG.icaweights tmpoldicaweights{:} };
EEG.etc.oldicasphere = { EEG.icasphere tmpoldicasphere{:} };
EEG.etc.oldicachansind = { EEG.icachansind tmpoldicachansind{:} };
fprintf(' Decomposition saved as entry %d.\n',length(EEG.etc.oldicaweights));
end
EEG.icaweights = [];
EEG.icasphere = [];
EEG.icawinv = [];
EEG.icaact = [];
% select sub_channels
% -------------------
if isempty(g.chanind)
g.chanind = 1:EEG.nbchan;
end;
if iscell(g.chanind)
g.chanind = eeg_chantype(EEG.chanlocs, g.chanind);
end;
EEG.icachansind = g.chanind;
% is pca already an option?
% -------------------------
pca_opt = 0;
for i = 1:length(g.options)
if isstr(g.options{i})
if strcmpi(g.options{i}, 'pca')
pca_opt = 1;
end;
end;
end;
%------------------------------
% compute ICA on a definite set
% -----------------------------
tmpdata = reshape( EEG.data(g.chanind,:,:), length(g.chanind), EEG.pnts*EEG.trials);
tmprank = getrank(double(tmpdata(:,1:min(3000, size(tmpdata,2)))));
tmpdata = tmpdata - repmat(mean(tmpdata,2), [1 size(tmpdata,2)]); % zero mean
if ~strcmpi(lower(g.icatype), 'binica')
try
disp('Attempting to convert data matrix to double precision for more accurate ICA results.')
tmpdata = double(tmpdata);
tmpdata = tmpdata - repmat(mean(tmpdata,2), [1 size(tmpdata,2)]); % zero mean (more precise than single precision)
catch
disp('*************************************************************')
disp('Not enough memory to convert data matrix to double precision.')
disp('All computations will be done in single precision. Matlab 7.x')
disp('under 64-bit Linux and others is imprecise in this mode.')
disp('We advise use of "binica" instead of "runica."')
disp('*************************************************************')
end;
end;
switch lower(g.icatype)
case 'runica'
try, if ismatlab, g.options = { g.options{:}, 'interupt', 'on' }; end; catch, end;
if tmprank == size(tmpdata,1) | pca_opt
[EEG.icaweights,EEG.icasphere] = runica( tmpdata, 'lrate', 0.001, g.options{:} );
else
if nargin < 2
uilist = { { 'style' 'text' 'string' [ 'EEGLAB has detected that the rank of your data matrix' 10 ...
'is lower the number of input data channels. This might' 10 ...
'be because you are including a reference channel or' 10 ...
'because you are running a second ICA decomposition.' 10 ...
sprintf('The proposed dimension for ICA is %d (out of %d channels).', tmprank, size(tmpdata,1)) 10 ...
'Rank computation may be innacurate so you may edit this' 10 ...
'number below. If you do not understand, simply press OK.' ] } { } ...
{ 'style' 'text' 'string' 'Proposed rank:' } ...
{ 'style' 'edit' 'string' num2str(tmprank) } };
res = inputgui('uilist', uilist, 'geometry', { [1] [1] [1 1] }, 'geomvert', [6 1 1]);
if isempty(res), return; end;
tmprank = str2num(res{1});
g.options = [g.options { 'pca' tmprank }];
else
g.options = [g.options {'pca' tmprank }]; % automatic for STUDY (batch processing)
end;
disp(['Data rank (' int2str(tmprank) ') is smaller than the number of channels (' int2str(size(tmpdata,1)) ').']);
[EEG.icaweights,EEG.icasphere] = runica( tmpdata, 'lrate', 0.001, g.options{:} );
end;
case 'binica'
icadefs;
fprintf(['Warning: If the binary ICA function does not work, check that you have added the\n' ...
'binary file location (in the EEGLAB directory) to your Unix /bin directory (.cshrc file)\n']);
if exist(ICABINARY) ~= 2
error('Pop_runica(): binary ICA executable not found. Edit icadefs.m file to specify the ICABINARY location');
end;
tmprank = getrank(tmpdata(:,1:min(3000, size(tmpdata,2))));
if tmprank == size(tmpdata,1) | pca_opt
[EEG.icaweights,EEG.icasphere] = binica( tmpdata, 'lrate', 0.001, g.options{:} );
else
disp(['Data rank (' int2str(tmprank) ') is smaller than the number of channels (' int2str(size(tmpdata,1)) ').']);
[EEG.icaweights,EEG.icasphere] = binica( tmpdata, 'lrate', 0.001, 'pca', tmprank, g.options{:} );
end;
case 'amica'
tmprank = getrank(tmpdata(:,1:min(3000, size(tmpdata,2))));
fprintf('Now Running AMICA\n');
if length(g.options) > 1
if isstr(g.options{2})
fprintf('See folder %s for outputs\n', g.options{2});
end;
end;
fprintf('To import results, use menu item "Tools > Run AMICA > Load AMICA components\n');
modres = runamica( tmpdata, [], size(tmpdata,1), size(tmpdata,2), g.options{:} );
if ~isempty(modres)
EEG.icaweights = modres.W;
EEG.icasphere = modres.S;
else
return;
end;
case 'pearson_ica'
if isempty(g.options)
disp('Warning: EEGLAB default for pearson ICA is 1000 iterations and epsilon=0.0005');
[tmp EEG.icaweights] = pearson_ica( tmpdata, 'maxNumIterations', 1000,'epsilon',0.0005);
else
[tmp EEG.icaweights] = pearson_ica( tmpdata, g.options{:});
end;
case 'egld_ica', disp('Warning: This algorithm is very slow!!!');
[tmp EEG.icaweights] = egld_ica( tmpdata, g.options{:} );
case 'tfbss'
if isempty(g.options)
[tmp EEG.icaweights] = tfbss( tmpdata, size(tmpdata,1), 8, 512 );
else
[tmp EEG.icaweights] = tfbss( tmpdata, g.options{:} );
end;
case 'jader', [EEG.icaweights] = jader( tmpdata, g.options{:} );
case 'matlabshibbsr', [EEG.icaweights] = MatlabshibbsR( tmpdata, g.options{:} );
case 'eea', [EEG.icaweights] = eeA( tmpdata, g.options{:} );
case 'icaml', [tmp EEG.icawinv] = icaML( tmpdata, g.options{:} );
case 'icams', [tmp EEG.icawinv] = icaMS( tmpdata, g.options{:} );
case 'fastica', [ ICAcomp, EEG.icawinv, EEG.icaweights] = fastica( tmpdata, 'displayMode', 'off', g.options{:} );
case { 'tica' 'erica' 'simbec' 'unica' 'amuse' 'fobi' 'evd' 'sons' ...
'jadeop' 'jade_td_p' 'evd24' 'sobi' 'ng_ol' 'acsobiro' 'acrsobibpf' }
fig = figure('tag', 'alg_is_run', 'visible', 'off');
if isempty(g.options), g.options = { size(tmpdata,1) }; end;
switch lower(g.icatype)
case 'tica', EEG.icaweights = tica( tmpdata, g.options{:} );
case 'erica', EEG.icaweights = erica( tmpdata, g.options{:} );
case 'simbec', EEG.icaweights = simbec( tmpdata, g.options{:} );
case 'unica', EEG.icaweights = unica( tmpdata, g.options{:} );
case 'amuse', EEG.icaweights = amuse( tmpdata );
case 'fobi', [tmp EEG.icaweights] = fobi( tmpdata, g.options{:} );
case 'evd', EEG.icaweights = evd( tmpdata, g.options{:} );
case 'sons', EEG.icaweights = sons( tmpdata, g.options{:} );
case 'jadeop', EEG.icaweights = jadeop( tmpdata, g.options{:} );
case 'jade_td_p',EEG.icaweights = jade_td_p( tmpdata, g.options{:} );
case 'evd24', EEG.icaweights = evd24( tmpdata, g.options{:} );
case 'sobi', EEG.icawinv = sobi( tmpdata, g.options{:} );
case 'ng_ol', [tmp EEG.icaweights] = ng_ol( tmpdata, g.options{:} );
case 'acsobiro', EEG.icawinv = acsobiro( tmpdata, g.options{:} );
case 'acrsobibpf', EEG.icawinv = acrsobibpf( tmpdata, g.options{:} );
end;
clear tmp;
close(fig);
otherwise, error('Pop_runica: unrecognized algorithm');
end;
% update weight and inverse matrices etc...
% -----------------------------------------
if ~isempty(fig), try, close(fig); catch, end; end;
if isempty(EEG.icaweights)
EEG.icaweights = pinv(EEG.icawinv);
end;
if isempty(EEG.icasphere)
EEG.icasphere = eye(size(EEG.icaweights,2));
end;
if isempty(EEG.icawinv)
EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere); % a priori same result as inv
end;
% copy back data to datasets if necessary
% ---------------------------------------
if length(g.dataset) > 1
for i = g.dataset
ALLEEG(i).icaweights = EEG.icaweights;
ALLEEG(i).icasphere = EEG.icasphere;
ALLEEG(i).icawinv = EEG.icawinv;
ALLEEG(i).icachansind = g.chanind;
end;
ALLEEG = eeg_checkset(ALLEEG);
else
EEG = eeg_checkset(EEG);
ALLEEG = eeg_store(ALLEEG, EEG, g.dataset);
end;
if nargin < 2 || selectamica
com = sprintf('%s = pop_runica(%s, %s);', inputname(1), inputname(1), vararg2str(g.options) ); %vararg2str({ 'icatype' g.icatype 'dataset' g.dataset 'options' g.options }) );
end;
return;
function tmprank2 = getrank(tmpdata);
tmprank = rank(tmpdata);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Here: alternate computation of the rank by Sven Hoffman
%tmprank = rank(tmpdata(:,1:min(3000, size(tmpdata,2)))); old code
covarianceMatrix = cov(tmpdata', 1);
[E, D] = eig (covarianceMatrix);
rankTolerance = 1e-7;
tmprank2=sum (diag (D) > rankTolerance);
if tmprank ~= tmprank2
fprintf('Warning: fixing rank computation inconsistency (%d vs %d) most likely because running under Linux 64-bit Matlab\n', tmprank, tmprank2);
tmprank2 = max(tmprank, tmprank2);
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_importegimat.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_importegimat.m
| 6,143 |
utf_8
|
8818148b71178dda895cef6b124f69bf
|
% pop_importegimat() - import EGI Matlab segmented file
%
% Usage:
% >> EEG = pop_importegimat(filename, srate, latpoint0);
%
% Inputs:
% filename - Matlab file name
% srate - sampling rate
% latpoint0 - latency in sample ms of stimulus presentation.
% When data files are exported using Netstation, the user specify
% a time range (-100 ms to 500 ms for instance). In this
% case, the latency of the stimulus is 100 (ms). Default is 0 (ms)
%
% Output:
% EEG - EEGLAB dataset structure
%
% Authors: Arnaud Delorme, CERCO/UCSD, Jan 2010
% Copyright (C) Arnaud Delorme, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG com] = pop_importegimat(filename, srate, latpoint0, dataField);
EEG = [];
com = '';
if nargin < 3, latpoint0 = 0; end;
if nargin < 4, lookupchanfile = 0; end;
if nargin < 5, dataField = 'Session'; end;
if nargin < 1
% ask user
[filename, filepath] = uigetfile('*.mat', 'Choose a Matlab file from Netstation -- pop_importegimat()');
if filename == 0 return; end;
filename = fullfile(filepath, filename);
tmpdata = load('-mat', filename);
fieldValues = fieldnames(tmpdata);
sessionPos = strmatch('Session', fieldValues);
posFieldData = 1;
if ~isempty(sessionPos), posFieldData = sessionPos; end;
if ~isfield(tmpdata, 'samplingRate'), srate = 250; else srate = tmpdata.samplingRate; end;
% epoch data files only
promptstr = { { 'style' 'text' 'string' 'Sampling rate (Hz)' } ...
{ 'style' 'edit' 'string' int2str(srate) } ...
{ 'style' 'text' 'string' 'Sample latency for stimulus (ms)' } ...
{ 'style' 'edit' 'string' '0' } ...
{ 'style' 'text' 'string' 'Field containing data' } ...
{ 'style' 'popupmenu' 'string' fieldValues 'value' posFieldData } ...
};
geometry = { [1 1] [1 1] [1 1] };
result = inputgui( 'geometry', geometry, 'uilist', promptstr, ...
'helpcom', 'pophelp(''pop_importegimat'')', ...
'title', 'Import a Matlab file from Netstation -- pop_importegimat()');
if length(result) == 0 return; end;
srate = str2num(result{1});
latpoint0 = str2num(result{2});
dataField = fieldValues{result{3}};
if isempty(latpoint0), latpoint0 = 0; end;
end;
EEG = eeg_emptyset;
fprintf('Reading EGI Matlab file %s\n', filename);
tmpdata = load('-mat', filename);
if isfield(tmpdata, 'samplingRate') % continuous file
srate = tmpdata.samplingRate;
end;
fieldValues = fieldnames(tmpdata);
if all(cellfun(@(x)isempty(findstr(x, 'Segment')), fieldValues))
EEG.srate = srate;
indData = strmatch(dataField, fieldValues);
EEG.data = tmpdata.(fieldValues{indData(1)});
EEG = eeg_checkset(EEG);
EEG = readegilocs(EEG);
com = sprintf('EEG = pop_importegimat(''%s'');', filename);
else
% get data types
% --------------
allfields = fieldnames(tmpdata);
for index = 1:length(allfields)
allfields{index} = allfields{index}(1:findstr(allfields{index}, 'Segment')-2);
end;
datatypes = unique_bc(allfields);
datatypes(cellfun(@isempty, datatypes)) = [];
% read all data
% -------------
counttrial = 1;
EEG.srate = srate;
latency = (latpoint0/1000)*EEG.srate+1;
for index = 1:length(datatypes)
tindex = 1;
for tindex = 1:length(allfields)
if isfield(tmpdata, sprintf('%s_Segment%d', datatypes{index}, tindex))
datatrial = getfield(tmpdata, sprintf('%s_Segment%d', datatypes{index}, tindex));
if counttrial == 1
EEG.pnts = size(datatrial,2);
EEG.data = repmat(single(0), [size(datatrial,1), size(datatrial,2), 1000]);
end;
EEG.data(:,:,counttrial) = datatrial;
EEG.event(counttrial).type = datatypes{index};
EEG.event(counttrial).latency = latency;
EEG.event(counttrial).epoch = counttrial;
counttrial = counttrial+1;
latency = latency + EEG.pnts;
end;
end;
end;
fprintf('%d trials read\n', counttrial-1);
EEG.data(:,:,counttrial:end) = [];
EEG.setname = filename(1:end-4);
EEG.nbchan = size(EEG.data,1);
EEG.trials = counttrial-1;
if latpoint0 ~= 1
EEG.xmin = -latpoint0/1000;
end;
EEG = eeg_checkset(EEG);
% channel location
% ----------------
if all(EEG.data(end,1:10) == 0)
disp('Deleting empty data reference channel (reference channel location is retained)');
EEG.data(end,:) = [];
EEG.nbchan = size(EEG.data,1);
EEG = eeg_checkset(EEG);
end;
EEG = readegilocs(EEG);
com = sprintf('EEG = pop_importegimat(''%s'', %3.2f, %3.2f, %d);', filename, srate, latpoint0, lookupchanfile);
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_rejepoch.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_rejepoch.m
| 2,957 |
utf_8
|
a252e31365db94282bc48a802d83b48b
|
% pop_rejepoch() - Reject pre-labeled trials in a EEG dataset.
% Ask for confirmation and accept the rejection
%
% Usage:
% >> OUTEEG = pop_rejepoch( INEEG, trialrej, confirm)
%
% Inputs:
% INEEG - Input dataset
% trialrej - Array of 0s and 1s (depicting rejected trials) (size is
% number of trials)
% confirm - Display rejections and ask for confirmation. (0=no. 1=yes;
% default is 1).
% Outputs:
% OUTEEG - output dataset
%
% Example:
% >> data2 = pop_rejepoch( EEG, [1 1 1 0 0 0] );
% % reject the 3 first trials of a six-trial dataset
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab(), eegplot()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
function [EEG, com] = pop_rejepoch( EEG, tmprej, confirm);
com = '';
if nargin < 1
help pop_rejepoch;
return;
end;
if nargin < 2
tmprej = find(EEG.reject.rejglobal);
end;
if nargin < 3
confirm = 1;
end;
if islogical(tmprej), tmprej = tmprej+0; end;
uniquerej = double(sort(unique(tmprej)));
if length(tmprej) > 0 && length(uniquerej) <= 2 && ...
ismember(uniquerej(1), [0 1]) && ismember(uniquerej(end), [0 1]) && any(~tmprej)
format0_1 = 1;
fprintf('%d/%d trials rejected\n', sum(tmprej), EEG.trials);
else
format0_1 = 0;
fprintf('%d/%d trials rejected\n', length(tmprej), EEG.trials);
end;
if confirm ~= 0
ButtonName=questdlg2('Are you sure, you want to reject the labeled trials ?', ...
'Reject pre-labelled epochs -- pop_rejepoch()', 'NO', 'YES', 'YES');
switch ButtonName,
case 'NO',
disp('Operation cancelled');
return;
case 'YES',
disp('Compute new dataset');
end % switch
end;
% create a new set if set_out is non nul
% --------------------------------------
if format0_1
tmprej = find(tmprej > 0);
end;
EEG = pop_select( EEG, 'notrial', tmprej);
%com = sprintf( '%s = pop_rejepoch( %s, find(%s.reject.rejglobal), 0);', inputname(1), ...
% inputname(1), inputname(1));
com = sprintf( '%s = pop_rejepoch( %s, %s);', inputname(1), inputname(1), vararg2str({ tmprej 0 }));
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_loadeeg.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_loadeeg.m
| 5,829 |
utf_8
|
1009f8be42d7b9ae13a7b487334378c9
|
% pop_loadeeg() - load a Neuroscan .EEG file (via a pop-up window if no
% arguments). Calls loadeeg().
%
% Usage:
% >> EEG = pop_loadeeg; % pop-up data entry window
% >> EEG = pop_loadeeg( filename, filepath, range_chan, range_trials, ...
% range_typeeeg, range_response, format); % no pop-up window
%
% Graphic interface:
% "Data precision in bits..." - [edit box] data binary format length
% in bits. Command line equivalent: 'format'
% "Trial range subset" - [edit box] integer array.
% Command line equivalent: 'range_trials'
% "Type range subset" - [edit box] integer array.
% Command line equivalent: 'range_typeeeg'
% "Electrode subset" - [edit box] integer array.
% Command line equivalent: 'range_chan'
% "Response range subset" - [edit box] integer array.
% Command line equivalent: 'range_response'
%
% Inputs:
% filename - ['string'] file name
% filepath - ['string'] file path
% range_chan - [integer array] Import only selected electrodes
% Ex: 3,4:10; {Default: [] -> import all}
% range_trials - [integer array] Import only selected trials
% { Default: [] -> import all}
% range_typeeeg - [integer array] Import only trials of selected type
% {Default: [] -> import all}
% range_response - [integer array] Import only trials with selected
% response values {Default: [] -> import all}
% format - ['short'|'int32'] data binary format (Neuroscan 4.3
% saves data as 'int32'; earlier versions save data as
% 'short'. Default is 'short'.
% Outputs:
% EEG - eeglab() data structure
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: loadeeg(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% uses calls to eeg_emptyset and loadeeg
% popup loadeeg file
% ------------------
function [EEG, command] = pop_loadeeg(filename, filepath, range_chan, range_sweeps, range_typeeeg, range_response, datformat);
EEG = [];
command = '';
if nargin < 1
% ask user
[filename, filepath] = uigetfile('*.eeg;*.EEG', 'Choose an EEG file -- pop_loadeeg()');
if filename == 0 return; end;
% popup window parameters
% -----------------------
promptstr = { 'Data precision in bits (16 / 32 bit or Auto for NS v4.3):', ...
'Trial range subset:', ...
'Type range subset:', ...
'Electrodes subset:', ...
'Response range subset:'};
inistr = { 'Auto' '' '' '' '' };
pop_title = sprintf('Load an EEG dataset');
result = inputdlg2( promptstr, pop_title, 1, inistr, 'pop_loadeeg');
if size( result,1 ) == 0 return; end;
% decode parameters
% -----------------
precision = lower(strtrim(result{1}));
if strcmpi(precision, '16')
datformat = 'short';
elseif strcmpi(precision, '32')
datformat = 'int32';
elseif (strcmpi(precision, '0') || strcmpi(precision, 'auto'))
datformat = 'auto'
end;
range_sweeps = eval( [ '[' result{2} ']' ] );
range_typeeeg = eval( [ '[' result{3} ']' ] );
range_chan = eval( [ '[' result{4} ']' ] );
range_response = eval( [ '[' result{5} ']' ] );
else
if exist('filepath') ~= 1
filepath = '';
end;
end;
if exist('datformat') ~= 1, datformat = 'auto'; end;
if exist('range_chan') ~= 1 | isempty(range_chan) , range_chan = 'all'; end;
if exist('range_sweeps') ~= 1 | isempty(range_sweeps) , range_sweeps = 'all'; end;
if exist('range_typeeeg') ~= 1 | isempty(range_typeeeg) , range_typeeeg = 'all'; end;
if exist('range_response') ~= 1 | isempty(range_response), range_response = 'all'; end;
% load datas
% ----------
EEG = eeg_emptyset;
if ~isempty(filepath)
if filepath(end) ~= '/' & filepath(end) ~= '\' & filepath(end) ~= ':'
error('The file path last character must be a delimiter');
end;
fullFileName = sprintf('%s%s', filepath, filename);
else
fullFileName = filename;
end;
[EEG.data, accept, eegtype, rt, eegresp, namechan, EEG.pnts, EEG.trials, EEG.srate, EEG.xmin, EEG.xmax] = ...
loadeeg( fullFileName, range_chan, range_sweeps, range_typeeeg, 'all', 'all', range_response, datformat);
EEG.comments = [ 'Original file: ' fullFileName ];
EEG.setname = 'Neuroscan EEG data';
EEG.nbchan = size(EEG.data,1);
for index = 1:size(namechan,1)
EEG.chanlocs(index).labels = deblank(char(namechan(index,:)));
end;
EEG = eeg_checkset(EEG);
if any(rt)
EEG = pop_importepoch( EEG, [rt(:)*1000 eegtype(:) accept(:) eegresp(:)], { 'RT' 'type' 'accept' 'response'}, {'RT'}, 1E-3, 0, 1);
else
EEG = pop_importepoch( EEG, [eegtype(:) accept(:) eegresp(:)], { 'type' 'accept' 'response'}, { }, 1E-3, 0, 1);
end;
command = sprintf('EEG = pop_loadeeg(''%s'', ''%s'', %s);', filename, filepath, ...
vararg2str({range_chan range_sweeps range_typeeeg range_response datformat }));
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_importdata.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_importdata.m
| 18,140 |
utf_8
|
55023f12445bd132394251c54b2b62e5
|
% pop_importdata() - import data from a Matlab variable or disk file by calling
% importdata().
% Usage:
% >> EEGOUT = pop_importdata(); % pop-up a data entry window
% >> EEGOUT = pop_importdata( 'key', val,...); % no pop-up window
%
% Graphic interface (refer to a previous version of the GUI):
% "Data file/array" - [Edit box] Data file or Matlab variable name to import
% to EEGLAB. Command line equivalent: 'data'
% "Data file/array" - [list box] select data format from listbox. If you
% browse for a data file, the graphical interface might be
% able to detect the file format from the file extension and
% his list box accordingly. Note that you have to click on
% the option to make it active. Command line equivalent is
% 'dataformat'
% "Dataset name" - [Edit box] Name for the new dataset.
% In the last column of the graphic interface, the "EEG.setname"
% text indicates which field of the EEG structure this parameter
% is corresponding to (in this case 'setname').
% Command line equivalent: 'setname'.
% "Data sampling rate" - [Edit box] In Hz. Command line equivalent: 'srate'
% "Time points per epoch" - [Edit box] Number of data frames (points) per epoch.
% Changing this value will change the number of data epochs.
% Command line equivalent: 'pnts'.
% "Start time" - [Edit box] This edit box is only present for
% data epoch and specify the epochs start time in ms. Epoch upper
% time limit is automatically calculated.
% Command line equivalent: 'xmin'
% "Number of channels" - [Edit box] Number of data channels. Command line
% equivalent: 'nbchan'. This edit box cannot be edited.
% "Ref. channel indices or mode" - [edit box] current reference. This edit box
% cannot be edited. To change data reference, use menu
% Tools > Re-reference calling function pop_reref(). The reference
% can be a string, 'common' indicating an unknow common reference,
% 'averef' indicating average reference, or an array of integer
% containing the indices of the reference channels.
% "Subject code" - [Edit box] subject code. For example, 'S01'. The command
% line equivalent is 'subject'.
% "Task Condition" - [Edit box] task condition. For example, 'Targets'. The
% command line equivalent is 'condition'.
% "Session number" - [Edit box] session number (from the same subject). All datasets
% from the same subject and session will be assumed to use the
% same ICA decomposition. The command line equivalent is 'session'.
% "Subject group" - [Edit box] subject group. For example 'Patients' or 'Control'.
% Command line equivalent is 'group'.
% "About this dataset" - [Edit box] Comments about the dataset. Command line
% equivalent is 'comments'.
% "Channel locations file or array" - [Edit box] For channel data formats, see
% >> readlocs help Command line equivalent: 'chanlocs'
% "ICA weights array or text/binary file" - [edit box] Import ICA weights from other
% decompositions (e.g., same data, different conditions).
% To use the ICA weights from another loaded dataset (n), enter
% ALLEEG(n).icaweights. Command line equivalent: 'icaweights'
% "ICA sphere array or text/binary file" - [edit box] Import ICA sphere matrix.
% In EEGLAB, ICA decompositions require a sphere matrix
% and an unmixing weight matrix (see above). To use the sphere
% matrix from another loaded dataset (n), enter ALLEEG(n).icasphere
% Command line equivalent: 'icasphere'.
% "From other dataset" - [push button] Press this button and enter the index
% of another dataset. This will update the channel location or the
% ICA edit box.
%
% Optional inputs:
% 'setname' - Name of the EEG dataset
% 'data' - ['varname'|'filename'] Import data from a Matlab variable or file
% into an EEG data structure
% 'dataformat' - ['array|matlab|ascii|float32le|float32be'] Input data format.
% 'array' is a Matlab array in the global workspace.
% 'matlab' is a Matlab file (which must contain a single variable).
% 'ascii' is an ascii file. 'float32le' and 'float32be' are 32-bit
% float data files with little-endian and big-endian byte order.
% Data must be organised as (channels, timepoints) i.e.
% channels = rows, timepoints = columns; else, as 3-D (channels,
% timepoints, epochs). For convenience, the data file is transposed
% if the number of rows is larger than the number of columns as the
% program assumes that there is more channel than data points.
% 'subject' - [string] subject code. For example, 'S01'.
% {default: none -> each dataset from a different subject}
% 'condition' - [string] task condition. For example, 'Targets'
% {default: none -> all datasets from one condition}
% 'group' - [string] subject group. For example 'Patients' or 'Control'.
% {default: none -> all subjects in one group}
% 'session' - [integer] session number (from the same subject). All datasets
% from the same subject and session will be assumed to use the
% same ICA decomposition {default: none -> each dataset from
% a different session}
% 'chanlocs' - ['varname'|'filename'] Import a channel location file.
% For file formats, see >> help readlocs
% 'nbchan' - [int] Number of data channels.
% 'xmin' - [real] Data epoch start time (in seconds).
% {default: 0}
% 'pnts' - [int] Number of data points per data epoch. The number of trial
% is automatically calculated.
% {default: length of the data -> continuous data assumed}
% 'srate' - [real] Data sampling rate in Hz {default: 1Hz}
% 'ref' - [string or integer] reference channel indices. 'averef' indicates
% average reference. Note that this does not perform referencing
% but only sets the initial reference when the data is imported.
% 'icaweight' - [matrix] ICA weight matrix.
% 'icasphere' - [matrix] ICA sphere matrix. By default, the sphere matrix
% is initialized to the identity matrix if it is left empty.
% 'comments' - [string] Comments on the dataset, accessible through the EEGLAB
% main menu using (Edit > About This Dataset). Use this to attach
% background information about the experiment or data to the dataset.
% Outputs:
% EEGOUT - modified EEG dataset structure
%
% Note: This function calls pop_editset() to modify parameter values.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: pop_editset(), pop_select(), eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 03-16-02 text interface editing -sm & ad
% 03-16-02 remove EEG.xmax et EEG.xmin (for continuous) -ad & sm
% 04-02-02 debugging command line calls -ad & lf
function [EEGOUT, com] = pop_importdata( varargin);
com = '';
EEGOUT = eeg_emptyset;
if nargin < 1 % if several arguments, assign values
% popup window parameters
% -----------------------
geometry = { [1.4 0.7 .8 0.5] [2 3.02] [1] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] [2.5 1 1.5 1.5] ...
[1] [1.4 0.7 .8 0.5] [1] [1.4 0.7 .8 0.5] [1.4 0.7 .8 0.5] };
editcomments = [ 'tmp = pop_comments(get(gcbf, ''userdata''), ''Edit comments of current dataset'');' ...
'if ~isempty(tmp), set(gcf, ''userdata'', tmp); end; clear tmp;' ];
commandload = [ '[filename, filepath] = uigetfile(''*'', ''Select a text file'');' ...
'if filename(1) ~=0,' ...
' set(findobj(''parent'', gcbf, ''tag'', tagtest), ''string'', [ filepath filename ]);' ...
'end;' ...
'clear filename filepath tagtest;' ];
commandsetfiletype = [ 'filename = get( findobj(''parent'', gcbf, ''tag'', ''globfile''), ''string'');' ...
'tmpext = findstr(filename,''.'');' ...
'if ~isempty(tmpext),' ...
' tmpext = lower(filename(tmpext(end)+1:end));' ...
' switch tmpext, ' ...
' case ''mat'', set(findobj(gcbf,''tag'', ''loclist''), ''value'',5);' ...
' case ''fdt'', set(findobj(gcbf,''tag'', ''loclist''), ''value'',3);' ...
' case ''txt'', set(findobj(gcbf,''tag'', ''loclist''), ''value'',2);' ...
' end;' ...
'end; clear tmpext filename;' ];
commandselica = [ 'res = inputdlg2({ ''Enter dataset number'' }, ''Select ICA weights and sphere from other dataset'', 1, { ''1'' });' ...
'if ~isempty(res),' ...
' set(findobj( ''parent'', gcbf, ''tag'', ''weightfile''), ''string'', sprintf(''ALLEEG(%s).icaweights'', res{1}));' ...
' set(findobj( ''parent'', gcbf, ''tag'', ''sphfile'') , ''string'', sprintf(''ALLEEG(%s).icasphere'' , res{1}));' ...
'end;' ];
commandselchan = [ 'res = inputdlg2({ ''Enter dataset number'' }, ''Select channel information from other dataset'', 1, { ''1'' });' ...
'if ~isempty(res),' ...
' set(findobj( ''parent'', gcbf, ''tag'', ''chanfile''), ' ...
' ''string'', sprintf(''{ ALLEEG(%s).chanlocs ALLEEG(%s).chaninfo ALLEEG(%s).urchanlocs }'', res{1}, res{1}, res{1}));' ...
'end;' ];
if isstr(EEGOUT.ref)
curref = EEGOUT.ref;
else
if length(EEGOUT.ref) > 1
curref = [ int2str(abs(EEGOUT.ref)) ];
else
curref = [ int2str(abs(EEGOUT.ref)) ];
end;
end;
uilist = { ...
{ 'Style', 'text', 'string', 'Data file/array (click on the selected option)', 'horizontalalignment', 'right', 'fontweight', 'bold' }, ...
{ 'Style', 'popupmenu', 'string', 'Matlab variable|ASCII text file|float32 le file|float32 be file|Matlab .mat file', ...
'fontweight', 'bold', 'tag','loclist' } ...
{ 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'globfile' }, ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', ...
[ 'tagtest = ''globfile'';' commandload commandsetfiletype ] }, ...
...
{ 'Style', 'text', 'string', 'Dataset name', 'horizontalalignment', 'right', ...
'fontweight', 'bold' }, { 'Style', 'edit', 'string', '' }, { } ...
...
{ 'Style', 'text', 'string', 'Data sampling rate (Hz)', 'horizontalalignment', 'right', 'fontweight', ...
'bold' }, { 'Style', 'edit', 'string', num2str(EEGOUT.srate) }, ...
{ 'Style', 'text', 'string', 'Subject code', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', '' }, ...
{ 'Style', 'text', 'string', 'Time points per epoch (0->continuous)', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', num2str(EEGOUT.pnts) }, ...
{ 'Style', 'text', 'string', 'Task condition', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', '' }, ...
{ 'Style', 'text', 'string', 'Start time (sec) (only for data epochs)', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', num2str(EEGOUT.xmin) }, ...
{ 'Style', 'text', 'string', 'Session number', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', '' }, ...
{ 'Style', 'text', 'string', 'Number of channels (0->set from data)', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', '0' }, ...
{ 'Style', 'text', 'string', 'Subject group', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', '' }, ...
{ 'Style', 'text', 'string', 'Ref. channel indices or mode (see help)', 'horizontalalignment', 'right', ...
}, { 'Style', 'edit', 'string', curref }, ...
{ 'Style', 'text', 'string', 'About this dataset', 'horizontalalignment', 'right', ...
}, { 'Style', 'pushbutton', 'string', 'Enter comments' 'callback' editcomments }, ...
{ } ...
{ 'Style', 'text', 'string', 'Channel location file or info', 'horizontalalignment', 'right', 'fontweight', ...
'bold' }, {'Style', 'pushbutton', 'string', 'From other dataset', 'callback', commandselchan }, ...
{ 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'chanfile' }, ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''chanfile'';' commandload ] }, ...
...
{ 'Style', 'text', 'string', ...
' (note: autodetect file format using file extension; use menu "Edit > Channel locations" for more importing options)', ...
'horizontalalignment', 'right' }, ...
...
{ 'Style', 'text', 'string', 'ICA weights array or text/binary file (if any):', 'horizontalalignment', 'right' }, ...
{ 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ...
{ 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'weightfile' }, ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''weightfile'';' commandload ] }, ...
...
{ 'Style', 'text', 'string', 'ICA sphere array or text/binary file (if any):', 'horizontalalignment', 'right' }, ...
{ 'Style', 'pushbutton' 'string' 'from other dataset' 'callback' commandselica }, ...
{ 'Style', 'edit', 'string', '', 'horizontalalignment', 'left', 'tag', 'sphfile' } ...
{ 'Style', 'pushbutton', 'string', 'Browse', 'callback', [ 'tagtest = ''sphfile'';' commandload ] } };
[ results newcomments ] = inputgui( geometry, uilist, 'pophelp(''pop_importdata'');', 'Import dataset info -- pop_importdata()');
if length(results) == 0, return; end;
args = {};
% specific to importdata (not identical to pop_editset
% ----------------------------------------------------
switch results{1}
case 1, args = { args{:}, 'dataformat', 'array' };
case 2, args = { args{:}, 'dataformat', 'ascii' };
case 3, args = { args{:}, 'dataformat', 'float32le' };
case 4, args = { args{:}, 'dataformat', 'float32be' };
case 5, args = { args{:}, 'dataformat', 'matlab' };
end;
i = 3;
if ~isempty( results{i+7} ) , args = { args{:}, 'nbchan', str2num(results{i+7}) }; end;
if ~isempty( results{2} ) , args = { args{:}, 'data', results{2} }; end;
if ~isempty( results{i } ) , args = { args{:}, 'setname', results{i } }; end;
if ~isempty( results{i+1} ) , args = { args{:}, 'srate', str2num(results{i+1}) }; end;
if ~isempty( results{i+2} ) , args = { args{:}, 'subject', results{i+2} }; end;
if ~isempty( results{i+3} ) , args = { args{:}, 'pnts', str2num(results{i+3}) }; end;
if ~isempty( results{i+4} ) , args = { args{:}, 'condition', results{i+4} }; end;
if ~isempty( results{i+5} ) , args = { args{:}, 'xmin', str2num(results{i+5}) }; end;
if ~isempty( results{i+6} ) , args = { args{:}, 'session', str2num(results{i+6}) }; end;
if ~isempty( results{i+8} ) , args = { args{:}, 'group', results{i+8} }; end;
if ~isempty( results{i+9} ) , args = { args{:}, 'ref', str2num(results{i+9}) }; end;
if ~isempty( newcomments ) , args = { args{:}, 'comments', newcomments }; end;
if abs(str2num(results{i+5})) > 10,
fprintf('WARNING: are you sure the epoch start time (%3.2f) is in seconds\n');
end;
if ~isempty( results{i+10} ) , args = { args{:}, 'chanlocs' , results{i+10} }; end;
if ~isempty( results{i+11} ), args = { args{:}, 'icaweights', results{i+11} }; end;
if ~isempty( results{i+12} ) , args = { args{:}, 'icasphere', results{i+12} }; end;
% generate the output command
% ---------------------------
EEGOUT = pop_editset(EEGOUT, args{:});
com = sprintf( 'EEG = pop_importdata(%s);', vararg2str(args) );
%com = '';
%for i=1:2:length(args)
% if ~isempty( args{i+1} )
% if isstr( args{i+1} ) com = sprintf('%s, ''%s'', ''%s''', com, args{i}, char(args{i+1}) );
% else com = sprintf('%s, ''%s'', [%s]', com, args{i}, num2str(args{i+1}) );
% end;
% else
% com = sprintf('%s, ''%s'', []', com, args{i} );
% end;
%end;
%com = [ 'EEG = pop_importdata(' com(2:end) ');'];
else % no interactive inputs
EEGOUT = pop_editset(EEGOUT, varargin{:});
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_newtimef.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_newtimef.m
| 17,922 |
utf_8
|
8b3292d8b45194eca46e02293f7e5942
|
% pop_newtimef() - Returns estimates and plots of event-related (log) spectral
% perturbation (ERSP) and inter-trial coherence (ITC) phenomena
% timelocked to a set of single-channel input epochs
%
% Usage:
% >> pop_newtimef(EEG, typeplot); % pop_up window
% >> pop_newtimef(EEG, typeplot, lastcom); % pop_up window
% >> pop_newtimef(EEG, typeplot, channel); % do not pop-up window
% >> pop_newtimef(EEG, typeproc, num, tlimits,cycles,
% 'key1',value1,'key2',value2, ... );
%
% Graphical interface:
% "Channel/component number" - [edit box] this is the index of the data
% channel or the index of the component for which to plot the
% time-frequency decomposition.
% "Sub-epoch time limits" - [edit box] sub epochs may be extracted (note that
% this function aims at plotting data epochs not continuous data).
% You may select the new epoch limits in this edit box.
% "Use n time points" - [muliple choice list] this is the number of time
% points to use for the time-frequency decomposition. The more
% time points, the longer the time-frequency decomposition
% takes to compute.
% "Frequency limits" - [edit box] these are the lower and upper
% frequency limit of the time-frequency decomposition. Instead
% of limits, you may also enter a sequence of frequencies. For
% example to compute the time-frequency decomposition at all
% frequency between 5 and 50 hertz with 1 Hz increment, enter "1:50"
% "Use limits, padding n" - [muliple choice list] "using limits" means
% to use the upper and lower limits in "Frequency limits" with
% a specific padding ratio (padratio argument of newtimef).
% The last option "use actual frequencies" forces newtimef to
% ignore the padratio argument and use the vector of frequencies
% given as input in the "Frequency limits" edit box.
% "Log spaced" - [checkbox] you may check this box to compute log-spaced
% frequencies. Note that this is only relevant if you specify
% frequency limits (in case you specify actual frequencies,
% this parameter is ignored).
% "Use divisive baseline" - [muliple choice list] there are two types of
% baseline correction, additive (the baseline is subtracted)
% or divisive (the data is divided by the baseline values).
% The choice is yours. There is also the option to perform
% baseline correction in single trials. See the 'trialbase' "full"
% option in the newtimef.m documentation for more information.
% "No baseline" - [checkbox] check this box to compute the raw time-frequency
% decomposition with no baseline removal.
% "Wavelet cycles" - [edit box] specify the number of cycle at the lowest
% and highest frequency. Instead of specifying the number of cycle
% at the highest frequency, you may also specify a wavelet
% "factor" (see newtimef help message). In addition, it is
% possible to specify actual wavelet cycles for each frequency
% by entering a sequence of numbers.
% "Use FFT" - [checkbox] check this checkbox to use FFT instead of
% wavelet decomposition.
% "ERSP color limits" - [edit box] set the upper and lower limit for the
% ERSP image.
% "see log power" - [checkbox] the log power values (in dB) are plotted.
% Uncheck this box to plot the absolute power values.
% "ITC color limits" - [edit box] set the upper and lower limit for the
% ITC image.
% "plot ITC phase" - [checkbox] check this box plot plot (overlayed on
% the ITC amplitude) the polarity of the ITC complex value.
% "Bootstrap significance level" - [edit box] use this edit box to enter
% the p-value threshold for masking both the ERSP and the ITC
% image for significance (masked values appear as light green)
% "FDR correct" - [checkbox] this correct the p-value for multiple comparisons
% (accross all time and frequencies) using the False Discovery
% Rate method. See the fdr.m function for more details.
% "Optional newtimef arguments" - [edit box] addition argument for the
% newtimef function may be entered here in the 'key', value
% format.
% "Plot Event Related Spectral Power" - [checkbox] plot the ERSP image
% showing event related spectral stimulus induced changes
% "Plot Inter Trial Coherence" - [checkbox] plot the ITC image.
% "Plot Curve at each frequency" - [checkbox] instead of plotting images,
% it is also possible to display curves at each frequency.
% This functionality is beta and might not work in all cases.
%
% Inputs:
% INEEG - input EEG dataset
% typeproc - type of processing: 1 process the raw channel data
% 0 process the ICA component data
% num - component or channel number
% tlimits - [mintime maxtime] (ms) sub-epoch time limits to plot
% cycles - > 0 --> Number of cycles in each analysis wavelet
% = 0 --> Use FFTs (with constant window length
% at all frequencies)
%
% Optional inputs:
% See the newtimef() function.
%
% Outputs: Same as newtimef(); no outputs are returned when a
% window pops-up to ask for additional arguments
%
% Saving the ERSP and ITC output values:
% Simply look up the history using the eegh function (type eegh).
% Then copy and paste the pop_newtimef() command and add output args.
% See the newtimef() function for a list of outputs. For instance,
% >> [ersp itc powbase times frequencies] = pop_newtimef( EEG, ....);
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: newtimef(), eeglab()
% Copyright (C) 2002 University of California San Diego
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 03-08-02 add eeglab option & optimize variable sizes -ad
% 03-10-02 change newtimef call -ad
% 03-18-02 added title -ad & sm
% 04-04-02 added outputs -ad & sm
function varargout = pop_newtimef(EEG, typeproc, num, tlimits, cycles, varargin );
varargout{1} = '';
% display help if not enough arguments
% ------------------------------------
if nargin < 2
help pop_newtimef;
return;
end;
lastcom = [];
if nargin < 3
popup = 1;
else
popup = isstr(num) | isempty(num);
if isstr(num)
lastcom = num;
end;
end;
% pop up window
% -------------
if popup
[txt vars] = gethelpvar('newtimef.m');
g = [1 0.3 0.6 0.4];
geometry = { g g g g g g g g [0.975 1.27] [1] [1.2 1 1.2]};
uilist = { ...
{ 'Style', 'text', 'string', fastif(typeproc, 'Channel number', 'Component number'), 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,3,[],'1') 'tag' 'chan'} {} {} ...
...
{ 'Style', 'text', 'string', 'Sub epoch time limits [min max] (msec)', 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,4,[],[ int2str(EEG.xmin*1000) ' ' int2str(EEG.xmax*1000) ]) 'tag' 'tlimits' } ...
{ 'Style', 'popupmenu', 'string', 'Use 50 time points|Use 100 time points|Use 150 time points|Use 200 time points|Use 300 time points|Use 400 time points' 'tag' 'ntimesout' 'value' 4} { } ...
...
{ 'Style', 'text', 'string', 'Frequency limits [min max] (Hz) or sequence', 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', '' 'tag' 'freqs' } ...
{ 'Style', 'popupmenu', 'string', 'Use limits, padding 1|Use limits, padding 2|Use limits, padding 4|Use actual freqs.' 'tag' 'nfreqs' } ...
{ 'Style', 'checkbox', 'string' 'Log spaced' 'value' 0 'tag' 'freqscale' } ...
...
{ 'Style', 'text', 'string', 'Baseline limits [min max] (msec) (0->pre-stim.)', 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', '0' 'tag' 'baseline' } ...
{ 'Style', 'popupmenu', 'string', 'Use divisive baseline (DIV)|Use standard deviation (STD)|Use single trial DIV baseline|Use single trial STD baseline' 'tag' 'basenorm' } ...
{ 'Style', 'checkbox', 'string' 'No baseline' 'tag' 'nobase' } ...
...
{ 'Style', 'text', 'string', 'Wavelet cycles [min max/fact] or sequence', 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,5,[],'3 0.5') 'tag' 'cycle' } ...
{ 'Style', 'checkbox', 'string' 'Use FFT' 'value' 0 'tag' 'fft' } ...
{ } ...
...
{ 'Style', 'text', 'string', 'ERSP color limits [max] (min=-max)', 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', '' 'tag' 'erspmax'} ...
{ 'Style', 'checkbox', 'string' 'see log power (set)' 'tag' 'scale' 'value' 1} {} ...
...
{ 'Style', 'text', 'string', 'ITC color limits [max]', 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', '' 'tag' 'itcmax'} ...
{ 'Style', 'checkbox', 'string' 'plot ITC phase (set)' 'tag' 'plotphase' } {} ...
...
{ 'Style', 'text', 'string', 'Bootstrap significance level (Ex: 0.01 -> 1%)', 'fontweight', 'bold' } ...
{ 'Style', 'edit', 'string', getkeyval(lastcom,'alpha') 'tag' 'alpha'} ...
{ 'Style', 'checkbox', 'string' 'FDR correct (set)' 'tag' 'fdr' } {} ...
...
{ 'Style', 'text', 'string', 'Optional newtimef() arguments (see Help)', 'fontweight', 'bold', ...
'tooltipstring', 'See newtimef() help via the Help button on the right...' } ...
{ 'Style', 'edit', 'string', '' 'tag' 'options' } ...
{} ...
{ 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotersp','present',0), 'string', ...
'Plot Event Related Spectral Power', 'tooltipstring', ...
'Plot log spectral perturbation image in the upper panel' 'tag' 'plotersp' } ...
{ 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotitc','present',0), 'string', ...
'Plot Inter Trial Coherence', 'tooltipstring', ...
'Plot the inter-trial coherence image in the lower panel' 'tag' 'plotitc' } ...
{ 'Style', 'checkbox', 'value', 0, 'string', ...
'Plot curve at each frequency' 'tag' 'plotcurve' } ...
};
% { 'Style', 'edit', 'string', '''padratio'', 4, ''plotphase'', ''off''' } ...
%{ 'Style', 'text', 'string', '[set] -> Plot ITC phase sign', 'fontweight', 'bold', ...
% 'tooltipstring', ['Plot the sign (+/-) of inter-trial coherence phase' 10 ...
% 'as red (+) or blue (-)'] } ...
% { 'Style', 'checkbox', 'value', ~getkeyval(lastcom,'plotphase','present',1) } { } ...
[ tmp1 tmp2 strhalt result ] = inputgui( geometry, uilist, 'pophelp(''pop_newtimef'');', ...
fastif(typeproc, 'Plot channel time frequency -- pop_newtimef()', ...
'Plot component time frequency -- pop_newtimef()'));
if length( tmp1 ) == 0 return; end;
if result.fft, result.cycle = '0'; end;
if result.nobase, result.baseline = 'NaN'; end;
num = eval( [ '[' result.chan ']' ] );
tlimits = eval( [ '[' result.tlimits ']' ] );
cycles = eval( [ '[' result.cycle ']' ] );
freqs = eval( [ '[' result.freqs ']' ] );
%result.ncycles == 2 is ignored
% add topoplot
% ------------
options = [];
if isfield(EEG.chanlocs, 'theta') && ~isempty(EEG.chanlocs(num).theta)
if ~isfield(EEG, 'chaninfo'), EEG.chaninfo = []; end;
if typeproc == 1
if isempty(EEG.chanlocs), caption = [ 'Channel ' int2str(num) ]; else caption = EEG.chanlocs(num).labels; end;
options = [options ', ''topovec'', ' int2str(num) ...
', ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo, ''caption'', ''' caption '''' ];
else
options = [options ', ''topovec'', EEG.icawinv(:,' int2str(num) ...
'), ''elocs'', EEG.chanlocs, ''chaninfo'', EEG.chaninfo, ''caption'', [''IC '', num2str(num)]' ];
end;
end;
if ~isempty( result.baseline ), options = [ options ', ''baseline'',[' result.baseline ']' ]; end;
if ~isempty( result.alpha ), options = [ options ', ''alpha'',' result.alpha ]; end;
if ~isempty( result.options ), options = [ options ',' result.options ]; end;
if ~isempty( result.freqs ), options = [ options ', ''freqs'', [' result.freqs ']' ]; end;
if ~isempty( result.erspmax ), options = [ options ', ''erspmax'', [' result.erspmax ']' ]; end;
if ~isempty( result.itcmax ), options = [ options ', ''itcmax'',' result.itcmax ]; end;
if ~result.plotersp, options = [ options ', ''plotersp'', ''off''' ]; end;
if ~result.plotitc, options = [ options ', ''plotitc'' , ''off''' ]; end;
if result.plotcurve, options = [ options ', ''plottype'', ''curve''' ]; end;
if result.fdr, options = [ options ', ''mcorrect'', ''fdr''' ]; end;
if result.freqscale, options = [ options ', ''freqscale'', ''log''' ]; end;
if ~result.plotphase, options = [ options ', ''plotphase'', ''off''' ]; end;
if ~result.scale, options = [ options ', ''scale'', ''abs''' ]; end;
if result.ntimesout == 1, options = [ options ', ''ntimesout'', 50' ]; end;
if result.ntimesout == 2, options = [ options ', ''ntimesout'', 100' ]; end;
if result.ntimesout == 3, options = [ options ', ''ntimesout'', 150' ]; end;
if result.ntimesout == 5, options = [ options ', ''ntimesout'', 300' ]; end;
if result.ntimesout == 6, options = [ options ', ''ntimesout'', 400' ]; end;
if result.nfreqs == 1, options = [ options ', ''padratio'', 1' ]; end;
if result.nfreqs == 2, options = [ options ', ''padratio'', 2' ]; end;
if result.nfreqs == 3, options = [ options ', ''padratio'', 4' ]; end;
if result.nfreqs == 4, options = [ options ', ''nfreqs'', ' int2str(length(freqs)) ]; end;
if result.basenorm == 2, options = [ options ', ''basenorm'', ''on''' ]; end;
if result.basenorm == 4, options = [ options ', ''basenorm'', ''on''' ]; end;
if result.basenorm >= 3, options = [ options ', ''trialbase'', ''full''' ]; end;
% add title
% ---------
if isempty( findstr( '''title''', result.options))
if ~isempty(EEG.chanlocs) & typeproc
chanlabel = EEG.chanlocs(num).labels;
else
chanlabel = int2str(num);
end;
end;
% compute default winsize
% -----------------------
if EEG.xmin < 0 && isempty(findstr( '''winsize''', result.options)) && isempty( result.freqs )
fprintf('Computing window size in pop_newtimef based on half of the length of the baseline period');
options = [ options ', ''winsize'', ' int2str(-EEG.xmin*EEG.srate) ];
end;
figure; try, icadefs; set(gcf, 'color', BACKCOLOR); catch, end;
else
options = [ ',' vararg2str(varargin) ];
end;
% compute epoch limits
% --------------------
if isempty(tlimits)
tlimits = [EEG.xmin, EEG.xmax]*1000;
end;
pointrange1 = round(max((tlimits(1)/1000-EEG.xmin)*EEG.srate, 1));
pointrange2 = round(min((tlimits(2)/1000-EEG.xmin)*EEG.srate, EEG.pnts));
pointrange = [pointrange1:pointrange2];
% call function sample either on raw data or ICA data
% ---------------------------------------------------
if typeproc == 1
tmpsig = EEG.data(num,pointrange,:);
else
if ~isempty( EEG.icasphere )
eeglab_options; % changed from eeglaboptions 3/30/02 -sm
if option_computeica
tmpsig = EEG.icaact(num,pointrange,:);
else
tmpsig = (EEG.icaweights(num,:)*EEG.icasphere)*reshape(EEG.data(:,pointrange,:), EEG.nbchan, EEG.trials*length(pointrange));
end;
else
error('You must run ICA first');
end;
end;
tmpsig = reshape( tmpsig, length(num), size(tmpsig,2)*size(tmpsig,3));
% outputs
% -------
outstr = '';
if ~popup
for io = 1:nargout, outstr = [outstr 'varargout{' int2str(io) '},' ]; end;
if ~isempty(outstr), outstr = [ '[' outstr(1:end-1) '] =' ]; end;
end;
% plot the datas and generate output command
% --------------------------------------------
if length( options ) < 2
options = '';
end;
if nargin < 4
varargout{1} = sprintf('figure; pop_newtimef( %s, %d, %d, [%s], [%s] %s);', inputname(1), typeproc, num, ...
int2str(tlimits), num2str(cycles), options);
end;
com = sprintf('%s newtimef( tmpsig(:, :), length(pointrange), [tlimits(1) tlimits(2)], EEG.srate, cycles %s);', outstr, options);
eval(com)
return;
% get contextual help
% -------------------
function txt = context(var, allvars, alltext);
loc = strmatch( var, allvars);
if ~isempty(loc)
txt= alltext{loc(1)};
else
disp([ 'warning: variable ''' var ''' not found']);
txt = '';
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_comperp.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_comperp.m
| 24,035 |
utf_8
|
0a2a28c8833fa31a4f0b429575080934
|
% pop_comperp() - Compute the grand average ERP waveforms of multiple datasets
% currently loaded into EEGLAB, with optional ERP difference-wave
% plotting and t-tests. Creates a plotting figure.
% Usage:
% >> pop_comperp( ALLEEG, flag ); % pop-up window, interactive mode
% >> [erp1 erp2 erpsub time sig] = pop_comperp( ALLEEG, flag, ...
% datadd, datsub, 'key', 'val', ...);
% Inputs:
% ALLEEG - Array of loaded EEGLAB EEG structure datasets
% flag - [0|1] 0 -> Use ICA components; 1 -> use data channels {default: 1}
% datadd - [integer array] List of ALLEEG dataset indices to average to make
% an ERP grand average and optionally to compare with 'datsub' datasets.
%
% Optional inputs:
% datsub - [integer array] List of ALLEEG dataset indices to average and then
% subtract from the 'datadd' result to make an ERP grand mean difference.
% Together, 'datadd' and 'datsub' may be used to plot and compare grand mean
% responses across subjects or conditions. Both arrays must contain the same
% number of dataset indices and entries must be matched pairwise (Ex:
% 'datadd' indexes condition A datasets from subjects 1:n, and 'datsub',
% condition B datasets from the same subjects 1:n). {default: []}
% 'alpha' - [0 < float < 1] Apply two-tailed t-tests for p < alpha. If 'datsub' is
% not empty, perform t-tests at each latency. If 'datasub' is empty,
% perform two-tailed t-tests against a 0 mean dataset with same variance.
% Significant time regions are highlighted in the plotted data.
% 'chans' - [integer array] Vector of chans. or comps. to use {default: all}
% 'geom' - ['scalp'|'array'] Plot erps in a scalp array (plottopo())
% or as a rectangular array (plotdata()). Note: Only channels
% (see 'chans' above) can be plotted in a 'scalp' array.
% 'tlim' - [min max] Time window (ms) to plot data {default: whole time range}
% 'title' - [string] Plot title {default: none}
% 'ylim' - [min max] y-axis limits {default: auto from data limits}
% 'mode' - ['ave'|'rms'] Plotting mode. Plot either grand average or RMS
% (root mean square) time course(s) {default: 'ave' -> grand average}.
% 'std' - ['on'|'off'|'none'] 'on' -> plot std. devs.; 'none' -> do not
% interact with other options {default:'none'}
%
% Vizualisation options:
% 'addavg' - ['on'|'off'] Plot grand average (or RMS) of 'datadd' datasets
% {default: 'on' if 'datsub' empty, otherwise 'off'}
% 'subavg' - ['on'|'off'] Plot grand average (or RMS) of 'datsub' datasets
% {default:'off'}
% 'diffavg' - ['on'|'off'] Plot grand average (or RMS) difference
% 'addall' - ['on'|'off'] Plot the ERPs for all 'dataadd' datasets only {default:'off'}
% 'suball' - ['on'|'off'] Plot the ERPs for all 'datasub datasets only {default:'off'}
% 'diffall' - ['on'|'off'] Plot all the 'datadd'-'datsub' ERP differences {default:'off'}
% 'addstd' - ['on'|'off'] Plot std. dev. for 'datadd' datasets only
% {default: 'on' if 'datsub' empty, otherwise 'off'}
% 'substd' - ['on'|'off'] Plot std. dev. of 'datsub' datasets only {default:'off'}
% 'diffstd' - ['on'|'off'] Plot std. dev. of 'datadd'-'datsub' differences {default:'on'}
% 'diffonly' - ['on'|'off'|'none'] 'on' -> plot difference only; 'none' -> do not affect
% other options {default:'none'}
% 'allerps' - ['on'|'off'|'none'] 'on' -> show ERPs for all conditions;
% 'none' -> do not affect other options {default:'none'}
% 'tplotopt' - [cell array] Pass 'key', val' plotting options to plottopo()
%
% Output:
% erp1 - Grand average (or rms) of the 'datadd' datasets
% erp2 - Grand average (or rms) of the 'datsub' datasets
% erpsub - Grand average (or rms) 'datadd' minus 'datsub' difference
% times - Vector of epoch time indices
% sig - T-test significance values (chans,times).
%
% Author: Arnaud Delorme, CNL / Salk Institute, 15 March 2003
%
% Note: t-test functions were adapted for matrix preprocessing from C functions
% by Press et al. See the description in the pttest() code below
% for more information.
%
% See also: eeglab(), plottopo()
% Copyright (C) 15 March 2003 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [erp1, erp2, erpsub, times, pvalues] = pop_comperp( ALLEEG, flag, datadd, datsub, varargin);
erp1 = '';
if nargin < 1
help pop_comperp;
return;
end;
if isempty(ALLEEG)
error('pop_comperp: cannot process empty sets of data');
end;
if nargin < 2
flag = 1;
end;
allcolors = { 'b' 'r' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' ...
'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm' 'r' 'b' 'g' 'c' 'm'};
erp1 = '';
if nargin < 3
gtmp = [1.1 0.8 .21 .21 .21 0.1]; gtmp2 = [1.48 1.03 1];
uigeom = { [2.6 0.95] gtmp gtmp gtmp [1] gtmp2 gtmp2 [1.48 0.25 1.75] gtmp2 gtmp2 };
commulcomp= ['if get(gcbo, ''value''),' ...
' set(findobj(gcbf, ''tag'', ''multcomp''), ''enable'', ''on'');' ...
'else,' ...
' set(findobj(gcbf, ''tag'', ''multcomp''), ''enable'', ''off'');' ...
'end;'];
uilist = { { } ...
{ 'style' 'text' 'string' 'avg. std. all ERPs' } ...
{ 'style' 'text' 'string' 'Datasets to average (ex: 1 3 4):' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'checkbox' 'string' '' 'value' 1 } ...
{ 'style' 'checkbox' 'string' '' } ...
{ 'style' 'checkbox' 'string' '' } { } ...
{ 'style' 'text' 'string' 'Datasets to average and subtract (ex: 5 6 7):' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'checkbox' 'string' '' 'value' 1 } ...
{ 'style' 'checkbox' 'string' '' } ...
{ 'style' 'checkbox' 'string' '' } { } ...
{ 'style' 'text' 'string' 'Plot difference' } { } ...
{ 'style' 'checkbox' 'string' '' 'value' 1 } ...
{ 'style' 'checkbox' 'string' '' } ...
{ 'style' 'checkbox' 'string' '' } { } ...
{ } ...
{ 'style' 'text' 'string' fastif(flag, 'Channels subset ([]=all):', ...
'Components subset ([]=all):') } ...
{ 'style' 'edit' 'string' '' } { } ...
{ 'style' 'text' 'string' 'Highlight significant regions (.01 -> p=.01)' } ...
{ 'style' 'edit' 'string' '' } { } ...
{ 'style' 'text' 'string' 'Use RMS instead of average (check):' } { 'style' 'checkbox' 'string' '' } { } ...
{ 'style' 'text' 'string' 'Low pass (Hz) (for display only)' } ...
{ 'style' 'edit' 'string' '' } { } ...
{ 'style' 'text' 'string' 'Plottopo options (''key'', ''val''):' } ...
{ 'style' 'edit' 'string' '''ydir'', -1' } ...
{ 'style' 'pushbutton' 'string' 'Help' 'callback', 'pophelp(''plottopo'')' } ...
};
% remove geometry textbox for ICA components
result = inputgui( uigeom, uilist, 'pophelp(''pop_comperp'')', 'ERP grand average/RMS - pop_comperp()');
if length(result) == 0, return; end;
%decode parameters list
options = {};
datadd = eval( [ '[' result{1} ']' ]);
if result{2}, options = { options{:} 'addavg' 'on' }; else, options = { options{:} 'addavg' 'off' }; end;
if result{3}, options = { options{:} 'addstd' 'on' }; else, options = { options{:} 'addstd' 'off' }; end;
if result{4}, options = { options{:} 'addall' 'on' }; end;
datsub = eval( [ '[' result{5} ']' ]);
if result{6}, options = { options{:} 'subavg' 'on' }; end;
if result{7}, options = { options{:} 'substd' 'on' }; end;
if result{8}, options = { options{:} 'suball' 'on' }; end;
if result{9}, options = { options{:} 'diffavg' 'on' }; else, options = { options{:} 'diffavg' 'off' }; end;
if result{10}, options = { options{:} 'diffstd' 'on' }; else, options = { options{:} 'diffstd' 'off' }; end;
if result{11}, options = { options{:} 'diffall' 'on' }; end;
if result{12}, options = { options{:} 'chans' eval( [ '[' result{12} ']' ]) }; end;
if ~isempty(result{13}), options = { options{:} 'alpha' str2num(result{13}) }; end;
if result{14}, options = { options{:} 'mode' 'rms' }; end;
if ~isempty(result{15}), options = { options{:} 'lowpass' str2num(result{15}) }; end;
if ~isempty(result{16}), options = { options{:} 'tplotopt' eval([ '{ ' result{16} ' }' ]) }; end;
else
options = varargin;
end;
if nargin == 3
datsub = []; % default
end
% decode inputs
% -------------
if isempty(datadd), error('First edit box (datasets to add) can not be empty'); end;
g = finputcheck( options, ...
{ 'chans' 'integer' [] [1:ALLEEG(datadd(1)).nbchan];
'title' 'string' [] '';
'alpha' 'float' [] [];
'geom' 'string' {'scalp';'array'} fastif(flag, 'scalp', 'array');
'addstd' 'string' {'on';'off'} fastif(isempty(datsub), 'on', 'off');
'substd' 'string' {'on';'off'} 'off';
'diffstd' 'string' {'on';'off'} 'on';
'addavg' 'string' {'on';'off'} fastif(isempty(datsub), 'on', 'off');
'subavg' 'string' {'on';'off'} 'off';
'diffavg' 'string' {'on';'off'} 'on';
'addall' 'string' {'on';'off'} 'off';
'suball' 'string' {'on';'off'} 'off';
'diffall' 'string' {'on';'off'} 'off';
'std' 'string' {'on';'off';'none'} 'none';
'diffonly' 'string' {'on';'off';'none'} 'none';
'allerps' 'string' {'on';'off';'none'} 'none';
'lowpass' 'float' [0 Inf] [];
'tlim' 'float' [] [];
'ylim' 'float' [] [];
'tplotopt' 'cell' [] {};
'mode' 'string' {'ave';'rms'} 'ave';
'multcmp' 'integer' [0 Inf] [] });
if isstr(g), error(g); end;
if length(datadd) == 1
disp('Cannot perform statistics using only 1 dataset');
g.alpha = [];
end;
figure; axcopy
try, icadefs; set(gcf, 'color', BACKCOLOR); axis off; catch, end;
% backward compatibility of param
% -------------------------------
if ~strcmpi(g.diffonly, 'none')
if strcmpi(g.diffonly, 'off'), g.addavg = 'on'; g.subavg = 'on'; end;
end;
if ~strcmpi(g.allerps, 'none')
if isempty(datsub)
g.addall = g.allerps;
else g.diffall = g.allerps;
end;
end;
if ~strcmpi(g.std, 'none')
if isempty(datsub)
g.addstd = g.std;
else g.diffstd = g.std;
end;
end;
% check consistency
% -----------------
if length(datsub) > 0 & length(datadd) ~= length(datsub)
error('The number of component to subtract must be the same as the number of components to add');
end;
% if only 2 dataset entered, toggle average to single trial
% ---------------------------------------------------------
if length(datadd) == 1 &strcmpi(g.addavg, 'on')
g.addavg = 'off';
g.addall = 'on';
end;
if length(datsub) == 1 &strcmpi(g.subavg, 'on')
g.subavg = 'off';
g.suball = 'on';
end;
if length(datsub) == 1 & length(datadd) == 1 &strcmpi(g.diffavg, 'on')
g.diffavg = 'off';
g.diffall = 'on';
end;
regions = {};
pnts = ALLEEG(datadd(1)).pnts;
srate = ALLEEG(datadd(1)).srate;
xmin = ALLEEG(datadd(1)).xmin;
xmax = ALLEEG(datadd(1)).xmax;
nbchan = ALLEEG(datadd(1)).nbchan;
chanlocs = ALLEEG(datadd(1)).chanlocs;
unionIndices = union_bc(datadd, datsub);
for index = unionIndices(:)'
if ALLEEG(index).pnts ~= pnts, error(['Dataset ' int2str(index) ' does not have the same number of points as others']); end;
if ALLEEG(index).xmin ~= xmin, error(['Dataset ' int2str(index) ' does not have the same xmin as others']); end;
if ALLEEG(index).xmax ~= xmax, error(['Dataset ' int2str(index) ' does not have the same xmax as others']); end;
if ALLEEG(index).nbchan ~= nbchan, error(['Dataset ' int2str(index) ' does not have the same number of channels as others']); end;
end;
if ~isempty(g.alpha) & length(datadd) == 1
error([ 'T-tests require more than one ''' datadd ''' dataset' ]);
end
% compute ERPs for add
% --------------------
for index = 1:length(datadd)
TMPEEG = eeg_checkset(ALLEEG(datadd(index)),'loaddata');
if flag == 1, erp1ind(:,:,index) = mean(TMPEEG.data,3);
else erp1ind(:,:,index) = mean(eeg_getdatact(TMPEEG, 'component', [1:size(TMPEEG.icaweights,1)]),3);
end;
addnames{index} = [ '#' int2str(datadd(index)) ' ' TMPEEG.setname ' (n=' int2str(TMPEEG.trials) ')' ];
clear TMPEEG;
end;
% optional: subtract
% ------------------
colors = {}; % color aspect for curves
allcolors = { 'b' 'r' 'g' 'c' 'm' 'y' [0 0.5 0] [0.5 0 0] [0 0 0.5] [0.5 0.5 0] [0 0.5 0.5] [0.5 0 0.5] [0.5 0.5 0.5] };
allcolors = { allcolors{:} allcolors{:} allcolors{:} allcolors{:} allcolors{:} allcolors{:} };
allcolors = { allcolors{:} allcolors{:} allcolors{:} allcolors{:} allcolors{:} allcolors{:} };
if length(datsub) > 0 % dataset to subtract
% compute ERPs for sub
% --------------------
for index = 1:length(datsub)
TMPEEG = eeg_checkset(ALLEEG(datsub(index)),'loaddata');
if flag == 1, erp2ind(:,:,index) = mean(TMPEEG.data,3);
else erp2ind(:,:,index) = mean(eeg_getdatact(TMPEEG, 'component', [1:size(TMPEEG.icaweights,1)]),3);
end;
subnames{index} = [ '#' int2str(datsub(index)) ' ' TMPEEG.setname '(n=' int2str(TMPEEG.trials) ')' ];
clear TMPEEG
end;
l1 = size(erp1ind,3);
l2 = size(erp2ind,3);
allcolors1 = allcolors(3:l1+2);
allcolors2 = allcolors(l1+3:l1+l2+3);
allcolors3 = allcolors(l1+l2+3:end);
[erps1, erpstd1, colors1, colstd1, legend1] = preparedata( erp1ind , g.addavg , g.addstd , g.addall , g.mode, 'Add ' , addnames, 'b', allcolors1 );
[erps2, erpstd2, colors2, colstd2, legend2] = preparedata( erp2ind , g.subavg , g.substd , g.suball , g.mode, 'Sub ' , subnames, 'r', allcolors2 );
[erps3, erpstd3, colors3, colstd3, legend3] = preparedata( erp1ind-erp2ind, g.diffavg, g.diffstd, g.diffall, g.mode, 'Diff ', ...
{ addnames subnames }, 'k', allcolors3 );
% handle special case of std
% --------------------------
erptoplot = [ erps1 erps2 erps3 erpstd1 erpstd2 erpstd3 ];
colors = { colors1{:} colors2{:} colors3{:} colstd1{:} colstd2{:} colstd3{:}};
legend = { legend1{:} legend2{:} legend3{:} };
% highlight significant regions
% -----------------------------
if ~isempty(g.alpha)
pvalues = pttest(erp1ind(g.chans,:,:), erp2ind(g.chans,:,:), 3);
regions = p2regions(pvalues, g.alpha, [xmin xmax]*1000);
else
pvalues= [];
end;
else
[erptoplot, erpstd, colors, colstd, legend] = preparedata( erp1ind, g.addavg, g.addstd, g.addall, g.mode, '', addnames, 'k', allcolors);
erptoplot = [ erptoplot erpstd ];
colors = { colors{:} colstd{:} };
% highlight significant regions
% -----------------------------
if ~isempty(g.alpha)
pvalues = ttest(erp1ind, 0, 3);
regions = p2regions(pvalues, g.alpha, [xmin xmax]*1000);
else
pvalues= [];
end;
end;
% lowpass data
% ------------
if ~isempty(g.lowpass)
if exist('filtfilt') == 2
erptoplot = eegfilt(erptoplot, srate, 0, g.lowpass);
else
erptoplot = eegfiltfft(erptoplot, srate, 0, g.lowpass);
end;
end;
if strcmpi(g.geom, 'array') | flag == 0, chanlocs = []; end;
if ~isfield(chanlocs, 'theta'), chanlocs = []; end;
% select time range
% -----------------
if ~isempty(g.tlim)
pointrange = round(eeg_lat2point(g.tlim/1000, [1 1], srate, [xmin xmax]));
g.tlim = eeg_point2lat(pointrange, [1 1], srate, [xmin xmax]);
erptoplot = reshape(erptoplot, size(erptoplot,1), pnts, size(erptoplot,2)/pnts);
erptoplot = erptoplot(:,[pointrange(1):pointrange(2)],:);
pnts = size(erptoplot,2);
erptoplot = reshape(erptoplot, size(erptoplot,1), pnts*size(erptoplot,3));
xmin = g.tlim(1);
xmax = g.tlim(2);
end;
% plot data
% ---------
plottopo( erptoplot, 'chanlocs', chanlocs, 'frames', pnts, ...
'limits', [xmin xmax 0 0]*1000, 'title', g.title, 'colors', colors, ...
'chans', g.chans, 'legend', legend, 'regions', regions, 'ylim', g.ylim, g.tplotopt{:});
% outputs
% -------
times = linspace(xmin, xmax, pnts);
erp1 = mean(erp1ind,3);
if length(datsub) > 0 % dataset to subtract
erp2 = mean(erp2ind,3);
erpsub = erp1-erp2;
else
erp2 = [];
erpsub = [];
end;
if nargin < 3 & nargout == 1
erp1 = sprintf('pop_comperp( %s, %d, %s);', inputname(1), ...
flag, vararg2str({ datadd datsub options{:} }) );
end;
return;
% convert significance values to alpha
% ------------------------------------
function regions = p2regions( pvalues, alpha, limits);
for index = 1:size(pvalues,1)
signif = diff([1 pvalues(index,:) 1] < alpha);
pos = find([signif] > 0);
pos = pos/length(pvalues)*(limits(2) - limits(1))+limits(1);
neg = find([signif(2:end)] < 0);
neg = neg/length(pvalues)*(limits(2) - limits(1))+limits(1);
if length(pos) ~= length(neg), signif, pos, neg, error('Region error'); end;
regions{index} = [neg;pos];
end;
% process data
% ------------
function [erptoplot, erpstd, colors, colstd, legend] = preparedata( erpind, plotavg, plotstd, plotall, mode, tag, dataset, coloravg, allcolors);
colors = {};
legend = {};
erptoplot = [];
erpstd = [];
colstd = {};
% plot individual differences
% ---------------------------
if strcmpi(plotall, 'on')
erptoplot = [ erptoplot erpind(:,:) ];
for index=1:size(erpind,3)
if iscell(dataset)
if strcmpi(tag, 'Diff ')
legend = { legend{:} [ dataset{1}{index} ' - ' dataset{2}{index} ] };
else
legend = { legend{:} dataset{index} };
end;
else
legend = { legend{:} [ 'Dataset ' int2str(dataset(index)) ] };
end;
colors = { colors{:} allcolors{index} };
end;
end;
% plot average
% ------------
if strcmpi( plotavg, 'on')
if strcmpi(mode, 'ave')
granderp = mean(erpind,3);
legend = { legend{:} [ tag 'Average' ] };
else granderp = sqrt(mean(erpind.^2,3));
legend = { legend{:} [ tag 'RMS' ] };
end;
colors = { colors{:} {coloravg;'linewidth';2 }};
erptoplot = [ erptoplot granderp];
end;
% plot standard deviation
% -----------------------
if strcmpi(plotstd, 'on')
if strcmpi(plotavg, 'on')
std1 = std(erpind, [], 3);
erptoplot = [ erptoplot granderp+std1 ];
erpstd = granderp-std1;
legend = { legend{:} [ tag 'Standard dev.' ] };
colors = { colors{:} { coloravg;'linestyle';':' } };
colstd = { { coloravg 'linestyle' ':' } };
else
disp('Warning: cannot show standard deviation without showing average');
end;
end;
% ------------------------------------------------------------------
function [p, t, df] = pttest(d1, d2, dim)
%PTTEST Student's paired t-test.
% PTTEST(X1, X2) gives the probability that Student's t
% calculated on paired data X1 and X2 is higher than
% observed, i.e. the "significance" level. This is used
% to test whether two paired samples have significantly
% different means.
% [P, T] = PTTEST(X1, X2) gives this probability P and the
% value of Student's t in T. The smaller P is, the more
% significant the difference between the means.
% E.g. if P = 0.05 or 0.01, it is very likely that the
% two sets are sampled from distributions with different
% means.
%
% This works for PAIRED SAMPLES, i.e. when elements of X1
% and X2 correspond one-on-one somehow.
% E.g. residuals of two models on the same data.
% Ref: Press et al. 1992. Numerical recipes in C. 14.2, Cambridge.
if size(d1,dim) ~= size(d2, dim)
error('PTTEST: paired samples must have the same number of elements !')
end
if size(d1,dim) == 1
close; error('Cannot compute paired t-test for a single ERP difference')
end;
a1 = mean(d1, dim);
a2 = mean(d2, dim);
v1 = std(d1, [], dim).^2;
v2 = std(d2, [], dim).^2;
n1 = size(d1,dim);
df = n1 - 1;
disp(['Computing t-values, df:' int2str(df) ]);
d1 = d1-repmat(a1, [ones(1,dim-1) size(d1,3)]);
d2 = d2-repmat(a2, [ones(1,dim-1) size(d2,3)]);
%cab = (x1 - a1)' * (x2 - a2) / (n1 - 1);
cab = sum(d1.*d2,3)/(n1-1);
% use abs to avoid numerical errors for very similar data
% for which v1+v2-2cab may be close to 0.
t = (a1 - a2) ./ sqrt(abs(v1 + v2 - 2 * cab) / n1) ;
p = betainc( df ./ (df + t.*t), df/2, 0.5) ;
% ------------------------------------------------------------------
function [p, t] = ttest(d1, d2, dim)
%TTEST Student's t-test for equal variances.
% TTEST(X1, X2) gives the probability that Student's t
% calculated on data X1 and X2, sampled from distributions
% with the same variance, is higher than observed, i.e.
% the "significance" level. This is used to test whether
% two sample have significantly different means.
% [P, T] = TTEST(X1, X2) gives this probability P and the
% value of Student's t in T. The smaller P is, the more
% significant the difference between the means.
% E.g. if P = 0.05 or 0.01, it is very likely that the
% two sets are sampled from distributions with different
% means.
%
% This works if the samples are drawn from distributions with
% the SAME VARIANCE. Otherwise, use UTTEST.
%
%See also: UTTEST, PTTEST.
if size(d1,dim) == 1
close; error('Cannot compute t-test for a single ERP')
end;
a1 = mean(d1, dim);
v1 = std(d1, [], dim).^2;
n1 = size(d1,dim);
if length(d2) == 1 & d2 == 0
a2 = 0;
n2 = n1;
df = n1 + n2 - 2;
pvar = (2*(n1 - 1) * v1) / df ;
else
a2 = mean(d2, dim);
v2 = std(d2, [], dim).^2;
n2 = size(d2,dim);
df = n1 + n2 - 2;
pvar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df ;
end;
disp(['Computing t-values, df:' int2str(df) ]);
t = (a1 - a2) ./ sqrt( pvar * (1/n1 + 1/n2)) ;
p = betainc( df ./ (df + t.*t), df/2, 0.5) ;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_jointprob.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/pop_jointprob.m
| 10,126 |
utf_8
|
17e94ffd9b3434caf75337897e769d38
|
% pop_jointprob() - reject artifacts in an EEG dataset using joint
% probability of the recorded electrode or component
% activities observed at each time point. e.g., Observing
% large absoluate values at most electrodes or components
% is improbable and may well mark the presence of artifact.
% Usage:
% >> pop_jointprob( INEEG, typerej) % pop-up interative window mode
% >> [OUTEEG, locthresh, globthresh, nrej] = ...
% = pop_jointprob( INEEG, typerej, elec_comp, ...
% locthresh, globthresh, superpose, reject, vistype);
%
% Graphic interface:
% "Electrode" - [edit box] electrode|component number(s) to take into
% consideration for rejection. Sets the 'elec_comp'
% parameter in the command line call (see below).
% "Single-channel limit(s)" - [edit box] activity probability limit(s) (in
% std. dev.) Sets the 'locthresh' command line parameter.
% If more than one, defined individual electrode|channel
% limits. If fewer values than the number of electrodes |
% components specified above, the last input value is used
% for all remaining electrodes|components.
% "All-channel limit(s)" - [edit box] activity probability limit(s) (in std.
% dev.) for all channels (grouped). Sets the 'globthresh'
% command line parameter.
% "Display with previously marked rejections?" - [edit box] either YES or
% NO. Sets the command line option 'superpose'.
% "Reject marked trial(s)?" - [edit box] either YES or NO. Sets the
% command line option 'reject'.
% "visualization mode" - [edit box] either REJECTRIALS or EEGPLOT.
% Sets the command line option 'vistype'.
% Inputs:
% INEEG - input dataset
% typerej - [1|0] data to reject on (0 = component activations;
% 1 = electrode data). {Default: 1 = electrode data}.
% elec_comp - [n1 n2 ...] electrode|component number(s) to take into
% consideration for rejection
% locthresh - activity probability limit(s) (in std. dev.) See "Single-
% channel limit(s)" above.
% globthresh - global limit(s) (all activities grouped) (in std. dev.)
% superpose - [0|1] 0 = Do not superpose rejection marks on previously
% marks stored in the dataset: 1 = Show both current and
% previous marks using different colors. {Default: 0}.
% reject - 0 = do not reject marked trials (but store the marks:
% 1 = reject marked trials {Default: 1}.
% vistype - visualization mode: 0 = rejstatepoch(); 1 = eegplot()
% {Default: 0}.
%
% Outputs:
% OUTEEG - output dataset with updated joint probability array
% locthresh - electrodes probability of activity thresholds in terms
% of standard-dev.
% globthresh - global threshold (where all electrode activity are
% regrouped).
% nrej - number of rejected sweeps
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: jointprob(), rejstatepoch(), eegplot(), eeglab(), pop_rejepoch()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
% 01-25-02 reformated help & license -ad
% 03-07-02 added srate argument to eegplot call -ad
% 03-08-02 add eeglab options -ad
function [EEG, locthresh, globthresh, nrej, com] = pop_jointprob( EEG, icacomp, elecrange, ...
locthresh, globthresh, superpose, reject, vistype, topcommand);
com = '';
if nargin < 1
help pop_jointprob;
return;
end;
if nargin < 2
icacomp = 1;
end;
if icacomp == 0
if isempty( EEG.icasphere )
ButtonName=questdlg( 'Do you want to run ICA now ?', ...
'Confirmation', 'NO', 'YES', 'YES');
switch ButtonName,
case 'NO', disp('Operation cancelled'); return;
case 'YES', [ EEG com ] = pop_runica(EEG);
end % switch
end;
end;
if exist('reject') ~= 1
reject = 1;
end;
if nargin < 3
% which set to save
% -----------------
promptstr = { [ fastif(icacomp, 'Electrode', 'Component') ' (number(s); Ex: 2 4 5):' ], ...
[ fastif(icacomp, 'Single-channel', 'Single-component') ' limit(s) (std. dev(s).: Ex: 2 2 2.5):'], ...
[ fastif(icacomp, 'All-channel', 'All-component') ' limit(s) (std. dev(s).: Ex: 2 2.1 2):'], ...
'Display previously marked rejections? (YES or NO)', ...
'Reject marked trial(s)? (YES or NO)', ...
'Visualization mode (REJECTRIALS|EEGPLOT)' };
inistr = { fastif(icacomp, ['1:' int2str(EEG.nbchan)], ['1:' int2str(size(EEG.icaweights,1))])...
fastif(icacomp, '3', '5'), ...
fastif(icacomp, '3', '5'), ...
'YES', ...
'NO', ...
'REJECTTRIALS' };
result = inputdlg2( promptstr, fastif( ~icacomp, 'Reject. improbable comp. -- pop_jointprob()', 'Reject improbable data -- pop_jointprob()'), 1, inistr, 'pop_jointprob');
size_result = size( result );
if size_result(1) == 0 return; end;
elecrange = result{1};
locthresh = result{2};
globthresh = result{3};
switch lower(result{4}), case 'yes', superpose=1; otherwise, superpose=0; end;
switch lower(result{5}), case 'yes', reject=1; otherwise, reject=0; end;
switch lower(result{6}), case 'rejecttrials', vistype=0; otherwise, vistype=1; end;
end;
if ~exist('vistype') vistype = 0; end;
if ~exist('reject') reject = 0; end;
if ~exist('superpose') superpose = 1; end;
if isstr(elecrange) % convert arguments if they are in text format
calldisp = 1;
elecrange = eval( [ '[' elecrange ']' ] );
locthresh = eval( [ '[' locthresh ']' ] );
globthresh = eval( [ '[' globthresh ']' ] );
else
calldisp = 0;
end;
if isempty(elecrange)
error('No electrode selectionned');
end;
% compute the joint probability
% -----------------------------
if icacomp == 1
fprintf('Computing joint probability for channels...\n');
tmpdata = eeg_getdatact(EEG);
if isempty(EEG.stats.jpE)
[ EEG.stats.jpE rejE ] = jointprob( tmpdata, locthresh, EEG.stats.jpE, 1);
end;
[ tmp rejEtmp ] = jointprob( tmpdata(elecrange,:,:), locthresh, EEG.stats.jpE(elecrange,:), 1);
rejE = zeros(EEG.nbchan, size(rejEtmp,2));
rejE(elecrange,:) = rejEtmp;
fprintf('Computing all-channel probability...\n');
tmpdata2 = permute(tmpdata, [3 1 2]);
tmpdata2 = reshape(tmpdata2, size(tmpdata2,1), size(tmpdata2,2)*size(tmpdata2,3));
[ EEG.stats.jp rej ] = jointprob( tmpdata2, globthresh, EEG.stats.jp, 1);
clear tmpdata2;
else
tmpdata = eeg_getica(EEG);
fprintf('Computing joint probability for components...\n');
if isempty(EEG.stats.icajpE)
[ EEG.stats.icajpE rejE ] = jointprob( tmpdata, locthresh, EEG.stats.icajpE, 1);
end;
[ tmp rejEtmp ] = jointprob( tmpdata(elecrange,:), locthresh, EEG.stats.icajpE(elecrange,:), 1);
rejE = zeros(size(tmpdata,1), size(rejEtmp,2));
rejE(elecrange,:) = rejEtmp;
fprintf('Computing global joint probability...\n');
tmpdata2 = permute(tmpdata, [3 1 2]);
tmpdata2 = reshape(tmpdata2, size(tmpdata2,1), size(tmpdata2,2)*size(tmpdata2,3));
[ EEG.stats.icajp rej] = jointprob( tmpdata2, globthresh, EEG.stats.icajp, 1);
clear tmpdata2;
end;
rej = rej' | max(rejE, [], 1);
fprintf('%d/%d trials marked for rejection\n', sum(rej), EEG.trials);
if calldisp
if vistype == 1 % EEGPLOT -------------------------
if icacomp == 1 macrorej = 'EEG.reject.rejjp';
macrorejE = 'EEG.reject.rejjpE';
else macrorej = 'EEG.reject.icarejjp';
macrorejE = 'EEG.reject.icarejjpE';
end;
colrej = EEG.reject.rejjpcol;
eeg_rejmacro; % script macro for generating command and old rejection arrays
if icacomp == 1
eegplot( tmpdata(elecrange,:,:), 'srate', ...
EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:});
else
eegplot( tmpdata(elecrange,:,:), 'srate', ...
EEG.srate, 'limits', [EEG.xmin EEG.xmax]*1000 , 'command', command, eegplotoptions{:});
end;
else % REJECTRIALS -------------------------
if icacomp == 1
[ rej, rejE, n, locthresh, globthresh] = ...
rejstatepoch( tmpdata(elecrange,:,:), EEG.stats.jpE(elecrange,:), 'global', 'on', 'rejglob', EEG.stats.jp, ...
'threshold', locthresh, 'thresholdg', globthresh, 'normalize', 'off' );
else
[ rej, rejE, n, locthresh, globthresh] = ...
rejstatepoch( tmpdata(elecrange,:,:), EEG.stats.icajpE(elecrange,:), 'global', 'on', 'rejglob', EEG.stats.icajp, ...
'threshold', locthresh, 'thresholdg', globthresh, 'normalize', 'off' );
end;
nrej = n;
end;
else
% compute rejection locally
rejtmp = max(rejE(elecrange,:),[],1);
rej = rejtmp | rej;
nrej = sum(rej);
fprintf('%d trials marked for rejection\n', nrej);
end;
if ~isempty(rej)
if icacomp == 1
EEG.reject.rejjp = rej;
EEG.reject.rejjpE = rejE;
else
EEG.reject.icarejjp = rej;
EEG.reject.icarejjpE = rejE;
end;
if reject
EEG = pop_rejepoch(EEG, rej, 0);
end;
end;
nrej = sum(rej);
com = [ com sprintf('%s = pop_jointprob(%s,%s);', inputname(1), ...
inputname(1), vararg2str({icacomp,elecrange,locthresh,globthresh,superpose,reject})) ];
if nargin < 3 & nargout == 2
locthresh = com;
end;
return;
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_lat2point.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_lat2point.m
| 4,019 |
utf_8
|
fc612a716877495d005080fab259effb
|
% eeg_lat2point() - convert latencies in time units relative to the
% time locking event of an eeglab() data epoch to
% latencies in data points (assuming concatenated epochs).
% Usage:
% >> [newlat] = eeg_lat2point( lat_array, epoch_array,...
% srate, timelimits, timeunit);
% >> [newlat] = eeg_lat2point( lat_array, epoch_array,...
% srate, timelimits, '','outrange',1);
% Inputs:
% lat_array - latency array in 'timeunit' units (see below)
% epoch_array - epoch number for each latency
% srate - data sampling rate in Hz
% timelimits - [min max] epoch timelimits in 'timeunit' units (see below)
% timeunit - time unit relative to seconds. Default is 1 = seconds.
%
% Optional inputs:
% outrange - [1/0] Replace the points out of the range with the value of
% the maximun point in the valid range or raise an error.
% Default [1] : Replace point.
%
% Outputs:
% newlat - converted latency values in points assuming concatenated
% data epochs (see eeglab() event structure)
% flag - 1 if any point out of range was replaced.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2 Mai 2002
%
% See also: eeg_point2lat(), eeglab()
% Copyright (C) 2 Mai 2002 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [newlat,flag] = eeg_lat2point( lat_array, epoch_array, srate, timewin, timeunit, varargin);
% -------------------------------------------------------------------------
try
options = varargin;
if ~isempty( varargin ),
for i = 1:2:numel(options)
g.(options{i}) = options{i+1};
end
else g= []; end;
catch
error('std_checkdatasession() error: calling convention {''key'', value, ... } error');
end;
try, g.outrange; catch, g.outrange = 1; end; %
flag = 0;
% -------------------------------------------------------------------------
if nargin <4
help eeg_lat2point;
return;
end;
if nargin <5 | isempty(timeunit)
timeunit = 1;
end;
if length(lat_array) ~= length(epoch_array)
if length(epoch_array)~= 1
disp('eeg_lat2point: latency and epochs must have the same length'); return;
else
epoch_array = ones(1,length(lat_array))*epoch_array;
end;
end;
if length(timewin) ~= 2
disp('eeg_lat2point: timelimits must have length 2'); return;
end;
if iscell(epoch_array)
epoch_array = [ epoch_array{:} ];
end;
if iscell(lat_array)
lat_array = [ lat_array{:} ];
end
timewin = timewin*timeunit;
pnts = (timewin(2)-timewin(1))*srate+1;
newlat = (lat_array*timeunit-timewin(1))*srate+1 + (epoch_array-1)*pnts;
% Detecting points out of range (RMC)
% Note: This is neccesary since the double precision multiplication could lead to the
% shifting in one sample out of the valid range
if and(~isempty(newlat),~isempty(epoch_array)) && max(newlat(:)) > max((epoch_array)*pnts)
if g.outrange == 1
IndxOut = find(newlat(:) > max((epoch_array)*pnts));
newlat(IndxOut) = max((epoch_array)*pnts);
flag = 1;
warning('eeg_lat2point(): Points out of range detected. Points replaced with maximum value');
elseif g.outrange == 0
error('Error in eeg_lat2point(): Points out of range detected');
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_addnewevents.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/popfunc/eeg_addnewevents.m
| 7,648 |
utf_8
|
ffc9194217c3e26d7b32be5361c7163b
|
% eeg_addnewevents() Add new events to EEG structure. Both EEG.event and
% EEG.urevent are updated.
%
% Usage:
% >> EEG = eeg_addnewevents(EEG, latencies, types, fieldNames, fieldValues);
%
% Inputs:
% EEG - input dataset
% latencies - cell containing numerical arrays for latencies of new
% events, each array corresponds to a different event type.
% type - cell array containing name of event types.
%
% Optional Inputs
% fieldNames - cell array containing names of fields to be added to event structure.
% fieldValues - A cell containing arrays for field values corresponding to fieldNames.
% Number of values for each field should be equal to the total number of
% latencies (new events) added to dataset.
% Outputs:
% EEG - EEG dataset with updated event and urevent fields
%
% Example:
% EEG = eeg_addnewevents(EEG, {[100 200] [300 400 500]}, {'type1' 'type2'}, {'field1' 'field2'}, {[1 2 3 4 5] [6 7 8 9]});
%
% Author: Nima Bigdely Shamlo, SCCN/INC/UCSD, 2008
function EEG = eeg_addnewevents(EEG, eventLatencyArrays, types, fieldNames, fieldValues);
if ~isfield(EEG, 'event')
EEG.event = [];
EEG.urevent = [];
EEG.event(1).type = 'dummy';
EEG.event(1).latency = 1;
EEG.event(1).duration = 0;
EEG.event(1).urevent = 1;
EEG.urevent(1).type = 'dummy';
EEG.urevent(1).latency = 1;
EEG.urevent(1).duration = 0;
end;
% add duration field if it does not exist
if length(EEG.event)>0 && ~isfield(EEG.event(1),'duration')
EEG.event(1).duration = 0;
EEG.urevent(1).duration = 0;
end;
if nargin<4
fieldNames = [];
fieldValues = [];
end;
newEventLatency = [];
for i=1:length(eventLatencyArrays)
newEventLatency = [newEventLatency eventLatencyArrays{i}];
end;
newEventType = [];
for i=1:length(eventLatencyArrays{1})
newEventType{i} = types{1};
end;
for j=2:length(eventLatencyArrays)
startIndex = length(newEventType);
for i=1:length(eventLatencyArrays{j})
newEventType{startIndex+i} = types{j};
end;
end;
% mix new and old events, sort them by latency and put them back in EEG
originalEventLatency = [];
originalEventType = [];
originalFieldNames = [];
for i=1:length(EEG.event)
originalEventLatency(i) = EEG.event(i).latency;
originalEventType{i} = EEG.event(i).type;
originalEventFields(i) = EEG.event(i);
end;
% make sure that originalEventFields has all the new field names
if ~isempty(EEG.event)
originalFieldNames = fields(originalEventFields);
for f= 1:length(fieldNames)
if ~isfield(originalEventFields, fieldNames{f})
originalEventFields(length(originalEventFields)).(fieldNames{f}) = NaN;
end;
end;
end;
% make sure that newEventFields has all the original field names
for i=1:length(originalFieldNames)
newEventFields(length(newEventLatency)).(originalFieldNames{i}) = NaN;
end;
for i=1:length(newEventLatency)
newEventFields(i).latency = newEventLatency(i);
newEventFields(i).type = newEventType{i};
newEventFields(i).duration = 0;
for f= 1:length(fieldNames)
newEventFields(i).(fieldNames{f}) = fieldValues{f}(i);
end;
end;
if ~isempty(EEG.event)
%newEventFields = struct('latency', num2cell(newEventLatency), 'type', newEventType);
combinedFields = [originalEventFields newEventFields];
combinedLatencies = [originalEventLatency newEventLatency];
combinedType = [originalEventType newEventType];
else
combinedFields = newEventFields;
combinedLatencies = newEventLatency;
combinedType = newEventType;
end
[sortedEventLatency order] = sort(combinedLatencies,'ascend');
sortedEventType = combinedType(order);
combinedFields = combinedFields(order);
% put events in eeg
%EEG.urevent = [];
%EEG.event = [];
EEG = rmfield(EEG,'event');
for i=1:length(sortedEventLatency)
% EEG.urevent(i).latency = sortedEventLatency(i);
% EEG.urevent(i).type = sortedEventType{i};
% combinedFields(order(i)).urevent = i;
EEG.event(i) = combinedFields(i);
% EEG.event(i).urevent = i;
end;
%% adding new urevents
originalUreventNumber = 1:length(EEG.urevent);
originalUreventLatency = zeros(1, length(EEG.urevent));
originalUreventFields= cell(1, length(EEG.urevent));
for i=1:length(EEG.urevent)
originalUreventLatency(i) = EEG.urevent(i).latency;
originalUreventFields{i} = EEG.urevent(i);
end;
newUreventLatency = [];
newUreventType = [];
for i=1:length(EEG.event)
if ~isfield(EEG.event,'urevent') || length(EEG.event(i).urevent) == 0 || isnan(EEG.event(i).urevent)
% newUreventLatency = [newUreventLatency newEventUrEventLatency(EEG, combinedFields, i)];
% use eeg_urlatency to calculate the original latency based on
% EEG.event duartions
newUreventLatency = [newUreventLatency eeg_urlatency(EEG.event, EEG.event(i).latency)];
else
newUreventLatency = [newUreventLatency EEG.urevent(EEG.event(i).urevent).latency];
end;
newUreventFields{i} = EEG.event(i);
newUreventEventNumber(i) = i;
end;
combinedEventNumber = newUreventEventNumber;%[NaN(1,length(EEG.urevent)) newUreventEventNumber];
combinedUrEventLatencies = newUreventLatency;%[originalUreventLatency newUreventLatency];
[sortedUrEventLatency order] = sort(combinedUrEventLatencies,'ascend');
% make urvent stucture ready
EEG.urevent = [];
EEG.urevent= newUreventFields{order(1)};
for i=1:length(order)
%if ~isnan(newUreventEventNumber(i))
EEG.urevent(i) = newUreventFields{order(i)};
EEG.urevent(i).latency = combinedUrEventLatencies(order(i));
EEG.event(newUreventEventNumber(i)).urevent = i;
%end;
end;
if isfield(EEG.urevent,'urevent')
EEG.urevent = rmfield(EEG.urevent,'urevent'); % remove urevent field
end;
% turn empty event durations into 0
for i=1:length(EEG.event)
if isempty(EEG.event(i).duration)
EEG.event(i).duration = 0;
end;
end;
for i=1:length(EEG.urevent)
if isempty(EEG.urevent(i).duration)
EEG.urevent(i).duration = 0;
end;
end;
%
% function latency = newEventUrEventLatency(EEG, combinedFields, i)
%
% %% looks for an event with urvent before the new event
% urlatencyBefore = [];
% currentEventNumber = i;
%
% while isempty(urlatencyBefore) && currentEventNumber > 1
% currentEventNumber = currentEventNumber - 1;
% if ~(~isfield(combinedFields(currentEventNumber),'urevent') || isempty(combinedFields(currentEventNumber).urevent) || isnan(combinedFields(currentEventNumber).urevent))
% urlatencyBefore = EEG.urevent(combinedFields(currentEventNumber).urevent).latency;
% end;
% end
%
% %% if no event with urevent is found before, look for an event with urvent after the new event
% if isempty(urlatencyBefore)
% urlatencyAfter = [];
% currentEventNumber = i;
%
% while isempty(urlatencyAfter) && currentEventNumber < length(combinedFields)
% currentEventNumber = currentEventNumber + 1;
% if ~(~isfield(combinedFields(currentEventNumber),'urevent') || isempty(combinedFields(currentEventNumber).urevent) || isnan(combinedFields(currentEventNumber).urevent))
% urlatencyAfter = EEG.urevent(combinedFields(currentEventNumber).urevent).latency;
% end;
% end
% end;
% %%
% if ~isempty(urlatencyBefore)
% latency = urlatencyBefore + combinedFields(i).latency - combinedFields(currentEventNumber).latency;
% elseif ~isempty(urlatencyAfter)
% latency = urlatencyAfter + combinedFields(currentEventNumber).latency - combinedFields(i).latency;
% else
% latency = [];
% end;
|
github
|
ZijingMao/baselineeegtest-master
|
supergui.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/guifunc/supergui.m
| 21,074 |
utf_8
|
05da62a5889eab777551326464481bdf
|
% supergui() - a comprehensive gui automatic builder. This function help
% to create GUI very fast without bothering about the
% positions of the elements. After creating a geometry,
% elements just place themselves into the predefined
% locations. It is especially usefull for figure where you
% intend to put text button and descriptions.
%
% Usage:
% >> [handles, height, allhandles ] = ...
% supergui( 'key1', 'val1', 'key2', 'val2', ... );
%
% Inputs:
% 'fig' - figure handler, if not given, create a new figure.
% 'geom' - cell array of cell array of integer vector. Each cell
% array defines the coordinate of a given input in the following
% manner: { nb_row nb_col [x_topcorner y_topcorner]
% [x_bottomcorner y_bottomcorner] };
% 'geomhoriz' - integer vector or cell array of numerical vectors describing the
% geometry of the elements in the figure.
% - if integer vector, vector length is the number of rows and vector
% values are the number of 'uilist' elements in each row.
% For example, [2 3 2] means that the
% figures will have 3 rows, with 2 elements in the first
% and last row and 3 elements in the second row.
% - if cell array, each vector describes the relative widths
% of items in each row. For example, { [2 8] [1 2 3] } which means
% that figures will have 2 rows, the first one with 2
% elements of relative width 2 and 8 (20% and 80%). The
% second row will have 3 elements of relative size 1, 2
% and 3 (1/6 2/6 and 3/6).
% 'geomvert' - describting geometry for the rows. For instance
% [1 2 1] means that the second row will be twice the height
% of the other ones. If [], all the lines have the same height.
% 'uilist' - list of uicontrol lists describing elements properties
% { { ui1 }, { ui2 }... }, { 'uiX' } being GUI matlab
% uicontrol arguments such as { 'style', 'radiobutton',
% 'String', 'hello' }. See Matlab function uicontrol() for details.
% 'borders' - [left right top bottom] GUI internal borders in normalized
% units (0 to 1). Default values are
% 'title' - optional figure title
% 'userdata' - optional userdata input for the figure
% 'inseth' - horizontal space between elements. Default is 2%
% of window size.
% 'insetv' - vertical space between elements. Default is 2%
% of window height.
% 'spacing' - [horiz vert] spacing in normalized units. Default
% 'spacingtype' - ['absolute'|'proportional'] abolute means that the
% spacing values are fixed. Proportional means that they
% depend on the number of element in a line.
% 'minwidth' - [integer] minimal width in pixels. Default is none.
% 'screenpos' - [x y] position of the right top corner of the graphic
% interface. 'center' may also be used to center the GUI on
% the screen.
% 'adjustbuttonwidth' - ['on'|'off'] adjust button width in the GUI.
% Default is 'off'.
%
% Hint:
% use 'print -mfile filemane' to save a matlab file of the figure.
%
% Output:
% handles - all the handles of the elements (in the same order as the
% uilist input).
% height - adviced height for the figure (so the text look nice).
% allhandles - all the handles in object format
%
% Example:
% figure;
% supergui( 'geomhoriz', { 1 1 }, 'uilist', { ...
% { 'style', 'radiobutton', 'string', 'radio' }, ...
% { 'style', 'pushbutton' , 'string', 'push' } } );
%
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 2001-
%
% See also: eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [handlers, outheight, allhandlers] = supergui( varargin);
% handlers cell format
% allhandlers linear format
handlers = {};
outheight = 0;
if nargin < 2
help supergui;
return;
end;
% get version and
% set additional parameters
% -------------------------
v = version;
indDot = find(v == '.');
versnum = str2num(v(1:indDot(2)-1));
if versnum >= 7.14
addParamFont = { 'fontsize' 12 };
else addParamFont = { };
end;
warning off MATLAB:hg:uicontrol:ParameterValuesMustBeValid
% decoding input and backward compatibility
% -----------------------------------------
if isstr(varargin{1})
options = varargin;
else
options = { 'fig' varargin{1} 'geomhoriz' varargin{2} ...
'geomvert' varargin{3} 'uilist' varargin(4:end) };
end
g = finputcheck(options, { 'geomhoriz' 'cell' [] {};
'fig' '' [] 0;
'geom' 'cell' [] {};
'uilist' 'cell' [] {};
'title' 'string' [] '';
'userdata' '' [] [];
'adjustbuttonwidth' 'string' { 'on' 'off' } 'off';
'geomvert' 'real' [] [];
'screenpos' { 'real' 'string' } [] [];
'horizontalalignment' 'string' { 'left','right','center' } 'left';
'minwidth' 'real' [] 10;
'borders' 'real' [] [0.05 0.04 0.07 0.06];
'spacing' 'real' [] [0.02 0.01];
'inseth' 'real' [] 0.02; % x border absolute (5% of width)
'insetv' 'real' [] 0.02 }, 'supergui');
if isstr(g), error(g); end
if ~isempty(g.geomhoriz)
maxcount = sum(cellfun('length', g.geomhoriz));
if maxcount ~= length(g.uilist)
warning('Wrong size for ''geomhoriz'' input');
end;
if ~isempty(g.geomvert)
if length(g.geomvert) ~= length(g.geomhoriz)
warning('Wrong size for ''geomvert'' input');
end;
end;
g.insetv = g.insetv/length(g.geomhoriz);
end;
if ~isempty(g.geom)
if length(g.geom) ~= length(g.uilist)
warning('Wrong size for ''geom'' input');
end;
maxcount = length(g.geom);
end;
% create new figure
% -----------------
if g.fig == 0
g.fig = figure('visible','off');
end
% converting the geometry formats
% -------------------------------
if ~isempty(g.geomhoriz) & ~iscell( g.geomhoriz )
oldgeom = g.geomhoriz;
g.geomhoriz = {};
for row = 1:length(oldgeom)
g.geomhoriz = { g.geomhoriz{:} ones(1, oldgeom(row)) };
end;
end
if isempty(g.geomvert)
g.geomvert = ones(1, length(g.geomhoriz));
end
% converting to the new format
% ----------------------------
if isempty(g.geom)
count = 1;
incy = 0;
sumvert = sum(g.geomvert);
maxhoriz = 1;
for row = 1:length(g.geomhoriz)
incx = 0;
maxhoriz = max(maxhoriz, length(g.geomhoriz{row}));
ratio = length(g.geomhoriz{row})/sum(g.geomhoriz{row});
for column = 1:length(g.geomhoriz{row})
g.geom{count} = { length(g.geomhoriz{row}) sumvert [incx incy] [g.geomhoriz{row}(column)*ratio g.geomvert(row)] };
incx = incx+g.geomhoriz{row}(column)*ratio;
count = count+1;
end;
incy = incy+g.geomvert(row);
end;
g.borders(1:2) = g.borders(1:2)/maxhoriz*5;
g.borders(3:4) = g.borders(3:4)/sumvert*10;
g.spacing(1) = g.spacing(1)/maxhoriz*5;
g.spacing(2) = g.spacing(2)/sumvert*10;
end;
% disp new geometry
% -----------------
if 0
fprintf('{ ...\n');
for index = 1:length(g.geom)
fprintf('{ %g %g [%g %g] [%g %g] } ...\n', g.geom{index}{1}, g.geom{index}{2}, ...
g.geom{index}{3}(1), g.geom{index}{3}(2), g.geom{index}{4}(1), g.geom{index}{3}(2));
end;
fprintf('};\n');
end;
% get axis coordinates
% --------------------
try
set(g.fig, 'menubar', 'none', 'numbertitle', 'off');
catch
end
pos = [0 0 1 1]; % plot relative to current axes
q = [pos(1) pos(2) 0 0];
s = [pos(3) pos(4) pos(3) pos(4)]; % allow to use normalized position [0 100] for x and y
axis('off');
% creating guis
% -------------
row = 1; % count the elements
column = 1; % count the elements
factmultx = 0;
factmulty = 0; %zeros(length(g.geomhoriz));
for counter = 1:maxcount
% init
clear rowhandle;
gm = g.geom{counter};
[posx posy width height] = getcoord(gm{1}, gm{2}, gm{3}, gm{4}, g.borders, g.spacing);
try
currentelem = g.uilist{ counter };
catch
fprintf('Warning: not all boxes were filled\n');
return;
end;
if ~isempty(currentelem)
% decode metadata
% ---------------
if strcmpi(currentelem{1}, 'link2lines'),
currentelem(1) = [];
hf1 = 3.6/2-0.3;
hf2 = 0.7/2-0.3;
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx-width/2 posy+hf1*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', '');
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx-width/2 posy+hf2*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', '');
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx posy+hf2*height 0.005 (hf1-hf2+0.1)*height].*s+q, 'style', 'pushbutton', 'string', '');
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx posy+(hf1+hf2)/2*height width/2 0.005].*s+q, 'style', 'pushbutton', 'string', '');
allhandlers{counter} = 0;
else
if strcmpi(currentelem{1}, 'width'),
curwidth = currentelem{2};
currentelem(1:2) = [];
else curwidth = 0;
end;
if strcmpi(currentelem{1}, 'align'),
align = currentelem{2};
currentelem(1:2) = [];
else align = 'right';
end;
if strcmpi(currentelem{1}, 'stickto'),
stickto = currentelem{2};
currentelem(1:2) = [];
else stickto = 'none';
end;
if strcmpi(currentelem{1}, 'vertshift'), currentelem(1) = []; addvert = -height/2;
else addvert = 0;
end;
if strcmpi(currentelem{1}, 'vertexpand'), heightfactor = currentelem{2}; addvert = -(heightfactor-1)*height; currentelem(1:2) = [];
else heightfactor = 1;
end;
% position adjustment depending on GUI type
if isstr(currentelem{2}) && strcmpi(currentelem{2}, 'popupmenu')
posy = posy-height/10;
end;
if isstr(currentelem{2}) && strcmpi(currentelem{2}, 'text')
posy = posy+height/5;
end;
if strcmpi(currentelem{1}, 'function'),
% property grid argument
panel = uipanel('Title','','FontSize',12,'BackgroundColor','white','Position',[posx posy+addvert width height*heightfactor].*s+q);
allhandlers{counter} = arg_guipanel(panel, currentelem{:});
else
allhandlers{counter} = uicontrol(g.fig, 'unit', 'normalized', 'position', ...
[posx posy+addvert width height*heightfactor].*s+q, currentelem{:}, addParamFont{:});
% this simply compute a factor so that all uicontrol will be visible
% ------------------------------------------------------------------
style = get( allhandlers{counter}, 'style');
set( allhandlers{counter}, 'units', 'pixels');
curpos = get(allhandlers{counter}, 'position');
curext = get(allhandlers{counter}, 'extent');
if curwidth ~= 0
curwidth = curwidth/((factmultx-1)/1.85+1);
if strcmpi(align, 'right')
curpos(1) = curpos(1)+curpos(3)-curwidth;
elseif strcmpi(align, 'center')
curpos(1) = curpos(1)+curpos(3)/2-curwidth/2;
end;
set(allhandlers{counter}, 'position', [ curpos(1) curpos(2) curwidth curpos(4) ]);
if strcmpi(stickto, 'on')
set( allhandlers{counter-1}, 'units', 'pixels');
curpos2 = get(allhandlers{counter-1}, 'position');
set(allhandlers{counter-1}, 'position', [ curpos(1)-curpos2(3)-10 curpos2(2) curpos2(3) curpos2(4) ]);
set( allhandlers{counter-1}, 'units', 'normalized');
end;
curext(3) = curwidth;
end;
set( allhandlers{counter}, 'units', 'normalized');
end;
if ~strcmp(style, 'edit') && (~strcmp(style, 'pushbutton') || strcmpi(g.adjustbuttonwidth, 'on'))
%tmp = curext(3)/curpos(3);
%if tmp > 3*factmultx && factmultx > 0, adsfasd; end;
factmultx = max(factmultx, curext(3)/curpos(3));
if strcmp(style, 'pushbutton'), factmultx = factmultx*1.1; end;
end;
if ~strcmp(style, 'listbox')
factmulty = max(factmulty, curext(4)/curpos(4));
end;
% Uniformize button text aspect (first letter must be upercase)
% -----------------------------
if strcmp(style, 'pushbutton')
tmptext = get(allhandlers{counter}, 'string');
if length(tmptext) > 1
if upper(tmptext(1)) ~= tmptext(1) || lower(tmptext(2)) ~= tmptext(2) && ~strcmpi(tmptext, 'STATS')
tmptext = lower(tmptext);
try, tmptext(1) = upper(tmptext(1)); catch, end;
end;
end;
set(allhandlers{counter}, 'string', tmptext);
end;
end;
else
allhandlers{counter} = 0;
end;
end;
% adjustments
% -----------
factmultx = factmultx*1.02;% because some text was still hidden
%factmultx = factmultx*1.2;
if factmultx < 0.1
factmultx = 0.1;
end;
% for MAC (magnify figures that have edit fields)
% -------
warning off;
try,
comp = computer;
if length(comp) > 2 && strcmpi(comp(1:3), 'MAC')
factmulty = factmulty*1.5;
elseif ~isunix % windows
factmulty = factmulty*1.08;
end;
catch, end;
factmulty = factmulty*0.9; % global shinking
warning on;
% scale and replace the figure in the screen
% -----------------------------------------
pos = get(g.fig, 'position');
if factmulty > 1
pos(2) = max(0,pos(2)+pos(4)-pos(4)*factmulty);
end;
pos(1) = pos(1)+pos(3)*(1-factmultx)/2;
pos(3) = max(pos(3)*factmultx, g.minwidth);
pos(4) = pos(4)*factmulty;
set(g.fig, 'position', pos);
% vertical alignment to bottom for text (isnumeric by ishanlde was changed here)
% ---------------------------------------
for index = 1:length(allhandlers)
if allhandlers{index} ~= 0 && ishandle(allhandlers{index})
if strcmp(get(allhandlers{index}, 'style'), 'text')
set(allhandlers{index}, 'unit', 'pixel');
curpos = get(allhandlers{index}, 'position');
curext = get(allhandlers{index}, 'extent');
set(allhandlers{index}, 'position', [curpos(1) curpos(2)-4 curpos(3) curext(4)]);
set(allhandlers{index}, 'unit', 'normalized');
end;
end;
end;
% setting defaults colors
%------------------------
try, icadefs;
catch,
GUIBACKCOLOR = [.8 .8 .8];
GUIPOPBUTTONCOLOR = [.8 .8 .8];
GUITEXTCOLOR = [0 0 0];
end;
numobjects = cellfun(@ishandle, allhandlers); % (isnumeric by ishanlde was changed here)
allhandlersnum = [ allhandlers{numobjects} ];
hh = findobj(allhandlersnum, 'parent', g.fig, 'style', 'text');
%set(hh, 'BackgroundColor', get(g.fig, 'color'), 'horizontalalignment', 'left');
set(hh, 'Backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
try
set(g.fig, 'color',GUIBACKCOLOR );
catch
end
set(hh, 'horizontalalignment', g.horizontalalignment);
hh = findobj(allhandlersnum, 'style', 'edit');
set(hh, 'BackgroundColor', [1 1 1]); %, 'horizontalalignment', 'right');
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'pushbutton');
comp = computer;
if length(comp) < 3 || ~strcmpi(comp(1:3), 'MAC') % this puts the wrong background on macs
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
end;
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'popupmenu');
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'checkbox');
set(hh, 'backgroundcolor', GUIBACKCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'listbox');
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(hh, 'foregroundcolor', GUITEXTCOLOR);
hh =findobj(allhandlersnum, 'parent', g.fig, 'style', 'radio');
set(hh, 'foregroundcolor', GUITEXTCOLOR);
set(hh, 'backgroundcolor', GUIPOPBUTTONCOLOR);
set(g.fig, 'visible', 'on');
% screen position
% ---------------
if ~isempty(g.screenpos)
pos = get(g.fig, 'position');
if isnumeric(g.screenpos)
set(g.fig, 'position', [ g.screenpos pos(3) pos(4)]);
else
screenSize = get(0, 'screensize');
pos(1) = (screenSize(3)-pos(3))/2;
pos(2) = (screenSize(4)-pos(4))/2+pos(4);
set(g.fig, 'position', pos);
end;
end;
% set userdata and title
% ----------------------
if ~isempty(g.userdata), set(g.fig, 'userdata', g.userdata); end;
if ~isempty(g.title ), set(g.fig, 'name', g.title ); end;
return;
function [posx posy width height] = getcoord(geom1, geom2, coord1, sz, borders, spacing);
coord2 = coord1+sz;
borders(1:2) = borders(1:2)-spacing(1);
borders(3:4) = borders(3:4)-spacing(2);
% absolute positions
posx = coord1(1)/geom1;
posy = coord1(2)/geom2;
posx2 = coord2(1)/geom1;
posy2 = coord2(2)/geom2;
width = posx2-posx;
height = posy2-posy;
% add spacing
posx = posx+spacing(1)/2;
width = max(posx2-posx-spacing(1), 0.001);
height = max(posy2-posy-spacing(2), 0.001);
posy = max(0, 1-posy2)+spacing(2)/2;
% add border
posx = posx*(1-borders(1)-borders(2))+borders(1);
posy = posy*(1-borders(3)-borders(4))+borders(4);
width = width*( 1-borders(1)-borders(2));
height = height*(1-borders(3)-borders(4));
function [posx posy width height] = getcoordold(geom1, geom2, coord1, sz);
coord2 = coord1+sz;
horiz_space = 0.05/geom1;
vert_space = 0.05/geom2;
horiz_border = min(0.1, 1/geom1)-horiz_space;
vert_border = min(0.2, 1.5/geom2)-vert_space;
% absolute positions
posx = coord1(1)/geom1;
posy = coord1(2)/geom2;
posx2 = coord2(1)/geom1;
posy2 = coord2(2)/geom2;
width = posx2-posx;
height = posy2-posy;
% add spacing
posx = posx+horiz_space/2;
width = max(posx2-posx-horiz_space, 0.001);
height = max(posy2-posy- vert_space, 0.001);
posy = max(0, 1-posy2)+vert_space/2;
% add border
posx = posx*(1-horiz_border)+horiz_border/2;
posy = posy*(1- vert_border)+vert_border/2;
width = width*(1-horiz_border);
height = height*(1-vert_border);
% posx = coord1(1)/geom1+horiz_border*1/geom1/2;
% posy = 1-(coord1(2)/geom2+vert_border*1/geom2/2)-1/geom2;
%
% posx2 = coord2(1)/geom1+horiz_border*1/geom1/2;
% posy2 = 1-(coord2(2)/geom2+vert_border*1/geom2/2)-1/geom2;
%
% width = posx2-posx;
% height = posy-posy2;
%h = axes('unit', 'normalized', 'position', [ posx posy width height ]);
%h = axes('unit', 'normalized', 'position', [ coordx/geom1 1-coordy/geom2-1/geom2 1/geom1 1/geom2 ]);
|
github
|
ZijingMao/baselineeegtest-master
|
warndlg2.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/guifunc/warndlg2.m
| 1,031 |
utf_8
|
4d58c147c6515911a93ba2375203951d
|
% warndlg2() - same as warndlg for eeglab()
%
% Author: Arnaud Delorme, CNL / Salk Institute, 12 August 2002
%
% See also: inputdlg2(), questdlg2()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function warndlg2(Prompt, Title);
if nargin <2
Title = 'Warning';
end;
questdlg2(Prompt, Title, 'OK', 'OK');
|
github
|
ZijingMao/baselineeegtest-master
|
pophelp.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/guifunc/pophelp.m
| 4,248 |
utf_8
|
bde4cd43c45ca121c2aa18c04083fe00
|
% pophelp() - Same as matlab HTHELP but does not crash under windows.
%
% Usage: >> pophelp( function );
% >> pophelp( function, nonmatlab );
%
% Inputs:
% function - string for a Matlab function name
% (with or without the '.m' extension).
% nonmatlab - [0|1], 1 the file is not a Matlab file
%
% Author: Arnaud Delorme, CNL / Salk Institute, 2001
%
% See also: eeglab()
% Copyright (C) 2001 Arnaud Delorme, Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function pophelp( funct, nonmatlab );
if nargin <1
help pophelp;
return;
end;
if nargin <2
nonmatlab = 0;
end;
if exist('help2html')
if length(funct) > 3 && strcmpi(funct(end-3:end), '.txt')
web(funct);
else
pathHelpHTML = fileparts(which('help2html'));
if ~isempty(findstr('NFT', pathHelpHTML)), rmpath(pathHelpHTML); end;
text1 = help2html(funct);
if length(funct) > 4 & strcmpi(funct(1:4), 'pop_')
try,
text2 = help2html(funct(5:end));
text1 = [text1 '<br><pre>___________________________________________________________________' 10 ...
' ' 10 ...
' The ''pop'' function above calls the eponymous Matlab function below' 10 ...
' and could use some of its optional parameters' 10 ...
'___________________________________________________________________</pre><br><br>' text2 ];
catch, end;
end;
web([ 'text://' text1 ]);
end;
else
if isempty(funct), return; end;
doc1 = readfunc(funct, nonmatlab);
if length(funct) > 4 & strcmpi(funct(1:4), 'pop_')
try,
doc2 = readfunc(funct(5:end), nonmatlab);
doc1 = { doc1{:} ' _________________________________________________________________ ' ...
' ' ...
' The ''pop'' function above calls the eponymous Matlab function below, ' ...
' which may contain more information for some parameters. '...
' ' ...
' _________________________________________________________________ ' ...
' ' ...
doc2{:} };
catch, end;
end;
textgui(doc1);1000
h = findobj('parent', gcf, 'style', 'slider');
try, icadefs; catch,
GUIBUTTONCOLOR = [0.8 0.8 0.8];
GUITEXTCOLOR = 'k';
end;
set(h, 'backgroundcolor', GUIBUTTONCOLOR);
h = findobj('parent', gcf, 'style', 'pushbutton');
set(h, 'backgroundcolor', GUIBUTTONCOLOR);
h = findobj('parent', gca);
set(h, 'color', GUITEXTCOLOR);
set(gcf, 'color', BACKCOLOR);
end;
return;
function [doc] = readfunc(funct, nonmatlab)
doc = {};
if iseeglabdeployed
if isempty(find(funct == '.')), funct = [ funct '.m' ]; end;
funct = fullfile(eeglabexefolder, 'help', funct);
end;
if nonmatlab
fid = fopen( funct, 'r');
else
if findstr( funct, '.m')
fid = fopen( funct, 'r');
else
fid = fopen( [funct '.m'], 'r');
end;
end;
if fid == -1
error('File not found');
end;
sub = 1;
try,
if ~isunix, sub = 0; end;
catch, end;
if nonmatlab
str = fgets( fid );
while ~feof(fid)
str = deblank(str(1:end-sub));
doc = { doc{:} str(1:end) };
str = fgets( fid );
end;
else
str = fgets( fid );
while (str(1) == '%')
str = deblank(str(1:end-sub));
doc = { doc{:} str(2:end) };
str = fgets( fid );
end;
end;
fclose(fid);
|
github
|
ZijingMao/baselineeegtest-master
|
errordlg2.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/guifunc/errordlg2.m
| 1,467 |
utf_8
|
710e811cd40d8f506b5264089f50c95c
|
% errordlg2() - Makes a popup dialog box with the specified message and (optional)
% title.
%
% Usage:
% errordlg2(Prompt, Title);
%
% Example:
% errordlg2('Explanation of error','title of error');
%
% Input:
% Prompt - A text string explaning why the user is seeing this error message.
% Title _ A text string that appears in the title bar of the error message.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 12 August 2002
%
% See also: inputdlg2(), questdlg2()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function errordlg2(Prompt, Title);
if exist('beep') == 5
beep;
else
disp(char(7));
end;
if nargin <2
Title = 'Error';
end;
if ~ismatlab, error(Prompt); end;
questdlg2(Prompt, Title, 'OK', 'OK');
|
github
|
ZijingMao/baselineeegtest-master
|
questdlg2.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/guifunc/questdlg2.m
| 3,133 |
utf_8
|
d94e219e87da50c5af28fe1007906abc
|
% questdlg2() - questdlg function clone with coloring and help for
% eeglab().
%
% Usage: same as questdlg()
%
% Warning:
% Case of button text and result might be changed by the function
%
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 11 August 2002
%
% See also: inputdlg2(), errordlg2(), supergui(), inputgui()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [result] = questdlg2(Prompt,Title,varargin);
result = '';
if nargin < 2
help questdlg2;
return;
end;
if isempty(varargin)
varargin = { 'Yes' 'No' 'Cancel' 'Yes' };
end;
result = varargin{end};
if Prompt(end) == 10, Prompt(end) = []; end;
if Prompt(end) == 10, Prompt(end) = []; end;
if Prompt(end) == 10, Prompt(end) = []; end;
if Prompt(end) == 10, Prompt(end) = []; end;
fig = figure('visible', 'off');
set(gcf, 'name', Title);
listui = {};
geometry = {};
if ~isempty(find(Prompt == 10))
indlines = find(Prompt == 10);
if indlines(1) ~= 1, indlines = [ 0 indlines ]; end;
if indlines(end) ~= length(Prompt), indlines = [ indlines length(Prompt)+1 ]; end;
for index = 1:length(indlines)-1
geometry{index} = [1];
listui{index} = { 'Style', 'text', 'string' Prompt(indlines(index)+1:indlines(index+1)-1) };
end;
else
for index = 1:size(Prompt,1)
geometry{index} = [1];
listui{index} = { 'Style', 'text', 'string' Prompt(index,:) };
end;
end;
listui{end+1} = {};
geometry = { geometry{:} 1 ones(1,length(varargin)-1) };
for index = 1:length(varargin)-1 % ignoring default val
listui = {listui{:} { 'width',80,'align','center','Style', 'pushbutton', 'string', varargin{index}, 'callback', ['set(gcbf, ''userdata'', ''' varargin{index} ''');'] } };
if strcmp(varargin{index}, varargin{end})
listui{end}{end+1} = 'fontweight';
listui{end}{end+1} = 'bold';
end;
end;
%cr = length(find(Prompt == char(10)))+1;
%if cr == 1
% cr = size(Prompt,1);
%end;
%cr = cr^(7/);
%if cr >= 8, cr = cr-1; end;
%if cr >= 4, cr = cr-1; end;
%[tmp tmp2 allobj] = supergui( 'fig', fig, 'geomhoriz', geometry, 'geomvert', [cr 1 1], 'uilist', listui, ...
[tmp tmp2 allobj] = supergui( 'fig', fig, 'geomhoriz', geometry, 'uilist', listui, ...
'borders', [0.02 0.015 0.08 0.06], 'spacing', [0 0], 'horizontalalignment', 'left', 'adjustbuttonwidth', 'on' );
waitfor( fig, 'userdata');
try,
result = get(fig, 'userdata');
close(fig);
drawnow;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
listdlg2.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/guifunc/listdlg2.m
| 3,771 |
utf_8
|
a0820fcb823bcb9968afa377c5582498
|
% listdlg2() - listdlg function clone with coloring and help for
% eeglab().
%
% Usage: same as listdlg()
%
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 16 August 2002
%
% See also: inputdlg2(), errordlg2(), supergui(), inputgui()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [vals, okornot, strval] = listdlg2(varargin);
if nargin < 2
help listdlg2;
return;
end;
for index = 1:length(varargin)
if iscell(varargin{index}), varargin{index} = { varargin{index} }; end;
if isstr(varargin{index}), varargin{index} = lower(varargin{index}); end;
end;
g = struct(varargin{:});
try, g.promptstring; catch, g.promptstring = ''; end;
try, g.liststring; catch, error('''liststring'' must be defined'); end;
try, g.selectionmode; catch, g.selectionmode = 'multiple'; end;
try, g.listsize; catch, g.listsize = []; end;
try, g.initialvalue; catch, g.initialvalue = []; end;
try, g.name; catch, g.name = ''; end;
fig = figure('visible', 'off');
set(gcf, 'name', g.name);
if isstr(g.liststring)
allstr = g.liststring;
else
allstr = '';
for index = 1:length(g.liststring)
allstr = [ allstr '|' g.liststring{index} ];
end;
allstr = allstr(2:end);
end;
geometry = {[1] [1 1]};
geomvert = [min(length(g.liststring), 10) 1];
if ~strcmpi(g.selectionmode, 'multiple') | ...
(iscell(g.liststring) & length(g.liststring) == 1) | ...
(isstr (g.liststring) & size (g.liststring,1) == 1 & isempty(find(g.liststring == '|')))
if isempty(g.initialvalue), g.initialvalue = 1; end;
minval = 1;
maxval = 1;
else
minval = 0;
maxval = 2;
end;
listui = {{ 'Style', 'listbox', 'tag', 'listboxvals', 'string', allstr, 'max', maxval, 'min', minval } ...
{ 'Style', 'pushbutton', 'string', 'Cancel', 'callback', ['set(gcbf, ''userdata'', ''cancel'');'] } ...
{ 'Style', 'pushbutton', 'string', 'Ok' , 'callback', ['set(gcbf, ''userdata'', ''ok'');'] } };
if ~isempty(g.promptstring)
geometry = {[1] geometry{:}};
geomvert = [1 geomvert];
listui = { { 'Style', 'text', 'string', g.promptstring } listui{:}};
end;
[tmp tmp2 allobj] = supergui( fig, geometry, geomvert, listui{:} );
% assign value to listbox
% must be done after creating it
% ------------------------------
lstbox = findobj(fig, 'tag', 'listboxvals');
set(lstbox, 'value', g.initialvalue);
if ~isempty(g.listsize)
pos = get(gcf, 'position');
set(gcf, 'position', [ pos(1:2) g.listsize]);
end;
h = findobj( 'parent', fig, 'tag', 'listboxvals');
okornot = 0;
strval = '';
vals = [];
figure(fig);
drawnow;
waitfor( fig, 'userdata');
try,
vals = get(h, 'value');
strval = '';
if iscell(g.liststring)
for index = vals
strval = [ strval ' ' g.liststring{index} ];
end;
else
for index = vals
strval = [ strval ' ' g.liststring(index,:) ];
end;
end;
strval = strval(2:end);
if strcmp(get(fig, 'userdata'), 'cancel')
okornot = 0;
else
okornot = 1;
end;
close(fig);
drawnow;
end;
|
github
|
ZijingMao/baselineeegtest-master
|
finputcheck.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/guifunc/finputcheck.m
| 9,133 |
utf_8
|
fe838fecdd60e76a4006a13c7c1b20e4
|
% finputcheck() - check Matlab function {'key','value'} input argument pairs
%
% Usage: >> result = finputcheck( varargin, fieldlist );
% >> [result varargin] = finputcheck( varargin, fieldlist, ...
% callingfunc, mode, verbose );
% Input:
% varargin - Cell array 'varargin' argument from a function call using 'key',
% 'value' argument pairs. See Matlab function 'varargin'.
% May also be a structure such as struct(varargin{:})
% fieldlist - A 4-column cell array, one row per 'key'. The first
% column contains the key string, the second its type(s),
% the third the accepted value range, and the fourth the
% default value. Allowed types are 'boolean', 'integer',
% 'real', 'string', 'cell' or 'struct'. For example,
% {'key1' 'string' { 'string1' 'string2' } 'defaultval_key1'}
% {'key2' {'real' 'integer'} { minint maxint } 'defaultval_key2'}
% callingfunc - Calling function name for error messages. {default: none}.
% mode - ['ignore'|'error'] ignore keywords that are either not specified
% in the fieldlist cell array or generate an error.
% {default: 'error'}.
% verbose - ['verbose', 'quiet'] print information. Default: 'verbose'.
%
% Outputs:
% result - If no error, structure with 'key' as fields and 'value' as
% content. If error this output contain the string error.
% varargin - residual varagin containing unrecognized input arguments.
% Requires mode 'ignore' above.
%
% Note: In case of error, a string is returned containing the error message
% instead of a structure.
%
% Example (insert the following at the beginning of your function):
% result = finputcheck(varargin, ...
% { 'title' 'string' [] ''; ...
% 'percent' 'real' [0 1] 1 ; ...
% 'elecamp' 'integer' [1:10] [] });
% if isstr(result)
% error(result);
% end
%
% Note:
% The 'title' argument should be a string. {no default value}
% The 'percent' argument should be a real number between 0 and 1. {default: 1}
% The 'elecamp' argument should be an integer between 1 and 10 (inclusive).
%
% Now 'g.title' will contain the title arg (if any, else the default ''), etc.
%
% Author: Arnaud Delorme, CNL / Salk Institute, 10 July 2002
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, 10 July 2002, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [g, varargnew] = finputcheck( vararg, fieldlist, callfunc, mode, verbose )
if nargin < 2
help finputcheck;
return;
end;
if nargin < 3
callfunc = '';
else
callfunc = [callfunc ' ' ];
end;
if nargin < 4
mode = 'do not ignore';
end;
if nargin < 5
verbose = 'verbose';
end;
NAME = 1;
TYPE = 2;
VALS = 3;
DEF = 4;
SIZE = 5;
varargnew = {};
% create structure
% ----------------
if ~isempty(vararg)
if isstruct(vararg)
g = vararg;
else
for index=1:length(vararg)
if iscell(vararg{index})
vararg{index} = {vararg{index}};
end;
end;
try
g = struct(vararg{:});
catch
vararg = removedup(vararg, verbose);
try
g = struct(vararg{:});
catch
g = [ callfunc 'error: bad ''key'', ''val'' sequence' ]; return;
end;
end;
end;
else
g = [];
end;
for index = 1:size(fieldlist,NAME)
% check if present
% ----------------
if ~isfield(g, fieldlist{index, NAME})
g = setfield( g, fieldlist{index, NAME}, fieldlist{index, DEF});
end;
tmpval = getfield( g, {1}, fieldlist{index, NAME});
% check type
% ----------
if ~iscell( fieldlist{index, TYPE} )
res = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}, ...
fieldlist{index, VALS}, tmpval, callfunc );
if isstr(res), g = res; return; end;
else
testres = 0;
tmplist = fieldlist;
for it = 1:length( fieldlist{index, TYPE} )
if ~iscell(fieldlist{index, VALS})
res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ...
fieldlist{index, VALS}, tmpval, callfunc );
else res{it} = fieldtest( fieldlist{index, NAME}, fieldlist{index, TYPE}{it}, ...
fieldlist{index, VALS}{it}, tmpval, callfunc );
end;
if ~isstr(res{it}), testres = 1; end;
end;
if testres == 0,
g = res{1};
for tmpi = 2:length(res)
g = [ g 10 'or ' res{tmpi} ];
end;
return;
end;
end;
end;
% check if fields are defined
% ---------------------------
allfields = fieldnames(g);
for index=1:length(allfields)
if isempty(strmatch(allfields{index}, fieldlist(:, 1)', 'exact'))
if ~strcmpi(mode, 'ignore')
g = [ callfunc 'error: undefined argument ''' allfields{index} '''']; return;
end;
varargnew{end+1} = allfields{index};
varargnew{end+1} = getfield(g, {1}, allfields{index});
end;
end;
function g = fieldtest( fieldname, fieldtype, fieldval, tmpval, callfunc );
NAME = 1;
TYPE = 2;
VALS = 3;
DEF = 4;
SIZE = 5;
g = [];
switch fieldtype
case { 'integer' 'real' 'boolean' 'float' },
if ~isnumeric(tmpval) && ~islogical(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be numeric' ]; return;
end;
if strcmpi(fieldtype, 'boolean')
if tmpval ~=0 && tmpval ~= 1
g = [ callfunc 'error: argument ''' fieldname ''' must be 0 or 1' ]; return;
end;
else
if strcmpi(fieldtype, 'integer')
if ~isempty(fieldval)
if (any(isnan(tmpval(:))) && ~any(isnan(fieldval))) ...
&& (~ismember(tmpval, fieldval))
g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return;
end;
end;
else % real or float
if ~isempty(fieldval) && ~isempty(tmpval)
if any(tmpval < fieldval(1)) || any(tmpval > fieldval(2))
g = [ callfunc 'error: value out of range for argument ''' fieldname '''' ]; return;
end;
end;
end;
end;
case 'string'
if ~isstr(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be a string' ]; return;
end;
if ~isempty(fieldval)
if isempty(strmatch(lower(tmpval), lower(fieldval), 'exact'))
g = [ callfunc 'error: wrong value for argument ''' fieldname '''' ]; return;
end;
end;
case 'cell'
if ~iscell(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be a cell array' ]; return;
end;
case 'struct'
if ~isstruct(tmpval)
g = [ callfunc 'error: argument ''' fieldname ''' must be a structure' ]; return;
end;
case 'function_handle'
if ~isa(tmpval, 'function_handle')
g = [ callfunc 'error: argument ''' fieldname ''' must be a function handle' ]; return;
end;
case '';
otherwise, error([ 'finputcheck error: unrecognized type ''' fieldname '''' ]);
end;
% remove duplicates in the list of parameters
% -------------------------------------------
function cella = removedup(cella, verbose)
% make sure if all the values passed to unique() are strings, if not, exist
%try
[tmp indices] = unique_bc(cella(1:2:end));
if length(tmp) ~= length(cella)/2
myfprintf(verbose,'Note: duplicate ''key'', ''val'' parameter(s), keeping the last one(s)\n');
end;
cella = cella(sort(union(indices*2-1, indices*2)));
%catch
% some elements of cella were not string
% error('some ''key'' values are not string.');
%end;
function myfprintf(verbose, varargin)
if strcmpi(verbose, 'verbose')
fprintf(varargin{:});
end;
|
github
|
ZijingMao/baselineeegtest-master
|
inputdlg2.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/guifunc/inputdlg2.m
| 2,497 |
utf_8
|
f37d94d5821140270d3242f0d5d06659
|
% inputdlg2() - inputdlg function clone with coloring and help for
% eeglab().
%
% Usage:
% >> Answer = inputdlg2(Prompt,Title,LineNo,DefAns,funcname);
%
% Inputs:
% Same as inputdlg. Using the optional additionnal funcname parameter
% the function will create a help button. The help message will be
% displayed using the pophelp() function.
%
% Output:
% Same as inputdlg
%
% Note: The advantage of this function is that the color of the window
% can be changed and that it displays an help button. Edit
% supergui to change window options. Also the parameter LineNo
% can only be one.
%
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 11 August 2002
%
% See also: supergui(), inputgui()
% Copyright (C) Arnaud Delorme, CNL / Salk Institute, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [result] = inputdlg2(Prompt,Title,LineNo,DefAns,funcname);
if nargin < 4
help inputdlg2;
return;
end;
if nargin < 5
funcname = '';
end;
if length(Prompt) ~= length(DefAns)
error('inputdlg2: prompt and default answer cell array must have the smae size');
end;
geometry = {};
listgui = {};
% determine if vertical or horizontal
% -----------------------------------
geomvert = [];
for index = 1:length(Prompt)
geomvert = [geomvert size(Prompt{index},1) 1]; % default is vertical geometry
end;
if all(geomvert == 1) & length(Prompt) > 1
geomvert = []; % horizontal
end;
for index = 1:length(Prompt)
if ~isempty(geomvert) % vertical
geometry = { geometry{:} [ 1] [1 ]};
else
geometry = { geometry{:} [ 1 0.6 ]};
end;
listgui = { listgui{:} { 'Style', 'text', 'string', Prompt{index}} ...
{ 'Style', 'edit', 'string', DefAns{index} } };
end;
result = inputgui(geometry, listgui, ['pophelp(''' funcname ''');'], Title, [], 'normal', geomvert);
|
github
|
ZijingMao/baselineeegtest-master
|
inputgui.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/functions/guifunc/inputgui.m
| 12,643 |
utf_8
|
87e7498822cdcf7eb92a71cb46360f83
|
% inputgui() - A comprehensive gui automatic builder. This function helps
% to create GUI very quickly without bothering about the
% positions of the elements. After creating a geometry,
% elements just place themselves in the predefined
% locations. It is especially useful for figures in which
% you intend to put text buttons and descriptions.
%
% Usage:
% >> [ outparam ] = inputgui( 'key1', 'val1', 'key2', 'val2', ... );
% >> [ outparam userdat strhalt outstruct] = ...
% inputgui( 'key1', 'val1', 'key2', 'val2', ... );
%
% Inputs:
% 'geom' - cell array of cell array of integer vector. Each cell
% array defines the coordinate of a given input in the
% following manner: { nb_row nb_col [x_topcorner y_topcorner]
% [x_bottomcorner y_bottomcorner] };
% 'geometry' - cell array describing horizontal geometry. This corresponds
% to the supergui function input 'geomhoriz'
% 'geomvert' - vertical geometry argument, this argument is passed on to
% the supergui function
% 'uilist' - list of uicontrol lists describing elements properties
% { { ui1 }, { ui2 }... }, { 'uiX' } being GUI matlab
% uicontrol arguments such as { 'style', 'radiobutton',
% 'String', 'hello' }. See Matlab function uicontrol() for details.
% 'helpcom' - optional help command
% 'helpbut' - text for help button
% 'title' - optional figure title
% 'userdata' - optional userdata input for the figure
% 'mode' - ['normal'|'noclose'|'plot' fignumber]. Either wait for
% user to press OK or CANCEL ('normal'), return without
% closing window input ('noclose'), only draw the gui ('plot')
% or process an existing window which number is given as
% input (fignumber). Default is 'normal'.
% 'eval' - [string] command to evaluate at the end of the creation
% of the GUI but before waiting for user input.
% 'screenpos' - see supergui.m help message.
% 'skipline' - ['on'|'off'] skip a row before the "OK" and "Cancel"
% button. Default is 'on'.
%
% Output:
% outparam - list of outputs. The function scans all lines and
% add up an output for each interactive uicontrol, i.e
% edit box, radio button, checkbox and listbox.
% userdat - 'userdata' value of the figure.
% strhalt - the function returns when the 'userdata' field of the
% button with the tag 'ok' is modified. This returns the
% new value of this field.
% outstruct - returns outputs as a structure (only tagged ui controls
% are considered). The field name of the structure is
% the tag of the ui and contain the ui value or string.
%
% Note: the function also adds three buttons at the bottom of each
% interactive windows: 'CANCEL', 'HELP' (if callback command
% is provided) and 'OK'.
%
% Example:
% res = inputgui('geometry', { 1 1 }, 'uilist', ...
% { { 'style' 'text' 'string' 'Enter a value' } ...
% { 'style' 'edit' 'string' '' } });
%
% res = inputgui('geom', { {2 1 [0 0] [1 1]} {2 1 [1 0] [1 1]} }, 'uilist', ...
% { { 'style' 'text' 'string' 'Enter a value' } ...
% { 'style' 'edit' 'string' '' } });
%
% Author: Arnaud Delorme, CNL / Salk Institute, La Jolla, 1 Feb 2002
%
% See also: supergui(), eeglab()
% Copyright (C) Arnaud Delorme, CNL/Salk Institute, 27 Jan 2002, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [result, userdat, strhalt, resstruct] = inputgui( varargin);
if nargin < 2
help inputgui;
return;
end;
% decoding input and backward compatibility
% -----------------------------------------
if isstr(varargin{1})
options = varargin;
else
options = { 'geometry' 'uilist' 'helpcom' 'title' 'userdata' 'mode' 'geomvert' };
options = { options{1:length(varargin)}; varargin{:} };
options = options(:)';
end;
% checking inputs
% ---------------
g = finputcheck(options, { 'geom' 'cell' [] {}; ...
'geometry' {'cell','integer'} [] []; ...
'uilist' 'cell' [] {}; ...
'helpcom' { 'string','cell' } { [] [] } ''; ...
'title' 'string' [] ''; ...
'eval' 'string' [] ''; ...
'helpbut' 'string' [] 'Help'; ...
'skipline' 'string' { 'on' 'off' } 'on'; ...
'addbuttons' 'string' { 'on' 'off' } 'on'; ...
'userdata' '' [] []; ...
'getresult' 'real' [] []; ...
'minwidth' 'real' [] 200; ...
'screenpos' '' [] []; ...
'mode' '' [] 'normal'; ...
'geomvert' 'real' [] [] ...
}, 'inputgui');
if isstr(g), error(g); end;
if isempty(g.getresult)
if isstr(g.mode)
fig = figure('visible', 'off');
set(fig, 'name', g.title);
set(fig, 'userdata', g.userdata);
if ~iscell( g.geometry )
oldgeom = g.geometry;
g.geometry = {};
for row = 1:length(oldgeom)
g.geometry = { g.geometry{:} ones(1, oldgeom(row)) };
end;
end
% skip a line
if strcmpi(g.skipline, 'on'),
g.geometry = { g.geometry{:} [1] };
if ~isempty(g.geom)
for ind = 1:length(g.geom)
g.geom{ind}{2} = g.geom{ind}{2}+1; % add one row
end;
g.geom = { g.geom{:} {1 g.geom{1}{2} [0 g.geom{1}{2}-2] [1 1] } };
end;
g.uilist = { g.uilist{:}, {} };
end;
% add buttons
if strcmpi(g.addbuttons, 'on'),
g.geometry = { g.geometry{:} [1 1 1 1] };
if ~isempty(g.geom)
for ind = 1:length(g.geom)
g.geom{ind}{2} = g.geom{ind}{2}+1; % add one row
end;
g.geom = { g.geom{:} ...
{4 g.geom{1}{2} [0 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [1 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [2 g.geom{1}{2}-1] [1 1] }, ...
{4 g.geom{1}{2} [3 g.geom{1}{2}-1] [1 1] } };
end;
if ~isempty(g.helpcom)
if ~iscell(g.helpcom)
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', g.helpbut, 'tag', 'help', 'callback', g.helpcom } {} };
else
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', 'Help gui', 'callback', g.helpcom{1} } };
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'left' 'Style', 'pushbutton', 'string', 'More help', 'callback', g.helpcom{2} } };
end;
else
g.uilist = { g.uilist{:}, {} {} };
end;
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'Style', 'pushbutton', 'string', 'Cancel', 'tag' 'cancel' 'callback', 'close gcbf' } };
g.uilist = { g.uilist{:}, { 'width' 80 'align' 'right' 'stickto' 'on' 'Style', 'pushbutton', 'tag', 'ok', 'string', 'OK', 'callback', 'set(gcbo, ''userdata'', ''retuninginputui'');' } };
end;
% add the three buttons (CANCEL HELP OK) at the bottom of the GUI
% ---------------------------------------------------------------
if ~isempty(g.geom)
[tmp tmp2 allobj] = supergui( 'fig', fig, 'minwidth', g.minwidth, 'geom', g.geom, 'uilist', g.uilist, 'screenpos', g.screenpos );
elseif isempty(g.geomvert)
[tmp tmp2 allobj] = supergui( 'fig', fig, 'minwidth', g.minwidth, 'geomhoriz', g.geometry, 'uilist', g.uilist, 'screenpos', g.screenpos );
else
if strcmpi(g.skipline, 'on'), g.geomvert = [g.geomvert(:)' 1]; end;
if strcmpi(g.addbuttons, 'on'),g.geomvert = [g.geomvert(:)' 1]; end;
[tmp tmp2 allobj] = supergui( 'fig', fig, 'minwidth', g.minwidth, 'geomhoriz', g.geometry, 'uilist', g.uilist, 'screenpos', g.screenpos, 'geomvert', g.geomvert(:)' );
end;
else
fig = g.mode;
set(findobj('parent', fig, 'tag', 'ok'), 'userdata', []);
allobj = findobj('parent',fig);
allobj = allobj(end:-1:1);
end;
% evaluate command before waiting?
% --------------------------------
if ~isempty(g.eval), eval(g.eval); end;
% create figure and wait for return
% ---------------------------------
if isstr(g.mode) & (strcmpi(g.mode, 'plot') | strcmpi(g.mode, 'return') )
if strcmpi(g.mode, 'plot')
return; % only plot and returns
end;
else
waitfor( findobj('parent', fig, 'tag', 'ok'), 'userdata');
end;
else
fig = g.getresult;
allobj = findobj('parent',fig);
allobj = allobj(end:-1:1);
end;
result = {};
userdat = [];
strhalt = '';
resstruct = [];
% Check if figure still exist (RMC) % try, findobj(fig);catch, return; end;
if ~(ishandle(fig))
return;
end
strhalt = get(findobj('parent', fig, 'tag', 'ok'), 'userdata');
% output parameters
% -----------------
counter = 1;
resstruct = [];
for index=1:length(allobj)
if isnumeric(allobj), currentobj = allobj(index);
else currentobj = allobj{index};
end;
if isnumeric(currentobj) | ~isprop(currentobj,'GetPropertySpecification') % To allow new object handles
try,
objstyle = get(currentobj, 'style');
switch lower( objstyle )
case { 'listbox', 'checkbox', 'radiobutton' 'popupmenu' 'radio' }
result{counter} = get( currentobj, 'value');
if ~isempty(get(currentobj, 'tag')), resstruct = setfield(resstruct, get(currentobj, 'tag'), result{counter}); end;
counter = counter+1;
case 'edit'
result{counter} = get( currentobj, 'string');
if ~isempty(get(currentobj, 'tag')), resstruct = setfield(resstruct, get(currentobj, 'tag'), result{counter}); end;
counter = counter+1;
end;
catch, end;
else
ps = currentobj.GetPropertySpecification;
result{counter} = arg_tovals(ps,false);
count = 1;
while isfield(resstruct, ['propgrid' int2str(count)])
count = count + 1;
end;
resstruct = setfield(resstruct, ['propgrid' int2str(count)], arg_tovals(ps,false));
end;
end;
userdat = get(fig, 'userdata');
% if nargout >= 4
% resstruct = myguihandles(fig, g);
% end;
if isempty(g.getresult) && isstr(g.mode) && ( strcmp(g.mode, 'normal') || strcmp(g.mode, 'return') )
close(fig);
end;
drawnow; % for windows
% function for gui res (deprecated)
% --------------------
% function g = myguihandles(fig, g)
% h = findobj('parent', fig);
% if ~isempty(get(h(index), 'tag'))
% try,
% switch get(h(index), 'style')
% case 'edit', g = setfield(g, get(h(index), 'tag'), get(h(index), 'string'));
% case { 'value' 'radio' 'checkbox' 'listbox' 'popupmenu' 'radiobutton' }, ...
% g = setfield(g, get(h(index), 'tag'), get(h(index), 'value'));
% end;
% catch, end;
% end;
|
github
|
ZijingMao/baselineeegtest-master
|
load_xdf.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/xdfimport1.12/load_xdf.m
| 36,394 |
utf_8
|
6f21f06210e2a00582be9587293550f9
|
function [streams,fileheader] = load_xdf(filename,varargin)
% Import an XDF file.
% [Streams,FileHeader] = load_xdf(Filename, Options...)
%
% This is a MATLAB importer for mult-stream XDF (Extensible Data Format) recordings. All
% information covered by the XDF 1.0 specification is imported, plus any additional meta-data
% associated with streams or with the container file itself.
%
% See http://code.google.com/p/xdf/ for more information on XDF.
%
% The function supports several further features, such as compressed XDF archives, robust
% time synchronization, support for breaks in the data, as well as some other defects.
%
% In:
% Filename : name of the file to import (*.xdf or *.xdfz)
%
% Options... : A list of optional name-value arguments for special use cases. The allowed names
% are listed in the following:
%
% Parameters that control various processing features:
%
% 'Verbose' : Whether to print verbose diagnostics. (default: false)
%
% 'HandleClockSynchronization' : Whether to enable clock synchronization based on
% ClockOffset chunks. (default: true)
%
% 'HandleJitterRemoval' : Whether to perform jitter removal for regularly sampled
% streams. (default: true)
%
% 'OnChunk' : Function that is called for each chunk of data as it
% is being retrieved from the file; the function is allowed to modify the
% data (for example, sub-sample it). The four input arguments are 1) the
% matrix of [#channels x #samples] values (either numeric or 2d cell
% array of strings), 2) the vector of unprocessed local time stamps (one
% per sample), 3) the info struct for the stream (same as the .info field
% in the final output, buth without the .effective_srate sub-field), and
% 4) the scalar stream number (1-based integers). The three return values
% are 1) the (optionally modified) data, 2) the (optionally modified)
% time stamps, and 3) the (optionally modified) header (default: []).
%
% Parameters for advanced failure recovery in clock synchronization:
%
% 'HandleClockResets' : Whether the importer should check for potential resets of the
% clock of a stream (e.g. computer restart during recording, or
% hot-swap). Only useful if the recording system supports
% recording under such circumstances. (default: true)
%
% 'ClockResetThresholdStds' : A clock reset must be accompanied by a ClockOffset
% chunk being delayed by at least this many standard
% deviations from the distribution. (default: 5)
%
% 'ClockResetThresholdSeconds' : A clock reset must be accompanied by a ClockOffset
% chunk being delayed by at least this many seconds.
% (default: 5)
%
% 'ClockResetThresholdOffsetStds' : A clock reset must be accompanied by a
% ClockOffset difference that lies at least this many
% standard deviations from the distribution. (default: 10)
%
% 'ClockResetThresholdOffsetSeconds' : A clock reset must be accompanied by a
% ClockOffset difference that is at least this
% many seconds away from the median. (default: 1)
%
% 'ClockResetMaxJitter' : Maximum tolerable jitter (in seconds of error) for clock
% reset handling. (default: 5)
%
% Parameters for jitter removal in the presence of data breaks:
%
% 'JitterBreakThresholdSeconds' : An interruption in a regularly-sampled stream of at least this
% many seconds will be considered as a potential break (if also
% the BreakThresholdSamples is crossed) and multiple segments
% will be returned. Default: 1
%
% 'JitterBreakThresholdSamples' : An interruption in a regularly-sampled stream of at least this
% many samples will be considered as a potential break (if also
% the BreakThresholdSeconds is crossed) and multiple segments
% will be returned. Default: 500
%
% Out:
% Streams : cell array of structs, one for each stream; the structs have the following content:
% .time_series field: contains the stream's time series [#Channels x #Samples]
% this matrix is of the type declared in .info.channel_format
% .time_stamps field: contains the time stamps for each sample (synced across streams)
%
% .info field: contains the meta-data of the stream (all values are strings)
% .name: name of the stream
% .type: content-type of the stream ('EEG','Events', ...)
% .channel_format: value format ('int8','int16','int32','int64','float32','double64','string')
% .nominal_srate: nominal sampling rate of the stream (as declared by the device);
% zero for streams with irregular sampling rate
% .effective_srate: effective (measured) sampling rate of the stream, if regular
% (otherwise omitted)
% .desc: struct with any domain-specific meta-data declared for the stream; see
% www.xdf.org for the declared specifications
%
% .segments field: struct array containing segment ranges for regularly sampled
% time series with breaks (not present if the stream is irregular)
% .index_range: 1st and last index of the segment within the .time_series/.time_stamps
% arrays
% .t_begin: time of the 1st sample in the segment, in seconds
% .t_end: time of the last sample in the segment, in seconds
% .duration: duration of the segment, in seconds
% .num_samples: number of samples in the segment
% .effective_srate: effective (i.e. measured) sampling rate within the segment
%
% FileHeader : struct with file header contents in the .info field
%
% Examples:
% % load the streams contained in a given XDF file
% streams = load_xdf('C:\Recordings\myrecording.xdf')
%
% License:
% This file is covered by the BSD license.
%
% Copyright (c) 2012, Christian Kothe
% Portions Copyright (c) 2010, Wouter Falkena
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are
% met:
%
% * Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
% * Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in
% the documentation and/or other materials provided with the distribution
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
% CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
% SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
% CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
% ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
% POSSIBILITY OF SUCH DAMAGE.
%
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2012-04-22
%
% Contains portions of xml2struct Copyright (c) 2010, Wouter Falkena,
% ASTI, TUDelft, 21-08-2010
%
% version 1.12
% check inputs
opts = cell2struct(varargin(2:2:end),varargin(1:2:end),2);
if ~isfield(opts,'OnChunk')
opts.OnChunk = []; end
if ~isfield(opts,'Verbose')
opts.Verbose = false; end
if ~isfield(opts,'HandleClockSynchronization')
opts.HandleClockSynchronization = true; end
if ~isfield(opts,'HandleClockResets')
opts.HandleClockResets = true; end
if ~isfield(opts,'HandleJitterRemoval')
opts.HandleJitterRemoval = true; end
if ~isfield(opts,'JitterBreakThresholdSeconds')
opts.JitterBreakThresholdSeconds = 1; end
if ~isfield(opts,'JitterBreakThresholdSamples')
opts.JitterBreakThresholdSamples = 500; end
if ~isfield(opts,'ClockResetThresholdSeconds')
opts.ClockResetThresholdSeconds = 5; end
if ~isfield(opts,'ClockResetThresholdStds')
opts.ClockResetThresholdStds = 5; end
if ~isfield(opts,'ClockResetThresholdOffsetSeconds')
opts.ClockResetThresholdOffsetSeconds = 1; end
if ~isfield(opts,'ClockResetThresholdOffsetStds')
opts.ClockResetThresholdOffsetStds = 10; end
if ~isfield(opts,'WinsorThreshold')
opts.WinsorThreshold = 0.0001; end
if ~isfield(opts,'ClockResetMaxJitter')
opts.ClockResetMaxJitter = 5; end
if ~exist(filename,'file')
error(['The file "' filename '" does not exist.']); end
if opts.Verbose
disp(['Importing XDF file ' filename '...']); end
% uncompress if necessary (note: "bonus" feature, not part of the XDF 1.0 spec)
[p,n,x] = fileparts(filename);
if strcmp(x,'.xdfz')
% idea for this type of approach by Michael Kleder
import com.mathworks.mlwidgets.io.InterruptibleStreamCopier
src = java.io.FileInputStream(filename);
flt = java.util.zip.InflaterInputStream(src);
filename = [p filesep n '_temp_uncompressed' x];
dst = java.io.FileOutputStream(filename);
copier = InterruptibleStreamCopier.getInterruptibleStreamCopier;
copier.copyStream(flt,dst);
dst.close();
src.close();
end
streams = {}; % cell array of returned streams (in the order of appearance in the file)
idmap = sparse(2^31-1,1); % remaps stream id's onto indices in streams
temp = struct(); % struct array of temporary per-stream information
fileheader = struct(); % the file header
f = fopen(filename,'r','ieee-le.l64'); % file handle
closer = onCleanup(@()close_file(f,filename)); % object that closes the file when the function exits
% there is a fast C mex file for the inner loop, but it's
% not necessarily available for every platform
have_mex = exist('load_xdf_innerloop','file');
if ~have_mex
disp('NOTE: apparently you are missing a compiled binary version of the inner loop code. Using the slow MATLAB code instead.'); end
% ======================
% === parse the file ===
% ======================
% read [MagicCode]
if ~strcmp(fread(f,4,'*char')','XDF:')
error(['This is not a valid XDF file (' filename ').']); end
% for each chunk...
while 1
% read [NumLengthBytes], [Length]
len = double(read_varlen_int(f));
if ~len
break; end
% read [Tag]
switch fread(f,1,'uint16')
case 3 % read [Samples] chunk
try
% read [StreamId]
id = idmap(fread(f,1,'uint32'));
if have_mex
% read the chunk data at once
data = fread(f,len-6,'*uint8');
% run the mex kernel
[values,timestamps] = load_xdf_innerloop(data, temp(id).chns, temp(id).readfmt, temp(id).sampling_interval, temp(id).last_timestamp);
temp(id).last_timestamp = timestamps(end);
else % fallback MATLAB implementation
% read [NumSampleBytes], [NumSamples]
num = read_varlen_int(f);
% allocate space
timestamps = zeros(1,num);
if strcmp(temp(id).readfmt,'*string')
values = cell(temp(id).chns,num);
else
values = zeros(temp(id).chns,num);
end
% for each sample...
for s=1:num
% read or deduce time stamp
if fread(f,1,'*uint8')
timestamps(s) = fread(f,1,'double');
else
timestamps(s) = temp(id).last_timestamp + temp(id).sampling_interval;
end
% read the values
if strcmp(temp(id).readfmt,'*string')
for v = 1:size(values,1)
values{v,s} = fread(f,double(read_varlen_int(f)),'*char')'; end
else
values(:,s) = fread(f,size(values,1),temp(id).readfmt);
end
temp(id).last_timestamp = timestamps(s);
end
end
% optionally send through the OnChunk function
if ~isempty(opts.OnChunk)
[values,timestamps,streams{id}] = opts.OnChunk(values,timestamps,streams{id},id); end %#ok<*AGROW>
% append to the time series...
temp(id).time_series{end+1} = values;
temp(id).time_stamps{end+1} = timestamps;
catch e
% an error occurred (perhaps a chopped-off file): emit a warning
% and return the file up to this point
warning(e.identifier,e.message);
break;
end
case 2 % read [StreamHeader] chunk
% read [StreamId]
streamid = fread(f,1,'uint32');
id = length(streams)+1;
idmap(streamid) = id; %#ok<SPRIX>
% read [Content]
header = parse_xml_struct(fread(f,len-6,'*char')');
streams{id} = header;
if opts.Verbose
fprintf([' found stream ' header.info.name '\n']); end
% generate a few temporary fields
temp(id).chns = str2num(header.info.channel_count); %#ok<*ST2NM>
temp(id).srate = str2num(header.info.nominal_srate);
temp(id).last_timestamp = 0;
temp(id).time_series = {};
temp(id).time_stamps = {};
temp(id).clock_times = [];
temp(id).clock_values = [];
if temp(id).srate > 0
temp(id).sampling_interval = 1/temp(id).srate;
else
temp(id).sampling_interval = 0;
end
% fread parsing format for data values
temp(id).readfmt = ['*' header.info.channel_format];
if strcmp(temp(id).readfmt,'*double64') && ~have_mex
temp(id).readfmt = '*double'; end % for fread()
case 6 % read [StreamFooter] chunk
% read [StreamId]
id = idmap(fread(f,1,'uint32'));
% read [Content]
footer = parse_xml_struct(fread(f,len-6,'*char')');
streams{id} = hlp_superimposedata(footer,streams{id});
case 1 % read [FileHeader] chunk
fileheader = parse_xml_struct(fread(f,len-2,'*char')');
case 4 % read [ClockOffset] chunk
% read [StreamId]
id = idmap(fread(f,1,'uint32'));
% read [CollectionTime]
temp(id).clock_times(end+1) = fread(f,1,'double');
% read [OffsetValue]
temp(id).clock_values(end+1) = fread(f,1,'double');
otherwise
% skip other chunk types (Boundary, ...)
fread(f,len-2,'*uint8');
end
end
% concatenate the signal across chunks
for k=1:length(temp)
try
temp(k).time_series = [temp(k).time_series{:}];
temp(k).time_stamps = [temp(k).time_stamps{:}];
catch e
disp(['Could not concatenate time series for stream ' streams{k}.info.name '; skipping.']);
disp(['Reason: ' e.message]);
temp(k).time_series = [];
temp(k).time_stamps = [];
end
end
% ===================================================================
% === perform (fault-tolerant) clock synchronization if requested ===
% ===================================================================
if opts.HandleClockSynchronization
if opts.Verbose
disp(' performing clock synchronization...'); end
for k=1:length(temp)
if ~isempty(temp(k).time_stamps)
try
clock_times = temp(k).clock_times;
clock_values = temp(k).clock_values;
catch
disp(['No clock offsets were available for stream "' streams{k}.info.name '"']);
continue;
end
% detect clock resets (e.g., computer restarts during recording) if requested
% this is only for cases where "everything goes wrong" during recording
% note that this is a fancy feature that is not needed for normal XDF compliance
if opts.HandleClockResets
% first detect potential breaks in the synchronization data; this is only necessary when the
% importer should be able to deal with recordings where the computer that served a stream
% was restarted or hot-swapped during an ongoing recording, or the clock was reset otherwise
time_diff = diff(clock_times);
value_diff = abs(diff(clock_values));
% points where a glitch in the timing of successive clock measurements happened
time_glitch = (time_diff < 0 | (((time_diff - median(time_diff)) ./ mad(time_diff,1)) > opts.ClockResetThresholdStds & ...
((time_diff - median(time_diff)) > opts.ClockResetThresholdSeconds)));
% points where a glitch in successive clock value estimates happened
value_glitch = (value_diff - median(value_diff)) ./ mad(value_diff,1) > opts.ClockResetThresholdOffsetStds & ...
(value_diff - median(value_diff)) > opts.ClockResetThresholdOffsetSeconds;
% points where both a time glitch and a value glitch co-occur are treated as resets
resets_at = time_glitch & value_glitch;
% determine the [begin,end] index ranges between resets
if any(resets_at)
tmp = find(resets_at)';
tmp = [tmp tmp+1]';
tmp = [1 tmp(:)' length(resets_at)];
ranges = num2cell(reshape(tmp,2,[])',2);
if opts.Verbose
disp([' found ' num2str(nnz(resets_at)) ' clock resets in stream ' streams{k}.info.name '.']); end
else
ranges = {[1,length(clock_times)]};
end
else
% otherwise we just assume that there are no clock resets
ranges = {[1,length(clock_times)]};
end
% calculate clock offset mappings for each data range
mappings = {};
for r=1:length(ranges)
idx = ranges{r};
if idx(1) ~= idx(2)
% to accomodate the Winsorizing threshold (in seconds) we rescale the data (robust_fit sets it to 1 unit)
mappings{r} = robust_fit([ones(idx(2)-idx(1)+1,1) clock_times(idx(1):idx(2))']/opts.WinsorThreshold, clock_values(idx(1):idx(2))'/opts.WinsorThreshold);
else
mappings{r} = [clock_values(idx(1)) 0]; % just one measurement
end
end
if length(ranges) == 1
% apply the correction to all time stamps
temp(k).time_stamps = temp(k).time_stamps + (mappings{1}(1) + mappings{1}(2)*temp(k).time_stamps);
else
% if there are data segments measured with different clocks we need to
% determine, for any time stamp lying between two segments, to which of the segments it belongs
clock_segments = zeros(size(temp(k).time_stamps)); % the segment index to which each stamp belongs
begin_of_segment = 1; % first index into time stamps that belongs to the current segment
end_of_segment = NaN; %#ok<NASGU> % last index into time stamps that belongs to the current segment
for r=1:length(ranges)-1
cur_end_time = clock_times(ranges{r}(2)); % time at which the current segment ends
next_begin_time = clock_times(ranges{r+1}(1)); % time at which the next segment begins
% get the data that is not yet processed
remaining_indices = begin_of_segment:length(temp(k).time_stamps);
if isempty(remaining_indices)
break; end
remaining_data = temp(k).time_stamps(remaining_indices);
if next_begin_time > cur_end_time
% clock jumps forward: the end of the segment is where the data time stamps
% lie closer to the next segment than the current in time
end_of_segment = remaining_indices(min(find([abs(remaining_data-cur_end_time) > abs(remaining_data-next_begin_time),true],1)-1,length(remaining_indices)));
else
% clock jumps backward: the end of the segment is where the data time stamps
% jump back by more than the max conceivable jitter (as any negative delta is jitter)
end_of_segment = remaining_indices(min(find([diff(remaining_data) < -opts.ClockResetMaxJitter,true],1),length(remaining_indices)));
end
% assign the segment of data points to the current range
% go to next segment
clock_segments(begin_of_segment:end_of_segment) = r;
begin_of_segment = end_of_segment+1;
end
% assign all remaining time stamps to the last segment
clock_segments(begin_of_segment:end) = length(ranges);
% apply corrections on a per-segment basis
for r=1:length(ranges)
temp(k).time_stamps(clock_segments==r) = temp(k).time_stamps(clock_segments==r) + (mappings{r}(1) + mappings{r}(2)*temp(k).time_stamps(clock_segments==r)); end
end
end
end
end
% ===========================================
% === perform jitter removal if requested ===
% ===========================================
if opts.HandleJitterRemoval
% jitter removal is a bonus feature that yields linearly increasing timestamps from data
% where samples had been time stamped with some jitter (e.g., due to operating system
% delays)
if opts.Verbose
disp(' performing jitter removal...'); end
for k=1:length(temp)
if ~isempty(temp(k).time_stamps) && temp(k).srate
% identify breaks in the data
diffs = diff(temp(k).time_stamps);
breaks_at = diffs > max(opts.JitterBreakThresholdSeconds,opts.JitterBreakThresholdSamples*temp(k).sampling_interval);
if any(breaks_at)
% turn the break mask into a cell array of [begin,end] index ranges
tmp = find(breaks_at)';
tmp = [tmp tmp+1]';
tmp = [1 tmp(:)' length(breaks_at)];
ranges = num2cell(reshape(tmp,2,[])',2);
if opts.Verbose
disp([' found ' num2str(nnz(breaks_at)) ' data breaks in stream ' streams{k}.info.name '.']); end
else
ranges = {[1,length(temp(k).time_stamps)]};
end
% process each segment separately
segments = repmat(struct(),1,length(ranges));
for r=1:length(ranges)
range = ranges{r};
segments(r).num_samples = range(2)-range(1)+1;
segments(r).index_range = range;
if segments(r).num_samples > 0
indices = segments(r).index_range(1):segments(r).index_range(2);
% regress out the jitter
mapping = temp(k).time_stamps(indices) / [ones(1,length(indices)); indices];
temp(k).time_stamps(indices) = mapping(1) + mapping(2) * indices;
end
% calculate some other meta-data about the segments
segments(r).t_begin = temp(k).time_stamps(range(1));
segments(r).t_end = temp(k).time_stamps(range(2));
segments(r).duration = segments(r).t_end - segments(r).t_begin;
segments(r).effective_srate = segments(r).num_samples / segments(r).duration;
end
% calculate the weighted mean sampling rate over all segments
temp(k).effective_rate = sum(bsxfun(@times,[segments.effective_srate],[segments.num_samples]/sum([segments.num_samples])));
% transfer the information into the output structs
streams{k}.info.effective_srate = temp(k).effective_rate;
streams{k}.segments = segments;
end
end
else
% calculate effective sampling rate
for k=1:length(temp)
temp(k).effective_srate = length(temp(k).time_stamps) / (temp(k).time_stamps(end) - temp(k).time_stamps(1)); end
end
% copy the information into the output
for k=1:length(temp)
streams{k}.time_series = temp(k).time_series;
streams{k}.time_stamps = temp(k).time_stamps;
end
end
% ========================
% === helper functions ===
% ========================
% read a variable-length integer
function num = read_varlen_int(f)
try
switch fread(f,1,'*uint8')
case 1
num = fread(f,1,'*uint8');
case 4
num = fread(f,1,'*uint32');
case 8
num = fread(f,1,'*uint64');
otherwise
error('Invalid variable-length integer encountered.');
end
catch %#ok<*CTCH>
num = 0;
end
end
% close the file and delete temporary data
function close_file(f,filename)
fclose(f);
if strfind(filename,'_temp_uncompressed.xdf')
delete(filename); end
end
% parse a simplified (attribute-free) subset of XML into a MATLAB struct
function result = parse_xml_struct(str)
import org.xml.sax.InputSource
import javax.xml.parsers.*
import java.io.*
tmp = InputSource();
tmp.setCharacterStream(StringReader(str));
result = parseChildNodes(xmlread(tmp));
% this is part of xml2struct (slightly simplified)
function [children,ptext] = parseChildNodes(theNode)
% Recurse over node children.
children = struct;
ptext = [];
if theNode.hasChildNodes
childNodes = theNode.getChildNodes;
numChildNodes = childNodes.getLength;
for count = 1:numChildNodes
theChild = childNodes.item(count-1);
[text,name,childs] = getNodeData(theChild);
if (~strcmp(name,'#text') && ~strcmp(name,'#comment'))
if (isfield(children,name))
if (~iscell(children.(name)))
children.(name) = {children.(name)}; end
index = length(children.(name))+1;
children.(name){index} = childs;
if(~isempty(text))
children.(name){index} = text; end
else
children.(name) = childs;
if(~isempty(text))
children.(name) = text; end
end
elseif (strcmp(name,'#text'))
if (~isempty(regexprep(text,'[\s]*','')))
if (isempty(ptext))
ptext = text;
else
ptext = [ptext text];
end
end
end
end
end
end
% this is part of xml2struct (slightly simplified)
function [text,name,childs] = getNodeData(theNode)
% Create structure of node info.
name = char(theNode.getNodeName);
if ~isvarname(name)
name = regexprep(name,'[-]','_dash_');
name = regexprep(name,'[:]','_colon_');
name = regexprep(name,'[.]','_dot_');
end
[childs,text] = parseChildNodes(theNode);
if (isempty(fieldnames(childs)))
try
text = char(theNode.getData);
catch
end
end
end
end
function x = robust_fit(A,y,rho,iters)
% Perform a robust linear regression using the Huber loss function.
% x = robust_fit(A,y,rho,iters)
%
% Input:
% A : design matrix
% y : target variable
% rho : augmented Lagrangian variable (default: 1)
% iters : number of iterations to perform (default: 1000)
%
% Output:
% x : solution for x
%
% Notes:
% solves the following problem via ADMM for x:
% minimize 1/2*sum(huber(A*x - y))
%
% Based on the ADMM Matlab codes also found at:
% http://www.stanford.edu/~boyd/papers/distr_opt_stat_learning_admm.html
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2013-03-04
if ~exist('rho','var')
rho = 1; end
if ~exist('iters','var')
iters = 1000; end
Aty = A'*y;
L = sparse(chol(A'*A,'lower')); U = L';
z = zeros(size(y)); u = z;
for k = 1:iters
x = U \ (L \ (Aty + A'*(z - u)));
d = A*x - y + u;
z = rho/(1+rho)*d + 1/(1+rho)*max(0,(1-(1+1/rho)./abs(d))).*d;
u = d - z;
end
end
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
end
function A = merge(A,B)
% merge data structures A and 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(A,B)
% we retain A and warn about dropping B
disp('Two non-empty (and non-identical) sub-elements occupied the same index; one was dropped. This warning will only be displayed once.');
end
end
function C = grow_cell(C,idx)
% grow a cell array to accomodate a particular index
% (assuming that this index is not contained in the cell array yet)
tmp = sprintf('%i,',idx);
eval(['C{' tmp(1:end-1) '} = [];']);
end
|
github
|
ZijingMao/baselineeegtest-master
|
eegplugin_xdfimport.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/xdfimport1.12/eegplugin_xdfimport.m
| 2,526 |
utf_8
|
65efeb97d83bfe9268d1b766b340fb0d
|
% eegplugin_xdfimport() - EEGLAB plugin for importing XDF data files.
% With this menu it is possible to import a raw XDF file (*.xdf) or
% a compressed file (*.xdfz).
%
% Usage:
% >> eegplugin_xdfimport(menu);
% >> eegplugin_xdfimport(menu, trystrs, catchstrs);
%
% Inputs:
% menu - [float] EEGLAB menu handle
% trystrs - [struct] "try" strings for menu callbacks. See notes on EEGLab plugins.
% (http://www.sccn.ucsd.edu/eeglab/contrib.html)
% catchstrs - [struct] "catch" strings for menu callbacks. See notes on EEGLab plugins.
% (http://www.sccn.ucsd.edu/eeglab/contrib.html)
%
%
% Notes:
% This plugins consist of the following Matlab files:
% pop_loadxdf.m eeg_load_xdf.m
% load_xdf.m
%
% Authors:
% Christian Kothe, Swartz Center for Computational Neuroscience UCSD, 7 May 2012
%
% See also: eeglab(), pop_loadxdf(), eeg_load_xdf(), load_xdf()
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2012 Christian Kothe, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% 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_xdfimport(fig, trystrs, catchstrs)
vers = 'xdfimport1.12';
if nargin < 3
error('eegplugin_xdfimport requires 3 arguments');
end;
% add folder to path
% ------------------
if ~exist('pop_loadxdf','file')
p = which('eegplugin_xdfimport.m');
p = p(1:findstr(p,'eegplugin_xdfimport.m')-1);
addpath( p );
end;
% find import data menu
% ---------------------
menu = findobj(fig, 'tag', 'import data');
% menu callbacks
% --------------
comcnt = [ trystrs.no_check '[EEG LASTCOM] = pop_loadxdf;' catchstrs.new_non_empty ];
uimenu( menu, 'label', 'From .XDF or .XDFZ file', 'callback', comcnt, 'separator', 'on');
|
github
|
ZijingMao/baselineeegtest-master
|
eeg_load_xdf.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/xdfimport1.12/eeg_load_xdf.m
| 11,458 |
utf_8
|
34873fb53b47680e65eec68f5b585067
|
function raw = eeg_load_xdf(filename, varargin)
% Import an XDF file from disk
% EEG = eeg_load_xdf(Filename, Options...)
%
% In:
% Filename : name of the xdf file
%
% Options... : list of name-value pairs for further options; the allowed names are as follows:
% 'streamname' : import only the first stream with the given name
% if specified, takes precedence over the streamtype argument
%
% 'streamtype' : import only the first stream with the given content type
% (default: 'EEG')
%
% 'effective_rate' : if true, use the effective sampling rate instead of the nominal
% sampling rate (as declared by the device) (default: false)
%
% 'exclude_markerstreams' : can be a cell array of stream names to exclude from
% use as marker streams (default: {})
%
% Out:
% EEG : imported EEGLAB data set
%
% Christian Kothe, Swartz Center for Computational Neuroscience, UCSD
% 2012-05-07
% parse arguments
args = hlp_varargin2struct(varargin,'streamname','','streamtype','EEG','effective_rate',false, ...
'exclude_markerstreams',{});
% first load the .xdf file
streams = load_xdf(filename);
% then pick the first stream that matches the criteria
if ~isempty(args.streamname)
% select by name
for s=1:length(streams)
if isfield(streams{s}.info,'name') && strcmp(streams{s}.info.name,args.streamname)
% found it
stream = streams{s};
break;
end
end
if ~exist('stream','var')
error(['The data contains no stream with the name "' args.streamname '".']); end
elseif ~isempty(args.streamtype)
% select by type
for s=1:length(streams)
if isfield(streams{s}.info,'type') && strcmp(streams{s}.info.type,args.streamtype)
% found it
stream = streams{s};
break;
end
end
if ~exist('stream','var')
error(['The data contains no stream with the type "' args.streamtype '".']); end
else
error('You need to pass either the streamname or the streamtype argument.');
end
raw = eeg_emptyset;
raw.data = stream.time_series;
[raw.nbchan,raw.pnts,raw.trials] = size(raw.data);
[raw.filepath,fname,fext] = fileparts(filename); raw.filename = [fname fext];
if args.effective_rate && isfinite(stream.info.effective_srate) && stream.info.effective_srate>0
raw.srate = stream.info.effective_srate;
else
raw.srate = str2num(stream.info.nominal_srate); %#ok<ST2NM>
end
raw.xmin = 0;
raw.xmax = (raw.pnts-1)/raw.srate;
% chanlocs...
chanlocs = struct();
try
for c=1:length(stream.info.desc.channels.channel)
chn = stream.info.desc.channels.channel{c};
if isfield(chn,'label')
chanlocs(c).labels = chn.label; end
if isfield(chn,'type')
chanlocs(c).type = chn.type; end
try
chanlocs(c).X = str2num(chn.location.X)/1000;
chanlocs(c).Y = str2num(chn.location.Y)/1000;
chanlocs(c).Z = str2num(chn.location.Z)/1000;
[chanlocs(c).sph_theta,chanlocs(c).sph_phi,chanlocs(c).sph_radius] = cart2sph(chanlocs(c).X,chanlocs(c).Y,chanlocs(c).Z);
[chanlocs(c).theta,chanlocs(c).radius] = cart2pol(chanlocs(c).X,chanlocs(c).Y);
catch
[chanlocs(c).X,chanlocs(c).Y,chanlocs(c).Z,chanlocs(c).sph_theta,chanlocs(c).sph_phi,chanlocs(c).sph_radius,chanlocs(c).theta,chanlocs(c).radius] = deal([]);
end
chanlocs(c).urchan = c;
chanlocs(c).ref = '';
end
raw.chaninfo.nosedir = '+Y';
catch e
disp(['Could not import chanlocs: ' e.message]);
end
raw.chanlocs = chanlocs;
try
raw.chaninfo.labelscheme = stream.info.desc.cap.labelscheme;
catch
end
% events...
event = [];
if isfinite(stream.info.effective_srate) && stream.info.effective_srate>0
srate = stream.info.effective_srate;
else
srate = raw.srate;
end
for s=1:length(streams)
if (strcmp(streams{s}.info.type,'Markers') || strcmp(streams{s}.info.type,'Events')) && ~ismember(streams{s}.info.name,args.exclude_markerstreams)
try
if iscell(streams{s}.time_series)
for e=1:length(streams{s}.time_stamps)
event(end+1).type = streams{s}.time_series{e};
event(end).latency = 1+srate*(streams{s}.time_stamps(e)-stream.time_stamps(1));
event(end).duration = 1;
end
else
for e=1:length(streams{s}.time_stamps)
event(end+1).type = num2str(streams{s}.time_series(e));
event(end).latency = 1+srate*(streams{s}.time_stamps(e)-stream.time_stamps(1));
event(end).duration = 1;
end
end
catch err
disp(['Could not interpret event stream named "' streams{s}.info.name '": ' err.message]);
end
end
end
raw.event = event;
% etc...
raw.etc.desc = stream.info.desc;
raw.etc.info = rmfield(stream.info,'desc');
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
|
ZijingMao/baselineeegtest-master
|
pop_loadxdf.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/xdfimport1.12/pop_loadxdf.m
| 4,515 |
utf_8
|
585952592e1218043944245f50745c2f
|
% pop_loadxdf() - Load an XDF file (*.xdf or *.xdfz).
% (pop out window if no arguments)
%
% Usage:
% >> [EEG] = pop_loadxdf;
% >> [EEG] = pop_loadxdf( filename, 'key', 'val', ...);
%
% Graphic interface:
%
% "Stream name to import" - [edit box] specify name of stream to import; if nonempty, only the
% stream with the given name will be imported (otherwise the stream type
% will be used to determine what stream to import)
% Command line equivalent in eeg_load_xdf: 'streamname'
% "Stream type to import" - [edit box] specify content type of stream to import
% see http://code.google.com/p/xdf/wiki/MetaData (bottom) for content types
% Command line equivalent in eeg_load_xdf: 'streamtype'
% "Exclude marker stream(s)" - [edit box] specify names of marker streams to skip; this is in
% MATLAB cell array syntax, e.g. {'MyVideoMarkers','SyncStream001'}
% Command line equivalent in eeg_load_xdf: 'exclude_markerstreams'
%
% Inputs:
% filename - file name
%
% Optional inputs:
% 'streamname' - name of stream to import (if omitted, streamtype takes precedence)
% 'streamtype' - type of stream to import (default: 'EEG')
% 'exclude_markerstreams' - cell array of marker stream names that should be excluded from import
% Same as eeg_load_xdf() function.
%
% Outputs:
% [EEG] - EEGLAB data structure
%
% Note:
% This script is based on pop_loadcnt.m to make it compatible and easy to use in
% EEGLab.
%
% Author: Christian Kothe, Swartz Center for Computational Neuroscience, UCSD, 2012
%
% See also: eeglab(), eeg_load_xdf(), load_xdf()
%
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2012 Christian Kothe, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function [EEG, command]=pop_loadxdf(filename, varargin);
command = '';
filepath = '';
EEG=[];
if nargin < 1
% ask user
[filename, filepath] = uigetfile('*.xdf;*.xdfz', 'Choose an XDF file -- pop_loadxdf()');
drawnow;
if filename == 0 return; end;
% popup window parameters
% -----------------------
uigeom = { [1 0.5] [1 0.5] [1 0.5] 0.13};
uilist = { { 'style' 'text' 'string' 'Stream name to import:' } ...
{ 'style' 'edit' 'string' '' } ...
{ 'style' 'text' 'string' 'Stream type to import:' } ...
{ 'style' 'edit' 'string' 'EEG' } ...
{ 'style' 'text' 'string' 'Exclude marker streams(s):' } ...
{ 'style' 'edit' 'string' '{}' } {}};
result = inputgui(uigeom, uilist, 'pophelp(''pop_loadxdf'')', 'Load an XDF file');
if length( result ) == 0 return; end;
% decode parameters
% -----------------
options = [];
if ~isempty(result{1}),
options = [options ', ''streamname'', ''' result{1} '''']; end
if ~isempty(result{2}),
options = [options ', ''streamtype'', ''' result{2} '''']; end
if ~isempty(result{3}),
options = [options ', ''exclude_markerstreams'', ' result{3} '']; end
else
options = vararg2str(varargin);
end;
% load data
% ----------
if exist('filepath','var')
fullFileName = sprintf('%s%s', filepath, filename);
else
fullFileName = filename;
end;
fprintf('Now importing...');
if nargin > 0
EEG = eeg_load_xdf(fullFileName, varargin{:});
else
eval( [ 'EEG = eeg_load_xdf( fullFileName ' options ');' ]);
end;
fprintf('done.\n');
EEG = eeg_checkset(EEG);
if length(options) > 2
command = sprintf('EEG = pop_loadxdf(''%s'' %s);',fullFileName, options);
else
command = sprintf('EEG = pop_loadxdf(''%s'');',fullFileName);
end;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_dipfit_manual.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
eeglab2fieldtrip.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/dipfit2.3/eeglab2fieldtrip.m
| 5,533 |
utf_8
|
d6ce02769901e24cc6e5dcc5fc0f3df6
|
% 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'
for index = 1:EEG.trials
% the trials correspond to the raw data trials, except that they
% contain the component activations
try,
data.trial{index} = EEG.icaact(:,:,index);
catch
end;
data.time{index} = linspace(EEG.xmin, EEG.xmax, EEG.pnts); % should be checked in FIELDTRIP
end;
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
|
ZijingMao/baselineeegtest-master
|
dipfit_reject.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
pop_dipplot.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
dipplot.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/dipfit2.3/dipplot.m
| 61,429 |
utf_8
|
65efa49f492935c7a8e31aa84235841c
|
% 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, [indx indy indz], 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
|
ZijingMao/baselineeegtest-master
|
fieldtripchan2eeglab.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
sph2spm.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
homogenous2traditional.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
electroderealign.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
pop_dipfit_nonlinear.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
dipfit_1_to_2.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
dipfit_gridsearch.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
eegplugin_dipfit.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
pop_multifit.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
pop_dipfit_gridsearch.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
dipfit_erpeeg.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
pop_dipfit_batch.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
dipfit_nonlinear.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
adjustcylinder2.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
pop_dipfit_settings.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/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
|
ZijingMao/baselineeegtest-master
|
firfiltdcpadded.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/firfiltdcpadded.m
| 2,137 |
utf_8
|
b21b4207bf032e32cc6f0597db3cb4fe
|
% firfiltdcpadded() - Pad data with DC constant and filter
%
% Usage:
% >> data = firfiltdcpadded(data, b, causal);
%
% Inputs:
% data - raw data
% b - vector of filter coefficients
% causal - boolean perform causal filtering {default 0}
%
% Outputs:
% data - smoothed data
%
% Note:
% firfiltdcpadded always operates (pads, filters) along first dimension.
% Not memory optimized.
%
% Author: Andreas Widmann, University of Leipzig, 2013
%
% See also:
% firfiltsplit
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2013 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 [ data ] = firfiltdcpadded(b, data, causal)
% Defaults
if nargin < 3 || isempty(causal)
causal = 0;
end
% Check arguments
if nargin < 2
error('Not enough input arguments.');
end
% Filter's group delay
if mod(length(b), 2) ~= 1
error('Filter order is not even.');
end
groupDelay = (length(b) - 1) / 2;
b = double(b); % Filter with double precision
% Pad data with DC constant
if causal
startPad = repmat(data(1, :), [2 * groupDelay 1]);
endPad = [];
else
startPad = repmat(data(1, :), [groupDelay 1]);
endPad = repmat(data(end, :), [groupDelay 1]);
end
% Filter data
data = filter(b, 1, double([startPad; data; endPad])); % Pad and filter with double precision
% Remove padded data
data = data(2 * groupDelay + 1:end, :);
end
|
github
|
ZijingMao/baselineeegtest-master
|
minphaserceps.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/minphaserceps.m
| 1,275 |
utf_8
|
7b751637e7eed71e29f91a4ef6b586e6
|
% rcepsminphase() - Convert FIR filter coefficient to minimum phase
%
% Usage:
% >> b = minphaserceps(b);
%
% Inputs:
% b - FIR filter coefficients
%
% Outputs:
% bMinPhase - minimum phase FIR filter coefficients
%
% Author: Andreas Widmann, University of Leipzig, 2013
%
% References:
% [1] Smith III, O. J. (2007). Introduction to Digital Filters with Audio
% Applications. W3K Publishing. Retrieved Nov 11 2013, from
% https://ccrma.stanford.edu/~jos/fp/Matlab_listing_mps_m.html
% [2] Vetter, K. (2013, Nov 11). Long FIR filters with low latency.
% Retrieved Nov 11 2013, from
% http://www.katjaas.nl/minimumphase/minimumphase.html
function [bMinPhase] = minphaserceps(b)
% Line vector
b = b(:)';
n = length(b);
upsamplingFactor = 1e3; % Impulse response upsampling/zero padding to reduce time-aliasing
nFFT = 2^ceil(log2(n * upsamplingFactor)); % Power of 2
clipThresh = 1e-8; % -160 dB
% Spectrum
s = abs(fft(b, nFFT));
s(s < clipThresh) = clipThresh; % Clip spectrum to reduce time-aliasing
% Real cepstrum
c = real(ifft(log(s)));
% Fold
c = [c(1) [c(2:nFFT / 2) 0] + conj(c(nFFT:-1:nFFT / 2 + 1)) zeros(1, nFFT / 2 - 1)];
% Minimum phase
bMinPhase = real(ifft(exp(fft(c))));
% Remove zero-padding
bMinPhase = bMinPhase(1:n);
|
github
|
ZijingMao/baselineeegtest-master
|
firws.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/firws.m
| 3,219 |
utf_8
|
0ab4c517238d31712ba1d97ab2497f45
|
%firws() - Designs windowed sinc type I linear phase FIR filter
%
% Usage:
% >> b = firws(m, f);
% >> b = firws(m, f, w);
% >> b = firws(m, f, t);
% >> b = firws(m, f, t, w);
%
% Inputs:
% m - filter order (mandatory even)
% f - vector or scalar of cutoff frequency/ies (-6 dB;
% pi rad / sample)
%
% Optional inputs:
% w - vector of length m + 1 defining window {default blackman}
% t - 'high' for highpass, 'stop' for bandstop filter {default low-/
% bandpass}
%
% Output:
% b - filter coefficients
%
% Example:
% fs = 500; cutoff = 0.5; tbw = 1;
% m = pop_firwsord('hamming', fs, tbw);
% b = firws(m, cutoff / (fs / 2), 'high', windows('hamming', m + 1));
%
% References:
% Smith, S. W. (1999). The scientist and engineer's guide to digital
% signal processing (2nd ed.). San Diego, CA: California Technical
% Publishing.
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% pop_firws, pop_firwsord, 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 [b a] = firws(m, f, t, w)
a = 1;
if nargin < 2
error('Not enough input arguments');
end
if length(m) > 1 || ~isnumeric(m) || ~isreal(m) || mod(m, 2) ~= 0 || m < 2
error('Filter order must be a real, even, positive integer.');
end
f = f / 2;
if any(f <= 0) || any(f >= 0.5)
error('Frequencies must fall in range between 0 and 1.');
end
if nargin < 3 || isempty(t)
t = '';
end
if nargin < 4 || isempty(w)
if ~isempty(t) && ~ischar(t)
w = t;
t = '';
else
w = windows('blackman', (m + 1));
end
end
w = w(:)'; % Make window row vector
b = fkernel(m, f(1), w);
if length(f) == 1 && strcmpi(t, 'high')
b = fspecinv(b);
end
if length(f) == 2
b = b + fspecinv(fkernel(m, f(2), w));
if isempty(t) || ~strcmpi(t, 'stop')
b = fspecinv(b);
end
end
% Compute filter kernel
function b = fkernel(m, f, w)
m = -m / 2 : m / 2;
b(m == 0) = 2 * pi * f; % No division by zero
b(m ~= 0) = sin(2 * pi * f * m(m ~= 0)) ./ m(m ~= 0); % Sinc
b = b .* w; % Window
b = b / sum(b); % Normalization to unity gain at DC
% Spectral inversion
function b = fspecinv(b)
b = -b;
b(1, (length(b) - 1) / 2 + 1) = b(1, (length(b) - 1) / 2 + 1) + 1;
|
github
|
ZijingMao/baselineeegtest-master
|
pop_firma.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/pop_firma.m
| 3,356 |
utf_8
|
e6d49147b8406a5ac3fed31ab0809194
|
% pop_firma() - Filter data using moving average FIR filter
%
% Usage:
% >> [EEG, com] = pop_firma(EEG); % pop-up window mode
% >> [EEG, com] = pop_firma(EEG, 'forder', order);
%
% Inputs:
% EEG - EEGLAB EEG structure
% 'forder' - scalar filter order. Mandatory even
%
% Outputs:
% EEG - filtered EEGLAB EEG structure
% com - history string
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% firfilt, plotfresp
%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] = pop_firma(EEG, varargin)
com = '';
if nargin < 1
help pop_firma;
return;
end
if isempty(EEG.data)
error('Cannot process empty dataset');
end
if nargin < 2
drawnow;
uigeom = {[1 1 1] [1] [1 1 1]};
uilist = {{'style' 'text' 'string' 'Filter order (mandatory even):'} ...
{'style' 'edit' 'string' '' 'tag' 'forderedit'} {} ...
{} ...
{} {} {'Style' 'pushbutton' 'string' 'Plot filter responses' 'callback' {@complot, EEG.srate}}};
result = inputgui(uigeom, uilist, 'pophelp(''pop_firma'')', 'Filter the data -- pop_firma()');
if length(result) == 0, return; end
if ~isempty(result{1})
args = [{'forder'} {str2num(result{1})}];
else
error('Not enough input arguments');
end
else
args = varargin;
end
% Convert args to structure
args = struct(args{:});
% Filter coefficients
b = ones(1, args.forder + 1) / (args.forder + 1);
% Filter
disp('pop_firma() - filtering the data');
EEG = firfilt(EEG, b);
% History string
com = sprintf('%s = pop_firma(%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 ');'];
% Callback plot filter properties
function complot(obj, evt, srate)
args.forder = str2num(get(findobj(gcbf, 'tag', 'forderedit'), 'string'));
if isempty(args.forder)
error('Not enough input arguments');
end
b = ones(1, args.forder + 1) / (args.forder + 1);
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);
|
github
|
ZijingMao/baselineeegtest-master
|
pop_firpm.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/pop_firpm.m
| 7,851 |
utf_8
|
7c3dd000ac470b65949e9914d8dc07d5
|
% pop_firpm() - Filter data using Parks-McClellan FIR filter
%
% Usage:
% >> [EEG, com, b] = pop_firpm(EEG); % pop-up window mode
% >> [EEG, com, b] = pop_firpm(EEG, 'key1', value1, 'key2', ...
% value2, 'keyn', valuen);
%
% Inputs:
% EEG - EEGLAB EEG structure
% 'fcutoff' - vector or scalar of cutoff frequency/ies (~-6 dB; Hz)
% 'ftrans' - scalar transition band width
% 'ftype' - char array filter type. 'bandpass', 'highpass',
% 'lowpass', or 'bandstop'
% 'forder' - scalar filter order. Mandatory even
%
% Optional inputs:
% 'wtpass' - scalar passband weight
% 'wtstop' - scalar stopband weight
%
% Outputs:
% EEG - filtered EEGLAB EEG structure
% com - history string
% b - filter coefficients
%
% Note:
% Requires the signal processing toolbox.
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% firfilt, pop_firpmord, plotfresp, 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 [EEG, com, b] = pop_firpm(EEG, varargin)
if exist('firpm', 'file') ~= 2
error('Requires the signal processing toolbox.');
end
com = '';
if nargin < 1
help pop_firpm;
return;
end
if isempty(EEG.data)
error('Cannot process empty dataset');
end
if nargin < 2
drawnow;
ftypes = {'bandpass' 'highpass' 'lowpass' 'bandstop'};
uigeom = {[1 0.75 0.75] [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 0.75 0.75]};
uilist = {{'Style' 'text' 'String' 'Cutoff frequency(ies) [hp lp] (~-6 dB; Hz):'} ...
{'Style' 'edit' 'String' '' 'Tag' 'fcutoffedit'} {} ...
{'Style' 'text' 'String' 'Transition band width:'} ...
{'Style' 'edit' 'String' '' 'Tag' 'ftransedit'} {} ...
{'Style' 'text' 'String' 'Filter type:'} ...
{'Style' 'popupmenu' 'String' ftypes 'Tag' 'ftypepop'} {} ...
{} ...
{'Style' 'text' 'String' 'Passband weight:'} ...
{'Style' 'edit' 'String' '' 'Tag' 'wtpassedit'} {} ...
{'Style' 'text' 'String' 'Stopband weight:'} ...
{'Style' 'edit' 'String' '' 'Tag' 'wtstopedit'} {} ...
{'Style' 'text' 'String' 'Filter order (mandatory even):'} ...
{'Style' 'edit' 'String' '' 'Tag' 'forderedit'} ...
{'Style' 'pushbutton' 'String' 'Estimate' 'Tag' 'orderpush' 'Callback' {@comcb, ftypes, EEG.srate}} ...
{} ...
{} {} {'Style' 'pushbutton' 'String', 'Plot filter responses' 'Tag' 'plotpush' 'Callback' {@comcb, ftypes, EEG.srate}}};
result = inputgui(uigeom, uilist, 'pophelp(''pop_firpm'')', 'Filter the data -- pop_firpm()');
if isempty(result), return; end
args = {};
if ~isempty(result{1})
args = [args {'fcutoff'} {str2num(result{1})}];
end
if ~isempty(result{2})
args = [args {'ftrans'} {str2double(result{2})}];
end
args = [args {'ftype'} ftypes(result{3})];
if ~isempty(result{4})
args = [args {'wtpass'} {str2double(result{4})}];
end
if ~isempty(result{5})
args = [args {'wtstop'} {str2double(result{5})}];
end
if ~isempty(result{6})
args = [args {'forder'} {str2double(result{6})}];
end
else
args = varargin;
end
% Convert args to structure
args = struct(args{:});
c = parseargs(args, EEG.srate);
if ~isfield(args, 'forder') || isempty(args.forder)
error('Not enough input arguments');
end
b = firpm(args.forder, c{:});
% Filter
disp('pop_firpm() - filtering the data');
EEG = firfilt(EEG, b);
% History string
com = sprintf('%s = pop_firpm(%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 firpm parameters
function c = parseargs(args, srate)
if ~isfield(args, 'fcutoff') || ~isfield(args, 'ftype') || ~isfield(args, 'ftrans') || isempty(args.fcutoff) || isempty(args.ftype) || isempty(args.ftrans)
error('Not enough input arguments.');
end
% Cutoff frequencies
args.fcutoff = [args.fcutoff - args.ftrans / 2 args.fcutoff + args.ftrans / 2];
args.fcutoff = sort(args.fcutoff / (srate / 2)); % Sorting and normalization
if any(args.fcutoff < 0)
error('Cutoff frequencies - transition band width / 2 must not be < DC');
elseif any(args.fcutoff > 1)
error('Cutoff frequencies + transition band width / 2 must not be > Nyquist');
end
c = {[0 args.fcutoff 1]};
% Filter type
switch args.ftype
case 'bandpass'
c = [c {[0 0 1 1 0 0]}];
case 'bandstop'
c = [c {[1 1 0 0 1 1]}];
case 'highpass'
c = [c {[0 0 1 1]}];
case 'lowpass'
c = [c {[1 1 0 0]}];
end
%Filter weights
if all(isfield(args, {'wtpass', 'wtstop'})) && ~isempty(args.wtpass) && ~isempty(args.wtstop)
w = [args.wtstop args.wtpass];
c{3} = w(c{2}(1:2:end) + 1);
end
% Callback
function comcb(obj, evt, ftypes, srate)
args.fcutoff = str2num(get(findobj(gcbf, 'Tag', 'fcutoffedit'), 'String'));
args.ftype = ftypes{get(findobj(gcbf, 'Tag', 'ftypepop'), 'Value')};
args.ftrans = str2double(get(findobj(gcbf, 'Tag', 'ftransedit'), 'String'));
args.wtpass = str2double(get(findobj(gcbf, 'Tag', 'wtpassedit'), 'String'));
args.wtstop = str2double(get(findobj(gcbf, 'Tag', 'wtstopedit'), 'String'));
c = parseargs(args, srate);
switch get(obj, 'Tag')
case 'orderpush'
[args.forder, args.wtpass, args.wtstop] = pop_firpmord(c{1}(2:end - 1), c{2}(1:2:end));
if ~isempty(args.forder) || ~isempty(args.wtpass) || ~isempty(args.wtstop)
set(findobj(gcbf, 'Tag', 'forderedit'), 'String', ceil(args.forder / 2) * 2);
set(findobj(gcbf, 'Tag', 'wtpassedit'), 'String', args.wtpass);
set(findobj(gcbf, 'Tag', 'wtstopedit'), 'String', args.wtstop);
end
case 'plotpush'
args.forder = str2double(get(findobj(gcbf, 'Tag', 'forderedit'), 'String'));
if isempty(args.forder)
error('Not enough input arguments');
end
b = firpm(args.forder, c{:});
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);
end
|
github
|
ZijingMao/baselineeegtest-master
|
pop_eegfiltnew.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/pop_eegfiltnew.m
| 8,518 |
utf_8
|
2643866f3c2d0e4035854d1705dce948
|
% pop_eegfiltnew() - Filter data using Hamming windowed sinc FIR filter
%
% Usage:
% >> [EEG, com, b] = pop_eegfiltnew(EEG); % pop-up window mode
% >> [EEG, com, b] = pop_eegfiltnew(EEG, locutoff, hicutoff, filtorder,
% revfilt, usefft, plotfreqz, minphase);
%
% Inputs:
% EEG - EEGLAB EEG structure
% locutoff - lower edge of the frequency pass band (Hz)
% {[]/0 -> lowpass}
% hicutoff - higher edge of the frequency pass band (Hz)
% {[]/0 -> highpass}
%
% Optional inputs:
% filtorder - filter order (filter length - 1). Mandatory even
% revfilt - [0|1] invert filter (from bandpass to notch filter)
% {default 0 (bandpass)}
% usefft - ignored (backward compatibility only)
% plotfreqz - [0|1] plot filter's frequency and phase response
% {default 0}
% minphase - scalar boolean minimum-phase converted causal filter
% {default false}
%
% Outputs:
% EEG - filtered EEGLAB EEG structure
% com - history string
% b - filter coefficients
%
% Note:
% pop_eegfiltnew is intended as a replacement for the deprecated
% pop_eegfilt function. Required filter order/transition band width is
% estimated with the following heuristic in default mode: transition band
% width is 25% of the lower passband edge, but not lower than 2 Hz, where
% possible (for bandpass, highpass, and bandstop) and distance from
% passband edge to critical frequency (DC, Nyquist) otherwise. Window
% type is hardcoded to Hamming. Migration to windowed sinc FIR filters
% (pop_firws) is recommended. pop_firws allows user defined window type
% and estimation of filter order by user defined transition band width.
%
% Author: Andreas Widmann, University of Leipzig, 2012
%
% See also:
% firfilt, firws, windows
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2008 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_eegfiltnew(EEG, locutoff, hicutoff, filtorder, revfilt, usefft, plotfreqz, minphase)
com = '';
if nargin < 1
help pop_eegfiltnew;
return
end
if isempty(EEG.data)
error('Cannot filter empty dataset.');
end
% GUI
if nargin < 2
geometry = {[3, 1], [3, 1], [3, 1], 1, 1, 1, 1};
geomvert = [1 1 1 2 1 1 1];
uilist = {{'style', 'text', 'string', 'Lower edge of the frequency pass band (Hz)'} ...
{'style', 'edit', 'string', ''} ...
{'style', 'text', 'string', 'Higher edge of the frequency pass band (Hz)'} ...
{'style', 'edit', 'string', ''} ...
{'style', 'text', 'string', 'FIR Filter order (Mandatory even. Default is automatic*)'} ...
{'style', 'edit', 'string', ''} ...
{'style', 'text', 'string', {'*See help text for a description of the default filter order heuristic.', 'Manual definition is recommended.'}} ...
{'style', 'checkbox', 'string', 'Notch filter the data instead of pass band', 'value', 0} ...
{'Style', 'checkbox', 'String', 'Use minimum-phase converted causal filter (non-linear!; beta)', 'Value', 0} ...
{'style', 'checkbox', 'string', 'Plot frequency response', 'value', 1}};
result = inputgui('geometry', geometry, 'geomvert', geomvert, 'uilist', uilist, 'title', 'Filter the data -- pop_eegfiltnew()', 'helpcom', 'pophelp(''pop_eegfiltnew'')');
if isempty(result), return; end
locutoff = str2num(result{1});
hicutoff = str2num(result{2});
filtorder = str2num(result{3});
revfilt = result{4};
minphase = result{5};
plotfreqz = result{6};
usefft = [];
else
if nargin < 3
hicutoff = [];
end
if nargin < 4
filtorder = [];
end
if nargin < 5 || isempty(revfilt)
revfilt = 0;
end
if nargin < 6
usefft = [];
elseif usefft == 1
error('FFT filtering not supported. Argument is provided for backward compatibility in command line mode only.')
end
if nargin < 7 || isempty(plotfreqz)
plotfreqz = 0;
end
if nargin < 8 || isempty(minphase)
minphase = 0;
end
end
% Constants
TRANSWIDTHRATIO = 0.25;
fNyquist = EEG.srate / 2;
% Check arguments
if locutoff == 0, locutoff = []; end
if hicutoff == 0, hicutoff = []; end
if isempty(hicutoff) % Convert highpass to inverted lowpass
hicutoff = locutoff;
locutoff = [];
revfilt = ~revfilt;
end
edgeArray = sort([locutoff hicutoff]);
if isempty(edgeArray)
error('Not enough input arguments.');
end
if any(edgeArray < 0 | edgeArray >= fNyquist)
error('Cutoff frequency out of range');
end
if ~isempty(filtorder) && (filtorder < 2 || mod(filtorder, 2) ~= 0)
error('Filter order must be a real, even, positive integer.')
end
% Max stop-band width
maxTBWArray = edgeArray; % Band-/highpass
if revfilt == 0 % Band-/lowpass
maxTBWArray(end) = fNyquist - edgeArray(end);
elseif length(edgeArray) == 2 % Bandstop
maxTBWArray = diff(edgeArray) / 2;
end
maxDf = min(maxTBWArray);
% Transition band width and filter order
if isempty(filtorder)
% Default filter order heuristic
if revfilt == 1 % Highpass and bandstop
df = min([max([maxDf * TRANSWIDTHRATIO 2]) maxDf]);
else % Lowpass and bandpass
df = min([max([edgeArray(1) * TRANSWIDTHRATIO 2]) maxDf]);
end
filtorder = 3.3 / (df / EEG.srate); % Hamming window
filtorder = ceil(filtorder / 2) * 2; % Filter order must be even.
else
df = 3.3 / filtorder * EEG.srate; % Hamming window
filtorderMin = ceil(3.3 ./ ((maxDf * 2) / EEG.srate) / 2) * 2;
filtorderOpt = ceil(3.3 ./ (maxDf / EEG.srate) / 2) * 2;
if filtorder < filtorderMin
error('Filter order too low. Minimum required filter order is %d. For better results a minimum filter order of %d is recommended.', filtorderMin, filtorderOpt)
elseif filtorder < filtorderOpt
warning('firfilt:filterOrderLow', 'Transition band is wider than maximum stop-band width. For better results a minimum filter order of %d is recommended. Reported might deviate from effective -6dB cutoff frequency.', filtorderOpt)
end
end
filterTypeArray = {'lowpass', 'bandpass'; 'highpass', 'bandstop (notch)'};
fprintf('pop_eegfiltnew() - performing %d point %s filtering.\n', filtorder + 1, filterTypeArray{revfilt + 1, length(edgeArray)})
fprintf('pop_eegfiltnew() - transition band width: %.4g Hz\n', df)
fprintf('pop_eegfiltnew() - passband edge(s): %s Hz\n', mat2str(edgeArray))
% Passband edge to cutoff (transition band center; -6 dB)
dfArray = {df, [-df, df]; -df, [df, -df]};
cutoffArray = edgeArray + dfArray{revfilt + 1, length(edgeArray)} / 2;
fprintf('pop_eegfiltnew() - cutoff frequency(ies) (-6 dB): %s Hz\n', mat2str(cutoffArray))
% Window
winArray = windows('hamming', filtorder + 1);
% Filter coefficients
if revfilt == 1
filterTypeArray = {'high', 'stop'};
b = firws(filtorder, cutoffArray / fNyquist, filterTypeArray{length(cutoffArray)}, winArray);
else
b = firws(filtorder, cutoffArray / fNyquist, winArray);
end
if minphase
disp('pop_eegfiltnew() - converting filter to minimum-phase (non-linear!)');
b = minphaserceps(b);
end
% Plot frequency response
if plotfreqz
freqz(b, 1, 8192, EEG.srate);
end
% Filter
if minphase
disp('pop_eegfiltnew() - filtering the data (causal)');
EEG = firfiltsplit(EEG, b, 1);
else
disp('pop_eegfiltnew() - filtering the data (zero-phase)');
EEG = firfilt(EEG, b);
end
% History string
com = sprintf('%s = pop_eegfiltnew(%s, %s, %s, %s, %s, %s, %s);', inputname(1), inputname(1), mat2str(locutoff), mat2str(hicutoff), mat2str(filtorder), mat2str(revfilt), mat2str(usefft), mat2str(plotfreqz));
end
|
github
|
ZijingMao/baselineeegtest-master
|
pop_xfirws.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/pop_xfirws.m
| 10,425 |
utf_8
|
d0777a1329eeb3b766e505a0b61242c9
|
% pop_xfirws() - Design and export xfir compatible windowed sinc FIR filter
%
% Usage:
% >> pop_xfirws; % pop-up window mode
% >> [b, a] = pop_xfirws; % pop-up window mode
% >> pop_xfirws('key1', value1, 'key2', value2, 'keyn', valuen);
% >> [b, a] = pop_xfirws('key1', value1, 'key2', value2, 'keyn', valuen);
%
% Inputs:
% 'srate' - scalar sampling rate (Hz)
% '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
% 'filename' - char array export filename
% 'pathname' - char array export pathname {default '.'}
%
% Outputs:
% b - filter coefficients
% a - 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) FIR filters
% are zero phase in passband when shifted by the filters group delay
% (what firfilt does). Pi phase jumps noticable in the phase reponse
% reflect a negative frequency response and only occur in the
% stopband.
%
% 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 (2.9** / m) 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
% ** estimate for higher m only
%
% Example:
% fs = 500; tbw = 2; dev = 0.001;
% beta = pop_kaiserbeta(dev);
% m = pop_firwsord('kaiser', fs, tbw, dev);
% pop_xfirws('srate', fs, 'fcutoff', [1 25], 'ftype', 'bandpass', 'wtype', 'kaiser', 'warg', beta, 'forder', m, 'filename', 'foo.fir')
%
% Author: Andreas Widmann, University of Leipzig, 2011
%
% See also:
% firfilt, firws, pop_firwsord, pop_kaiserbeta, plotfresp, windows
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2011 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 [varargout] = pop_xfirws(varargin)
% Pop-up window mode
if nargin < 1
drawnow;
ftypes = {'bandpass' 'highpass' 'lowpass' 'bandstop'};
wtypes = {'rectangular' 'bartlett' 'hann' 'hamming' 'blackman' 'kaiser'};
uigeom = {[1 0.75 0.75] 1 [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 0.75 0.75]};
uilist = {{'Style' 'text' 'String' 'Sampling frequency (Hz):'} ...
{'Style' 'edit' 'String' '2' 'Tag' 'srateedit'} {} ...
{} ...
{'Style' 'text' 'String' 'Cutoff frequency(ies) [hp lp] (-6 dB; Hz):'} ...
{'Style' 'edit' 'String' '' 'Tag' 'fcutoffedit'} {} ...
{'Style' 'text' 'String' 'Filter type:'} ...
{'Style' 'popupmenu' 'String' ftypes 'Tag' 'ftypepop'} {} ...
{} ...
{'Style' 'text' 'String' 'Window type:'} ...
{'Style' 'popupmenu' 'String' wtypes '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}} ...
{'Style' 'edit' 'Tag' 'devedit' 'Visible' 'off'} ...
{} {} {'Style' 'pushbutton' 'String', 'Plot filter responses' 'Callback' {@comfresp, wtypes, ftypes}}};
result = inputgui(uigeom, uilist, 'pophelp(''pop_firws'')', 'Filter the data -- pop_firws()');
if isempty(result), return; end
Arg = struct;
Arg.srate = str2double(result{1});
Arg.fcutoff = str2num(result{2});
Arg.ftype = ftypes{result{3}};
Arg.wtype = wtypes{result{4}};
Arg.warg = str2num(result{5});
Arg.forder = str2double(result{6});
% Command line mode
else
Arg = struct(varargin{:});
end
% Sampling rate
if ~isfield(Arg, 'srate') || isempty(Arg.srate) % Use default
Arg.srate = 2;
end
% Filter order and cutoff frequencies
if ~isfield(Arg, 'fcutoff') || ~isfield(Arg, 'forder') || isempty(Arg.fcutoff) || isempty(Arg.forder)
error('Not enough input arguments.');
end
firwsArgArray = {Arg.forder sort(Arg.fcutoff / Arg.srate * 2)}; % Sorting and normalization
% Filter type
if ~isfield(Arg, 'ftype') || isempty(Arg.ftype) % Use default
switch length(Arg.fcutoff)
case 1
Arg.ftype = 'lowpass';
case 2
Arg.ftype = 'bandpass';
otherwise
error('Wrong number of arguments.')
end
else
if any(strcmpi(Arg.ftype, {'bandpass' 'bandstop'})) && length(Arg.fcutoff) ~= 2
error('Not enough input arguments.');
elseif any(strcmpi(Arg.ftype, {'highpass' 'lowpass'})) && length(Arg.fcutoff) ~= 1
error('Too many input arguments.');
end
switch Arg.ftype
case 'bandstop'
firwsArgArray(end + 1) = {'stop'};
case 'highpass'
firwsArgArray(end + 1) = {'high'};
end
end
% Window type
if ~isfield(Arg, 'wtype') || isempty(Arg.wtype) % Use default
Arg.wtype = 'blackman';
end
% Window parameter
if ~isfield(Arg, 'warg') || isempty(Arg.warg)
Arg.warg = [];
firwsArgArray(end + 1) = {windows(Arg.wtype, Arg.forder + 1)};
else
firwsArgArray(end + 1) = {windows(Arg.wtype, Arg.forder + 1, Arg.warg)};
end
b = firws(firwsArgArray{:});
a = 1;
if nargout == 0 || isfield(Arg, 'filename')
% Open file
if ~isfield(Arg, 'filename') || isempty(Arg.filename)
[Arg.filename Arg.pathname] = uiputfile('*.fir', 'Save filter -- pop_xfirws');
end
if ~isfield(Arg, 'pathname') || isempty(Arg.pathname)
Arg.pathname = '.';
end
[fid message] = fopen(fullfile(Arg.pathname, Arg.filename), 'w', 'l');
if fid == -1
error(message)
end
% Author
fprintf(fid, '[author]\n');
fprintf(fid, '%s\n\n', 'pop_xfirws 1.5.1');
% FIR design
fprintf(fid, '[fir design]\n');
fprintf(fid, 'method %s\n', 'fourier');
fprintf(fid, 'type %s\n', Arg.ftype);
fprintf(fid, 'fsample %f\n', Arg.srate);
fprintf(fid, 'length %d\n', Arg.forder + 1);
fprintf(fid, 'fcrit%d %f\n', [1:length(Arg.fcutoff); Arg.fcutoff]);
fprintf(fid, 'window %s %s\n\n', Arg.wtype, num2str(Arg.warg)); % fprintf bug
% FIR
fprintf(fid, '[fir]\n');
fprintf(fid, '%d\n', Arg.forder + 1);
fprintf(fid, '% 18.10e\n', b);
% Close file
fclose(fid);
end
if nargout > 0
varargout = {b a};
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 = str2double(get(findobj(gcbf, 'Tag', 'srateedit'), 'String'));
wtype = wtypes{get(findobj(gcbf, 'Tag', 'wtypepop'), 'Value')};
dev = str2double(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)
Arg.srate = str2double(get(findobj(gcbf, 'Tag', 'srateedit'), 'String'));
Arg.fcutoff = str2num(get(findobj(gcbf, 'Tag', 'fcutoffedit'), 'String'));
Arg.ftype = ftypes{get(findobj(gcbf, 'Tag', 'ftypepop'), 'Value')};
Arg.wtype = wtypes{get(findobj(gcbf, 'Tag', 'wtypepop'), 'Value')};
Arg.warg = str2num(get(findobj(gcbf, 'Tag', 'wargedit'), 'String'));
Arg.forder = str2double(get(findobj(gcbf, 'Tag', 'forderedit'), 'String'));
xfirwsArgArray(1, :) = fieldnames(Arg);
xfirwsArgArray(2, :) = struct2cell(Arg);
[b a] = pop_xfirws(xfirwsArgArray{:});
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, a, [], Arg.srate);
|
github
|
ZijingMao/baselineeegtest-master
|
firfiltsplit.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/firfiltsplit.m
| 2,363 |
utf_8
|
8e58b4fa2694a8b1d55b8fcddcf94b4f
|
% firfiltsplit() - Split data at discontinuities and forward to dc padded
% filter function
%
% Usage:
% >> EEG = firfiltsplit(EEG, b);
%
% Inputs:
% EEG - EEGLAB EEG structure
% b - vector of filter coefficients
% causal - scalar boolean perform causal filtering {default 0}
%
% Outputs:
% EEG - EEGLAB EEG structure
%
% Note:
% This function is (in combination with firfiltdcpadded) just a
% non-memory optimized version of the firfilt function allowing causal
% filtering. Will possibly replace firfilt in the future.
%
% Author: Andreas Widmann, University of Leipzig, 2013
%
% See also:
% firfiltdcpadded, findboundaries
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2013 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 = firfiltsplit(EEG, b, causal)
if nargin < 3 || isempty(causal)
causal = 0;
end
if nargin < 2
error('Not enough input arguments.');
end
% 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
% Loop over continuous segments
for iDc = 1:(length(dcArray) - 1)
% Filter segment
EEG.data(:, dcArray(iDc):dcArray(iDc + 1) - 1) = firfiltdcpadded(b, EEG.data(:, dcArray(iDc):dcArray(iDc + 1) - 1)', causal)';
end
% Reshape epoched data
if EEG.trials > 1
EEG.data = reshape(EEG.data, [EEG.nbchan EEG.pnts EEG.trials]);
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
eegplugin_firfilt.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/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
|
ZijingMao/baselineeegtest-master
|
windows.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/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
|
ZijingMao/baselineeegtest-master
|
pop_firpmord.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/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
|
ZijingMao/baselineeegtest-master
|
firfilt.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/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
|
ZijingMao/baselineeegtest-master
|
pop_firws.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/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
|
ZijingMao/baselineeegtest-master
|
plotfresp.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/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
|
ZijingMao/baselineeegtest-master
|
pop_firwsord.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/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
|
ZijingMao/baselineeegtest-master
|
pop_kaiserbeta.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/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
|
ZijingMao/baselineeegtest-master
|
findboundaries.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/firfilt1.6.1/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
|
ZijingMao/baselineeegtest-master
|
ft_write_cifti.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/ft_write_cifti.m
| 31,382 |
utf_8
|
59bae254f9ddbd0026ce3b2f2fbc1909
|
function ft_write_cifti(filename, source, varargin)
% FT_WRITE_CIFTI writes functional data or functional connectivity to a cifti-2
% file. The geometrical description of the brainordinates can consist of
% triangulated surfaces or voxels in a regular 3-D volumetric grid. The functional
% data can consist of a dense or a parcellated representation. Furthermore, it
% writes the geometrical description of the surfaces to one or multiple gifti
% files.
%
% Use as
% ft_write_cifti(filename, data, ...)
% where the filename is a string and the data according to the description below.
%
% If the input data describes a dense representation of functional data, the data
% structure should conform to the FT_DATATYPE_SOURCE or FT_DATATYPE_VOLUME
% definition.
%
% If the input data describes a parcellated representation of functional data, the
% data structure should conform to the FT_DATATYPE_TIMELOCK or FT_DATATYPE_FREQ
% definition. In addition, the description of the geometry should be specified in
% the data.brainordinate field, which should conform to the FT_DATATYPE_SOURCE or
% FT_DATATYPE_VOLUME definition.
%
% Any optional input arguments should come in key-value pairs and may include
% 'parameter' = string, fieldname that contains the functional data
% 'brainstructure' = string, fieldname that describes the brain structures (default = 'brainstructure')
% 'parcellation' = string, fieldname that describes the parcellation (default = 'parcellation')
% 'precision' = string, can be 'single', 'double', 'int32', etc. (default ='single')
% 'writesurface' = boolean, can be false or true (default = true)
% 'debug' = boolean, write a debug.xml file (default = false)
%
% The brainstructure refers to the global anatomical structure, such as CortexLeft, Thalamus, etc.
% The parcellation refers to the the detailled parcellation, such as BA1, BA2, BA3, etc.
%
% See also FT_READ_CIFTI, FT_READ_MRI, FT_WRITE_MRI
% Copyright (C) 2013-2015, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_write_cifti.m 10393 2015-05-08 08:06:57Z roboos $
parameter = ft_getopt(varargin, 'parameter');
brainstructure = ft_getopt(varargin, 'brainstructure'); % the default is determined further down
parcellation = ft_getopt(varargin, 'parcellation'); % the default is determined further down
precision = ft_getopt(varargin, 'precision', 'single');
writesurface = ft_getopt(varargin, 'writesurface', true);
debug = ft_getopt(varargin, 'debug', false);
if isfield(source, 'brainordinate')
% this applies to a parcellated data representation
% copy the geometrical description over in to the main structure
source = copyfields(source.brainordinate, source, fieldnames(source.brainordinate));
source = rmfield(source, 'brainordinate');
end
if isempty(brainstructure) && isfield(source, 'brainstructure') && isfield(source, 'brainstructurelabel')
% these fields are asumed to be present from ft_read_cifti
brainstructure = 'brainstructure';
end
if isempty(parcellation) && isfield(source, 'parcellation') && isfield(source, 'parcellationlabel')
% these fields are asumed to be present from ft_read_cifti
parcellation = 'parcellation';
end
if isfield(source, 'inside') && islogical(source.inside)
% convert into an indexed representation
source.inside = find(source.inside(:));
end
if isfield(source, 'dim') && ~isfield(source, 'transform')
% ensure that the volumetric description contains both dim and transform
source.transform = pos2transform(source.pos);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% get the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
dat = source.(parameter);
dimord = getdimord(source, parameter);
switch dimord
case {'pos' 'pos_scalar'}
% NIFTI_INTENT_CONNECTIVITY_DENSE_SCALARS
extension = '.dscalar.nii';
intent_code = 3006;
intent_name = 'ConnDenseScalar';
dat = transpose(dat);
dimord = 'scalar_pos';
case 'pos_pos'
% NIFTI_INTENT_CONNECTIVITY_DENSE
extension = '.dconn.nii';
intent_code = 3001;
intent_name = 'ConnDense';
case 'pos_time'
% NIFTI_INTENT_CONNECTIVITY_DENSE_SERIES
extension = '.dtseries.nii';
intent_code = 3002;
intent_name = 'ConnDenseSeries';
dat = transpose(dat);
dimord = 'time_pos';
case 'pos_freq'
% NIFTI_INTENT_CONNECTIVITY_DENSE_SERIES
extension = '.dtseries.nii';
intent_code = 3002;
intent_name = 'ConnDenseSeries';
dat = transpose(dat);
dimord = 'freq_pos';
case {'chan' 'chan_scalar'}
% NIFTI_INTENT_CONNECTIVITY_PARCELLATED_SCALARS
extension = '.pscalar.nii';
intent_code = 3006;
intent_name = 'ConnParcelScalr'; % due to length constraints of the NIfTI header field, the last "a" is removed
dat = transpose(dat);
dimord = 'scalar_chan';
case 'chan_chan'
% NIFTI_INTENT_CONNECTIVITY_PARCELLATED
extension = '.pconn.nii';
intent_code = 3003;
intent_name = 'ConnParcels';
case 'chan_time'
% NIFTI_INTENT_CONNECTIVITY_PARCELLATED_SERIES
extension = '.ptseries.nii';
intent_code = 3004;
intent_name = 'ConnParcelSries'; % due to length constraints of the NIfTI header field, the first "e" is removed
dat = transpose(dat);
dimord = 'time_chan';
case 'chan_freq'
% NIFTI_INTENT_CONNECTIVITY_PARCELLATED_SERIES
extension = '.ptseries.nii';
intent_code = 3004;
intent_name = 'ConnParcelSries'; % due to length constraints of the NIfTI header field, the first "e" is removed
dat = transpose(dat);
dimord = 'freq_chan';
case {'chan_chan_time' 'chan_chan_freq'}
% NIFTI_INTENT_CONNECTIVITY_PARCELLATED_PARCELLATED_SERIES
extension = '.pconnseries.nii';
intent_code = 3011;
intent_name = 'ConnPPSr';
case {'pos_pos_time' 'pos_pos_freq'}
% this is not part of the Cifti v2 specification, but would have been NIFTI_INTENT_CONNECTIVITY_DENSE_DENSE_SERIES
extension = '.dconnseries.nii'; % user's choise
intent_code = 3000;
intent_name = 'ConnUnknown';
otherwise
error('unsupported dimord "%s"', dimord);
end % switch
% determine each of the dimensions
dimtok = tokenize(dimord, '_');
[p, f, x] = fileparts(filename);
if isequal(x, '.nii')
filename = fullfile(p, f); % strip the extension
end
[p, f, x] = fileparts(filename);
if any(isequal(x, {'.dtseries', '.ptseries', '.dconn', '.pconn', '.dscalar', '.pscalar'}))
filename = fullfile(p, f); % strip the extension
end
% add the full cifti extension to the filename
[p, f, x] = fileparts(filename);
filename = fullfile(p, [f x extension]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% get the description of the geometry
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ModelType = zeros(size(source.pos,1), 1);
ModelTypelabel = {'SURFACE', 'VOXEL'};
if isfield(source, 'transform')
tolerance = 0.01; % in milimeter
ijk = ft_warp_apply(inv(source.transform), source.pos); % convert from xyz to ijk
sel = sqrt(sum((ijk - round(ijk)).^2,2))<tolerance;
% note that some surface points might be marked as voxel if they happen to fall on a grid point
ModelType(~sel) = 1; % surface
ModelType( sel) = 2; % voxel
else
ModelType(:) = 1; % surface
end
if isfield(source, brainstructure)
BrainStructure = source.( brainstructure );
BrainStructurelabel = source.([brainstructure 'label']);
elseif isfield(source, 'pos')
BrainStructure = ones(size(source.pos,1),1);
BrainStructurelabel = {'INVALID'};
end
if isfield(source, parcellation)
Parcellation = source.( parcellation );
Parcellationlabel = source.([parcellation 'label']);
elseif isfield(source, 'pos')
Parcellation = ones(size(source.pos,1),1);
Parcellationlabel = {'INVALID'};
end
% ensure that these are column vectors
try, BrainStructure = BrainStructure(:); end
try, Parcellation = Parcellation(:); end
list1 = {
'CIFTI_STRUCTURE_CORTEX_LEFT'
'CIFTI_STRUCTURE_CORTEX_RIGHT'
'CIFTI_STRUCTURE_CEREBELLUM'
'CIFTI_STRUCTURE_ACCUMBENS_LEFT'
'CIFTI_STRUCTURE_ACCUMBENS_RIGHT'
'CIFTI_STRUCTURE_ALL_GREY_MATTER'
'CIFTI_STRUCTURE_ALL_WHITE_MATTER'
'CIFTI_STRUCTURE_AMYGDALA_LEFT'
'CIFTI_STRUCTURE_AMYGDALA_RIGHT'
'CIFTI_STRUCTURE_BRAIN_STEM'
'CIFTI_STRUCTURE_CAUDATE_LEFT'
'CIFTI_STRUCTURE_CAUDATE_RIGHT'
'CIFTI_STRUCTURE_CEREBELLAR_WHITE_MATTER_LEFT'
'CIFTI_STRUCTURE_CEREBELLAR_WHITE_MATTER_RIGHT'
'CIFTI_STRUCTURE_CEREBELLUM_LEFT'
'CIFTI_STRUCTURE_CEREBELLUM_RIGHT'
'CIFTI_STRUCTURE_CEREBRAL_WHITE_MATTER_LEFT'
'CIFTI_STRUCTURE_CEREBRAL_WHITE_MATTER_RIGHT'
'CIFTI_STRUCTURE_CORTEX'
'CIFTI_STRUCTURE_DIENCEPHALON_VENTRAL_LEFT'
'CIFTI_STRUCTURE_DIENCEPHALON_VENTRAL_RIGHT'
'CIFTI_STRUCTURE_HIPPOCAMPUS_LEFT'
'CIFTI_STRUCTURE_HIPPOCAMPUS_RIGHT'
'CIFTI_STRUCTURE_INVALID'
'CIFTI_STRUCTURE_OTHER'
'CIFTI_STRUCTURE_OTHER_GREY_MATTER'
'CIFTI_STRUCTURE_OTHER_WHITE_MATTER'
'CIFTI_STRUCTURE_PALLIDUM_LEFT'
'CIFTI_STRUCTURE_PALLIDUM_RIGHT'
'CIFTI_STRUCTURE_PUTAMEN_LEFT'
'CIFTI_STRUCTURE_PUTAMEN_RIGHT'
'CIFTI_STRUCTURE_THALAMUS_LEFT'
'CIFTI_STRUCTURE_THALAMUS_RIGHT'
};
list2 = {
'CORTEX_LEFT'
'CORTEX_RIGHT'
'CEREBELLUM'
'ACCUMBENS_LEFT'
'ACCUMBENS_RIGHT'
'ALL_GREY_MATTER'
'ALL_WHITE_MATTER'
'AMYGDALA_LEFT'
'AMYGDALA_RIGHT'
'BRAIN_STEM'
'CAUDATE_LEFT'
'CAUDATE_RIGHT'
'CEREBELLAR_WHITE_MATTER_LEFT'
'CEREBELLAR_WHITE_MATTER_RIGHT'
'CEREBELLUM_LEFT'
'CEREBELLUM_RIGHT'
'CEREBRAL_WHITE_MATTER_LEFT'
'CEREBRAL_WHITE_MATTER_RIGHT'
'CORTEX'
'DIENCEPHALON_VENTRAL_LEFT'
'DIENCEPHALON_VENTRAL_RIGHT'
'HIPPOCAMPUS_LEFT'
'HIPPOCAMPUS_RIGHT'
'INVALID'
'OTHER'
'OTHER_GREY_MATTER'
'OTHER_WHITE_MATTER'
'PALLIDUM_LEFT'
'PALLIDUM_RIGHT'
'PUTAMEN_LEFT'
'PUTAMEN_RIGHT'
'THALAMUS_LEFT'
'THALAMUS_RIGHT'
};
% replace the short name with the long name, i.e add 'CIFTI_STRUCTURE_' where applicable
[dum, indx1, indx2] = intersect(BrainStructurelabel, list2);
BrainStructurelabel(indx1) = list1(indx2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% construct the XML object describing the geometry
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ensure that the external toolbox is present, this adds gifti/@xmltree
ft_hastoolbox('gifti', 1);
tree = xmltree;
tree = set(tree, 1, 'name', 'CIFTI');
tree = attributes(tree, 'add', find(tree, 'CIFTI'), 'Version', '2');
tree = add(tree, find(tree, 'CIFTI'), 'element', 'Matrix');
% The cifti file contains one Matrix, which contains one or multiple MatrixIndicesMap, each containing
% CIFTI_INDEX_TYPE_BRAIN_MODELS The dimension represents one or more brain models.
% CIFTI_INDEX_TYPE_PARCELS The dimension represents a parcellation scheme.
% CIFTI_INDEX_TYPE_SERIES The dimension represents a series of regular samples.
% CIFTI_INDEX_TYPE_SCALARS The dimension represents named scalar maps.
% CIFTI_INDEX_TYPE_LABELS The dimension represents named label maps.
if any(strcmp(dimtok, 'time'))
% construct the MatrixIndicesMap for the time axis in the data
% NumberOfSeriesPoints="2" SeriesExponent="0" SeriesStart="0.0000000000" SeriesStep="1.0000000000" SeriesUnit="SECOND"
tree = add(tree, find(tree, 'CIFTI/Matrix'), 'element', 'MatrixIndicesMap');
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap');
branch = branch(end);
if length(source.time)>1
SeriesStep = median(diff(source.time)); % this assumes evenly spaced samples
else
SeriesStep = 0;
end
tree = attributes(tree, 'add', branch, 'AppliesToMatrixDimension', printwithcomma(find(strcmp(dimtok, 'time'))-1));
tree = attributes(tree, 'add', branch, 'IndicesMapToDataType', 'CIFTI_INDEX_TYPE_SERIES');
tree = attributes(tree, 'add', branch, 'NumberOfSeriesPoints', num2str(length(source.time)));
tree = attributes(tree, 'add', branch, 'SeriesExponent', num2str(0));
tree = attributes(tree, 'add', branch, 'SeriesStart', num2str(source.time(1)));
tree = attributes(tree, 'add', branch, 'SeriesStep', num2str(SeriesStep));
tree = attributes(tree, 'add', branch, 'SeriesUnit', 'SECOND');
end % if time
if any(strcmp(dimtok, 'freq'))
% construct the MatrixIndicesMap for the frequency axis in the data
% NumberOfSeriesPoints="2" SeriesExponent="0" SeriesStart="0.0000000000" SeriesStep="1.0000000000" SeriesUnit="HZ"
tree = add(tree, find(tree, 'CIFTI/Matrix'), 'element', 'MatrixIndicesMap');
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap');
branch = branch(end);
if length(source.freq)>1
SeriesStep = median(diff(source.freq)); % this assumes evenly spaced samples
else
SeriesStep = 0;
end
tree = attributes(tree, 'add', branch, 'AppliesToMatrixDimension', printwithcomma(find(strcmp(dimtok, 'freq'))-1));
tree = attributes(tree, 'add', branch, 'IndicesMapToDataType', 'CIFTI_INDEX_TYPE_SCALARS');
tree = attributes(tree, 'add', branch, 'NumberOfSeriesPoints', num2str(length(source.freq)));
tree = attributes(tree, 'add', branch, 'SeriesExponent', num2str(0));
tree = attributes(tree, 'add', branch, 'SeriesStart', num2str(source.freq(1)));
tree = attributes(tree, 'add', branch, 'SeriesStep', num2str(SeriesStep));
tree = attributes(tree, 'add', branch, 'SeriesUnit', 'HZ');
end % if freq
if any(strcmp(dimtok, 'scalar'))
tree = add(tree, find(tree, 'CIFTI/Matrix'), 'element', 'MatrixIndicesMap');
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap');
branch = branch(end);
tree = attributes(tree, 'add', branch, 'AppliesToMatrixDimension', printwithcomma(find(strcmp(dimtok, 'scalar'))-1));
tree = attributes(tree, 'add', branch, 'IndicesMapToDataType', 'CIFTI_INDEX_TYPE_SCALARS');
tree = add(tree, branch, 'element', 'NamedMap');
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/NamedMap');
branch = branch(end);
[tree, uid] = add(tree, branch, 'element', 'MapName');
tree = add(tree, uid, 'chardata', parameter);
end % if not freq and time
if any(strcmp(dimtok, 'pos'))
% construct the MatrixIndicesMap for the geometry
tree = add(tree, find(tree, 'CIFTI/Matrix'), 'element', 'MatrixIndicesMap');
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap');
branch = branch(end);
tree = attributes(tree, 'add', branch, 'AppliesToMatrixDimension', printwithcomma(find(strcmp(dimtok, 'pos'))-1));
tree = attributes(tree, 'add', branch, 'IndicesMapToDataType', 'CIFTI_INDEX_TYPE_BRAIN_MODELS');
if isfield(source, 'dim')
switch source.unit
case 'mm'
MeterExponent = -3;
case 'cm'
MeterExponent = -2;
case 'dm'
MeterExponent = -1;
case 'm'
MeterExponent = 0;
otherwise
error('unsupported source.unit')
end % case
[tree, uid] = add(tree, branch, 'element', 'Volume');
tree = attributes(tree, 'add', uid, 'VolumeDimensions', printwithcomma(source.dim));
[tree, uid] = add(tree, uid, 'element', 'TransformationMatrixVoxelIndicesIJKtoXYZ');
tree = attributes(tree, 'add', uid, 'MeterExponent', num2str(MeterExponent));
tree = add(tree, uid, 'chardata', printwithspace(source.transform')); % it needs to be transposed
end
for i=1:length(BrainStructurelabel)
% write one brainstructure for each group of vertices
if isempty(regexp(BrainStructurelabel{i}, '^CIFTI_STRUCTURE_', 'once'))
BrainStructurelabel{i} = ['CIFTI_STRUCTURE_' BrainStructurelabel{i}];
end
sel = (BrainStructure==i);
IndexCount = sum(sel);
IndexOffset = find(sel, 1, 'first') - 1; % zero offset
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap');
branch = branch(end);
tree = add(tree, branch, 'element', 'BrainModel');
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/BrainModel');
branch = branch(end);
if all(ModelType(sel)==find(strcmp(ModelTypelabel, 'VOXEL')))
tree = attributes(tree, 'add', branch, 'IndexOffset', printwithspace(IndexOffset));
tree = attributes(tree, 'add', branch, 'IndexCount', printwithspace(IndexCount));
tree = attributes(tree, 'add', branch, 'ModelType', 'CIFTI_MODEL_TYPE_VOXELS');
tree = attributes(tree, 'add', branch, 'BrainStructure', BrainStructurelabel{i});
tree = add(tree, branch, 'element', 'VoxelIndicesIJK');
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/BrainModel/VoxelIndicesIJK');
branch = branch(end);
tmp = source.pos(sel,:);
tmp = ft_warp_apply(inv(source.transform), tmp);
tmp = round(tmp)' - 1; % transpose, zero offset
tree = add(tree, branch, 'chardata', printwithspace(tmp));
else
tmp = find(sel)-IndexOffset-1; % zero offset
tree = attributes(tree, 'add', branch, 'IndexOffset', printwithspace(IndexOffset));
tree = attributes(tree, 'add', branch, 'IndexCount', printwithspace(IndexCount));
tree = attributes(tree, 'add', branch, 'ModelType', 'CIFTI_MODEL_TYPE_SURFACE');
tree = attributes(tree, 'add', branch, 'BrainStructure', BrainStructurelabel{i});
tree = attributes(tree, 'add', branch, 'SurfaceNumberOfVertices', printwithspace(IndexCount));
tree = add(tree, branch, 'element', 'VertexIndices');
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/BrainModel/VertexIndices');
branch = branch(end);
tree = add(tree, branch, 'chardata', printwithspace(tmp));
end
end % for each BrainStructurelabel
end % if pos
if any(strcmp(dimtok, 'chan'))
tree = add(tree, find(tree, 'CIFTI/Matrix'), 'element', 'MatrixIndicesMap');
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap');
branch = branch(end);
tree = attributes(tree, 'add', branch, 'AppliesToMatrixDimension', printwithcomma(find(strcmp(dimtok, 'chan'))-1));
tree = attributes(tree, 'add', branch, 'IndicesMapToDataType', 'CIFTI_INDEX_TYPE_PARCELS');
if isfield(source, 'dim')
switch source.unit
case 'mm'
MeterExponent = -3;
case 'cm'
MeterExponent = -2;
case 'dm'
MeterExponent = -1;
case 'm'
MeterExponent = 0;
otherwise
error('unsupported source.unit')
end % case
[tree, uid] = add(tree, branch, 'element', 'Volume');
tree = attributes(tree, 'add', uid, 'VolumeDimensions', printwithcomma(source.dim));
[tree, uid] = add(tree, uid, 'element', 'TransformationMatrixVoxelIndicesIJKtoXYZ');
tree = attributes(tree, 'add', uid, 'MeterExponent', num2str(MeterExponent));
tree = add(tree, uid, 'chardata', printwithspace(source.transform')); % it needs to be transposed
end
% surfaces are described with vertex positions (pos/pnt) and triangles (tri)
if isfield(source, 'pos') && isfield(source, 'tri')
% there is a surface description
for i=1:length(BrainStructurelabel)
sel = find(BrainStructure~=i);
[mesh.pnt, mesh.tri] = remove_vertices(source.pos, source.tri, sel);
mesh.unit = source.unit;
if isempty(mesh.pnt) || isempty(mesh.tri)
% the brainordinate positions in this brain structure are not connected with triangles, i.e. in the case of voxels
continue;
end
[tree, uid] = add(tree, branch, 'element', 'Surface');
tree = attributes(tree, 'add', uid, 'BrainStructure', BrainStructurelabel{i});
tree = attributes(tree, 'add', uid, 'SurfaceNumberOfVertices', printwithspace(size(mesh.pnt,1)));
end
end % if tri
parcel = source.label; % channels are used to represent parcels
for i=1:numel(parcel)
indx = find(strcmp(Parcellationlabel, parcel{i}));
if isempty(indx)
continue
end
selParcel = (Parcellation==indx);
structure = BrainStructurelabel(unique(BrainStructure(selParcel)));
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap');
branch = branch(end);
tree = add(tree, branch, 'element', 'Parcel');
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/Parcel');
branch = branch(end);
tree = attributes(tree, 'add', branch, 'Name', parcel{i});
% this is for pretty printing
maxparcellen = max(cellfun(@length, parcel));
for j=1:length(structure)
selStructure = (BrainStructure==find(strcmp(BrainStructurelabel, structure{j})));
indx = find(selParcel & selStructure);
offset = find(selStructure, 1, 'first') - 1;
fprintf('parcel %s contains %5d vertices in %s\n', stringpad(parcel{i}, maxparcellen), length(indx), structure{j});
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/Parcel');
branch = branch(end);
if all(ModelType(selStructure)==find(strcmp(ModelTypelabel, 'VOXEL')))
tree = add(tree, branch, 'element', 'VoxelIndicesIJK');
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/Parcel/VoxelIndicesIJK');
branch = branch(end);
tmp = ft_warp_apply(inv(source.transform), source.pos(indx,:));
tmp = round(tmp)' - 1; % transpose, zero offset
tree = add(tree, branch, 'chardata', printwithspace(tmp));
else
tree = add(tree, branch, 'element', 'Vertices');
branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/Parcel/Vertices');
branch = branch(end);
tree = attributes(tree, 'add', branch, 'BrainStructure', structure{j});
tmp = indx - offset - 1;
tree = add(tree, branch, 'chardata', printwithspace(tmp));
end
end % for each structure contained in this parcel
end % for each parcel
end % if chan
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% write everything to file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 4 bytes with the size of the header, 384 for nifti-1 or 540 for nifti-2
% 540 bytes with the nifti-2 header
% 4 bytes that indicate the presence of a header extension [1 0 0 0]
% 4 bytes with the size of the header extension in big endian?
% 4 bytes with the header extension code NIFTI_ECODE_CIFTI [0 0 0 32]
% variable number of bytes with the xml section, at the end there might be some empty "junk"
% 8 bytes, presumaby with the size and type?
% variable number of bytes with the voxel data
xmlfile = [tempname '.xml']; % this will contain the cifti XML structure
save(tree, xmlfile); % write the XMLTREE object to disk
xmlfid = fopen(xmlfile, 'rb');
xmldat = fread(xmlfid, [1, inf], 'char');
fclose(xmlfid);
% we do not want the content of the XML elements to be nicely formatted, as it might create confusion when reading
% therefore detect and remove whitespace immediately following a ">" and preceding a "<"
whitespace = false(size(xmldat));
gt = int8('>');
lt = int8('<');
ws = int8(sprintf(' \t\r\n'));
b = find(xmldat==gt);
e = find(xmldat==lt);
b = b(1:end-1); % the XML section ends with ">", this is not of relevance
e = e(2:end); % the XML section starts with "<", this is not of relevance
b = b+1;
e = e-1;
for i=1:length(b)
for j=b(i):1:e(i)
if any(ws==xmldat(j))
whitespace(j) = true;
else
break
end
end
end
for i=1:length(b)
for j=e(i):-1:b(i)
if any(ws==xmldat(j))
whitespace(j) = true;
else
break
end
end
end
% keep it if there is _only_ whitespace between the ">" and "<"
for i=1:length(b)
if all(whitespace(b(i):e(i)))
whitespace(b(i):e(i)) = false;
end
end
% remove the padding whitespace
xmldat = xmldat(~whitespace);
% the header extension needs to be aligned
xmlsize = length(xmldat);
xmlpad = ceil((xmlsize+8)/16)*16 - (xmlsize+8);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% construct the NIFTI-2 header
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
hdr.magic = [110 43 50 0 13 10 26 10];
% see http://nifti.nimh.nih.gov/nifti-1/documentation/nifti1fields/nifti1fields_pages/datatype.html
switch precision
case 'uint8'
hdr.datatype = 2;
case 'int16'
hdr.datatype = 4;
case 'int32'
hdr.datatype = 8;
case 'single'
hdr.datatype = 16;
case 'double'
hdr.datatype = 64;
case 'int8'
hdr.datatype = 256;
case 'uint16'
hdr.datatype = 512;
case 'uint32'
hdr.datatype = 768;
case 'uint64'
hdr.datatype = 1280;
case 'int64'
hdr.datatype = 1024;
otherwise
error('unsupported precision "%s"', precision);
end
switch precision
case {'uint8' 'int8'}
hdr.bitpix = 1*8;
case {'uint16' 'int16'}
hdr.bitpix = 2*8;
case {'uint32' 'int32'}
hdr.bitpix = 4*8;
case {'uint64' 'int64'}
hdr.bitpix = 8*8;
case 'single'
hdr.bitpix = 4*8;
case 'double'
hdr.bitpix = 8*8;
otherwise
error('unsupported precision "%s"', precision);
end
% dim(1) represents the number of dimensions
% for a normal nifti file, dim(2:4) are x, y, z, dim(5) is time
% cifti makes use of dim(6:8), which are free to choose
hdr.dim = [4+length(dimtok) 1 1 1 1 1 1 1];
% the nifti specification does not allow for more than 7 dimensions to be specified
assert(hdr.dim(1)<8);
for i=1:length(dimtok)
switch dimtok{i}
case 'pos'
hdr.dim(5+i) = size(source.pos,1);
case 'chan'
hdr.dim(5+i) = numel(source.label);
case 'time'
hdr.dim(5+i) = numel(source.time);
case 'freq'
hdr.dim(5+i) = numel(source.freq);
case 'scalar'
hdr.dim(5+i) = 1;
otherwise
error('unsupported dimord "%s"', dimord)
end
end
hdr.intent_p1 = 0;
hdr.intent_p2 = 0;
hdr.intent_p3 = 0;
hdr.pixdim = [0 1 1 1 1 1 1 1];
hdr.vox_offset = 4+540+8+xmlsize+xmlpad;
hdr.scl_slope = 1; % WorkBench sets scl_slope/scl_inter to 1 and 0, although 0 and 0 would also be fine - both mean the same thing according to the nifti spec
hdr.scl_inter = 0;
hdr.cal_max = 0;
hdr.cal_min = 0;
hdr.slice_duration = 0;
hdr.toffset = 0;
hdr.slice_start = 0;
hdr.slice_end = 0;
hdr.descrip = char(zeros(1,80));
hdr.aux_file = char(zeros(1,24));
hdr.qform_code = 0;
hdr.sform_code = 0;
hdr.quatern_b = 0;
hdr.quatern_c = 0;
hdr.quatern_d = 0;
hdr.qoffset_x = 0;
hdr.qoffset_y = 0;
hdr.qOffset_z = 0;
hdr.srow_x = [0 0 0 0];
hdr.srow_y = [0 0 0 0];
hdr.srow_z = [0 0 0 0];
hdr.slice_code = 0;
hdr.xyzt_units = 0;
hdr.intent_code = intent_code;
hdr.intent_name = cat(2, intent_name, zeros(1, 16-length(intent_name))); % zero-pad up to 16 characters
hdr.dim_info = 0;
hdr.unused_str = char(zeros(1,15));
% open the file
fid = fopen(filename, 'wb');
% write the header, this is 4+540 bytes
write_nifti2_hdr(fid, hdr);
if debug
try
% write the xml section to a temporary file for debugging
xmlfile = 'debug.xml';
tmp = fopen(xmlfile, 'w');
fwrite(tmp, xmldat, 'char');
fclose(tmp);
end
end
% write the cifti header extension
fwrite(fid, [1 0 0 0], 'uint8');
fwrite(fid, 8+xmlsize+xmlpad, 'int32'); % esize
fwrite(fid, 32, 'int32'); % etype
fwrite(fid, xmldat, 'char'); % write the ascii XML section
fwrite(fid, zeros(1,xmlpad), 'uint8'); % zero-pad to the next 16 byte boundary
% write the actual data
fwrite(fid, dat, precision);
fclose(fid);
% write the surfaces as gifti files
if writesurface && isfield(source, 'pos') && isfield(source, 'tri')
if isfield(source, brainstructure)
% it contains information about anatomical structures, including cortical surfaces
for i=1:length(BrainStructurelabel)
sel = find(BrainStructure~=i);
[mesh.pnt, mesh.tri] = remove_vertices(source.pos, source.tri, sel);
mesh.unit = source.unit;
if isempty(mesh.pnt) || isempty(mesh.tri)
% the brainordinate positions in this brain structure are not connected with triangles, i.e. in the case of voxels
continue;
end
if ~isempty(regexp(BrainStructurelabel{i}, '^CIFTI_STRUCTURE_', 'once'))
BrainStructurelabel{i} = BrainStructurelabel{i}(17:end);
end
[p, f, x] = fileparts(filename);
filetok = tokenize(f, '.');
surffile = fullfile(p, [filetok{1} '.' BrainStructurelabel{i} '.surf.gii']);
fprintf('writing %s surface to %s\n', BrainStructurelabel{i}, surffile);
ft_write_headshape(surffile, mesh, 'format', 'gifti');
end
else
mesh.pnt = source.pos;
mesh.tri = source.tri;
mesh.unit = source.unit;
[p, f, x] = fileparts(filename);
filetok = tokenize(f, '.');
surffile = fullfile(p, [filetok{1} '.surf.gii']);
ft_write_headshape(surffile, mesh, 'format', 'gifti');
end
end % if writesurface and isfield tri
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to print lists of numbers with appropriate whitespace
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = printwithspace(x)
x = x(:)'; % convert to vector
if all(round(x)==x)
% print as integer value
s = sprintf('%d ', x);
else
% print as floating point value
s = sprintf('%f ', x);
end
s = s(1:end-1);
function s = printwithcomma(x)
x = x(:)'; % convert to vector
if all(round(x)==x)
% print as integer value
s = sprintf('%d,', x);
else
% print as floating point value
s = sprintf('%f,', x);
end
s = s(1:end-1);
function s = stringpad(s, n)
while length(s)<n
s = [' ' s];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION from roboos/matlab/triangle
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [pntR, triR] = remove_vertices(pnt, tri, removepnt)
npnt = size(pnt,1);
ntri = size(tri,1);
if all(removepnt==0 | removepnt==1)
removepnt = find(removepnt);
end
% remove the vertices and determine the new numbering (indices) in numb
keeppnt = setdiff(1:npnt, removepnt);
numb = zeros(1,npnt);
numb(keeppnt) = 1:length(keeppnt);
% look for triangles referring to removed vertices
removetri = false(ntri,1);
removetri(ismember(tri(:,1), removepnt)) = true;
removetri(ismember(tri(:,2), removepnt)) = true;
removetri(ismember(tri(:,3), removepnt)) = true;
% remove the vertices and triangles
pntR = pnt(keeppnt, :);
triR = tri(~removetri,:);
% renumber the vertex indices for the triangles
triR = numb(triR);
|
github
|
ZijingMao/baselineeegtest-master
|
ft_chantype.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/ft_chantype.m
| 26,232 |
utf_8
|
5c1a68c24a12c393fb802cccb95458a3
|
function type = ft_chantype(input, desired)
% FT_CHANTYPE determines for each individual channel what type of data it
% represents, e.g. a planar gradiometer, axial gradiometer, magnetometer,
% trigger channel, etc. If you want to know what the acquisition system is
% (e.g. ctf151 or neuromag306), you should not use this function but
% FT_SENSTYPE instead.
%
% Use as
% type = ft_chantype(hdr)
% type = ft_chantype(sens)
% type = ft_chantype(label)
% or as
% type = ft_chantype(hdr, desired)
% type = ft_chantype(sens, desired)
% type = ft_chantype(label, desired)
%
% If the desired unit is not specified as second input argument, this
% function returns a Nchan*1 cell-array with a string describing the type
% of each channel.
%
% If the desired unit is specified as second input argument, this function
% returns a Nchan*1 boolean vector with "true" for the channels of the
% desired type and "false" for the ones that do not match.
%
% The specification of the channel types depends on the acquisition system,
% for example the ctf275 system includes the following type of channels:
% meggrad, refmag, refgrad, adc, trigger, eeg, headloc, headloc_gof.
%
% See also FT_READ_HEADER, FT_SENSTYPE, FT_CHANUNIT
% Copyright (C) 2008-2015, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_chantype.m 10516 2015-07-04 13:06:48Z roboos $
% these are for remembering the type on subsequent calls with the same input arguments
persistent previous_argin previous_argout
% this is to avoid a recursion loop
persistent recursion
if isempty(recursion)
recursion = false;
end
if nargin<2
desired = [];
end
% determine the type of input, this is handled similarly as in FT_CHANUNIT
isheader = isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'Fs');
isgrad = isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'pnt') && isfield(input, 'ori'); % old style
iselec = isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'pnt') && ~isfield(input, 'ori'); % old style
isgrad = (isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'coilpos')) || isgrad; % new style
iselec = (isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'elecpos')) || iselec; % new style
islabel = isa(input, 'cell') && ~isempty(input) && isa(input{1}, 'char');
if isheader
% this speeds up the caching in real-time applications
input.nSamples = 0;
end
current_argin = {input, desired};
if isequal(current_argin, previous_argin)
% don't do the type detection again, but return the previous output from cache
type = previous_argout{1};
return
end
if isheader
label = input.label;
numchan = length(label);
elseif isgrad
label = input.label;
numchan = length(label);
elseif iselec
label = input.label;
numchan = length(label);
elseif islabel
label = input;
numchan = length(label);
elseif isfield(input, 'label')
% this is a last resort: I don't know what it is, but perhaps the labels are informative
label = input.label;
numchan = length(label);
else
error('the input that was provided to this function cannot be deciphered');
end
if isfield(input, 'chantype')
% start with the provided channel types
type = input.chantype(:);
else
% start with unknown type for all channels
type = repmat({'unknown'}, numchan, 1);
end
if ft_senstype(input, 'unknown')
% don't bother doing all subsequent checks to determine the type of sensor array
elseif isheader && (ft_senstype(input, 'neuromag') || ft_senstype(input, 'babysquid74'))
% channames-KI is the channel kind, 1=meg, 202=eog, 2=eeg, 3=trigger (I am not sure, but have inferred this from a single test file)
% chaninfo-TY is the Coil type (0=magnetometer, 1=planar gradiometer)
if isfield(input, 'orig') && isfield(input.orig, 'channames')
for sel=find(input.orig.channames.KI(:)==202)'
type{sel} = 'eog';
end
for sel=find(input.orig.channames.KI(:)==2)'
type{sel} = 'eeg';
end
for sel=find(input.orig.channames.KI(:)==3)'
type{sel} = 'digital trigger';
end
% determine the MEG channel subtype
selmeg=find(input.orig.channames.KI(:)==1)';
for i=1:length(selmeg)
if input.orig.chaninfo.TY(i)==0
type{selmeg(i)} = 'megmag';
elseif input.orig.chaninfo.TY(i)==1
% FIXME this might also be a axial gradiometer in case the BabySQUID data is read with the old reading routines
type{selmeg(i)} = 'megplanar';
end
end
elseif isfield(input, 'orig') && isfield(input.orig, 'chs') && isfield(input.orig.chs, 'coil_type')
% all the chs.kinds and chs.coil_types are obtained from the MNE manual, p.210-211
for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==2)' % planar gradiometers
type(sel) = {'megplanar'}; %Neuromag-122 planar gradiometer
end
for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==3012)' %planar gradiometers
type(sel) = {'megplanar'}; %Type T1 planar grad
end
for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==3013)' %planar gradiometers
type(sel) = {'megplanar'}; %Type T2 planar grad
end
for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==3014)' %planar gradiometers
type(sel) = {'megplanar'}; %Type T3 planar grad
end
for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==3022)' %magnetometers
type(sel) = {'megmag'}; %Type T1 magenetometer
end
for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==3023)' %magnetometers
type(sel) = {'megmag'}; %Type T2 magenetometer
end
for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==3024)' %magnetometers
type(sel) = {'megmag'}; %Type T3 magenetometer
end
for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==7001)' %axial gradiometer
type(sel) = {'megaxial'};
end
for sel=find([input.orig.chs.kind]==301)' %MEG reference channel, located far from head
type(sel) = {'ref'};
end
for sel=find([input.orig.chs.kind]==2)' %EEG channels
type(sel) = {'eeg'};
end
for sel=find([input.orig.chs.kind]==201)' %MCG channels
type(sel) = {'mcg'};
end
for sel=find([input.orig.chs.kind]==3)' %Stim channels
if any([input.orig.chs(sel).logno] == 101) %new systems: 101 (and 102, if enabled) are digital; low numbers are 'pseudo-analog' (if enabled)
type(sel([input.orig.chs(sel).logno] == 101)) = {'digital trigger'};
type(sel([input.orig.chs(sel).logno] == 102)) = {'digital trigger'};
type(sel([input.orig.chs(sel).logno] <= 32)) = {'analog trigger'};
others = [input.orig.chs(sel).logno] > 32 & [input.orig.chs(sel).logno] ~= 101 & ...
[input.orig.chs(sel).logno] ~= 102;
type(sel(others)) = {'other trigger'};
elseif any([input.orig.chs(sel).logno] == 14) %older systems: STI 014/015/016 are digital; lower numbers 'pseudo-analog'(if enabled)
type(sel([input.orig.chs(sel).logno] == 14)) = {'digital trigger'};
type(sel([input.orig.chs(sel).logno] == 15)) = {'digital trigger'};
type(sel([input.orig.chs(sel).logno] == 16)) = {'digital trigger'};
type(sel([input.orig.chs(sel).logno] <= 13)) = {'analog trigger'};
others = [input.orig.chs(sel).logno] > 16;
type(sel(others)) = {'other trigger'};
else
warning('There does not seem to be a suitable trigger channel.');
type(sel) = {'other trigger'};
end
end
for sel=find([input.orig.chs.kind]==202)' %EOG
type(sel) = {'eog'};
end
for sel=find([input.orig.chs.kind]==302)' %EMG
type(sel) = {'emg'};
end
for sel=find([input.orig.chs.kind]==402)' %ECG
type(sel) = {'ecg'};
end
for sel=find([input.orig.chs.kind]==502)' %MISC
type(sel) = {'misc'};
end
for sel=find([input.orig.chs.kind]==602)' %Resp
type(sel) = {'respiration'};
end
end
elseif ft_senstype(input, 'babysquid74')
% the name can be something like "MEG 001" or "MEG001" or "MEG 0113" or "MEG0113"
% i.e. with two or three digits and with or without a space
sel = myregexp('^MEG', label);
type(sel) = {'megaxial'};
elseif ft_senstype(input, 'neuromag122')
% the name can be something like "MEG 001" or "MEG001" or "MEG 0113" or "MEG0113"
% i.e. with two or three digits and with or without a space
sel = myregexp('^MEG', label);
type(sel) = {'megplanar'};
elseif ft_senstype(input, 'neuromag306') && isgrad
% there should be 204 planar gradiometers and 102 axial magnetometers
if isfield(input, 'tra')
tmp = sum(abs(input.tra),2);
sel = (tmp==median(tmp));
type(sel) = {'megplanar'};
sel = (tmp~=median(tmp));
type(sel) = {'megmag'};
end
elseif ft_senstype(input, 'ctf') && isheader
% According to one source of information meg channels are 5, refmag 0,
% refgrad 1, adcs 18, trigger 11, eeg 9.
%
% According to another source of information it is as follows
% refMagnetometers: 0
% refGradiometers: 1
% meg_sens: 5
% eeg_sens: 9
% adc: 10
% stim_ref: 11
% video_time: 12
% sam: 15
% virtual_channels: 16
% sclk_ref: 17
% start with an empty one
origSensType = [];
if isfield(input, 'orig')
if isfield(input.orig, 'sensType') && isfield(input.orig, 'Chan')
% the header was read using the open-source MATLAB code that originates from CTF and that was modified by the FCDC
origSensType = input.orig.sensType;
elseif isfield(input.orig, 'res4') && isfield(input.orig.res4, 'senres')
% the header was read using the CTF p-files, i.e. readCTFds
origSensType = [input.orig.res4.senres.sensorTypeIndex];
elseif isfield(input.orig, 'sensor') && isfield(input.orig.sensor, 'info')
% the header was read using the CTF importer from the NIH and Daren Weber
origSensType = [input.orig.sensor.info.index];
end
end
if isempty(origSensType)
warning('could not determine channel type from the CTF header');
end
for sel=find(origSensType(:)==5)'
type{sel} = 'meggrad';
end
for sel=find(origSensType(:)==0)'
type{sel} = 'refmag';
end
for sel=find(origSensType(:)==1)'
type{sel} = 'refgrad';
end
for sel=find(origSensType(:)==18)'
type{sel} = 'adc';
end
for sel=find(origSensType(:)==11)'
type{sel} = 'trigger';
end
for sel=find(origSensType(:)==17)'
type{sel} = 'clock';
end
for sel=find(origSensType(:)==9)'
type{sel} = 'eeg';
end
for sel=find(origSensType(:)==29)'
type{sel} = 'reserved'; % these are "reserved for future use", but relate to head localization
end
for sel=find(origSensType(:)==13)'
type{sel} = 'headloc'; % these represent the x, y, z position of the head coils
end
for sel=find(origSensType(:)==28)'
type{sel} = 'headloc_gof'; % these represent the goodness of fit for the head coils
end
% for sel=find(origSensType(:)==23)'
% type{sel} = 'SPLxxxx'; % I have no idea what these are
% end
elseif ft_senstype(input, 'ctf') && isgrad
% in principle it is possible to look at the number of coils, but here the channels are identified based on their name
sel = myregexp('^M[ZLR][A-Z][0-9][0-9]$', input.label);
type(sel) = {'meggrad'}; % normal gradiometer channels
sel = myregexp('^S[LR][0-9][0-9]$', input.label);
type(sel) = {'meggrad'}; % normal gradiometer channels in the 64 channel CTF system
sel = myregexp('^B[GPQR][0-9]$', input.label);
type(sel) = {'refmag'}; % reference magnetometers
sel = myregexp('^[GPQR][0-9][0-9]$', input.label);
type(sel) = {'refgrad'}; % reference gradiometers
elseif ft_senstype(input, 'ctf') && islabel
% the channels have to be identified based on their name alone
sel = myregexp('^M[ZLR][A-Z][0-9][0-9]$', label);
type(sel) = {'meggrad'}; % normal gradiometer channels
sel = myregexp('^S[LR][0-9][0-9]$', label);
type(sel) = {'meggrad'}; % normal gradiometer channels in the 64 channel CTF system
sel = myregexp('^B[GPR][0-9]$', label);
type(sel) = {'refmag'}; % reference magnetometers
sel = myregexp('^[GPQR][0-9][0-9]$', label);
type(sel) = {'refgrad'}; % reference gradiometers
elseif ft_senstype(input, 'bti')
if isfield(input, 'orig') && isfield(input.orig, 'config')
configname = {input.orig.config.channel_data.name};
configtype = [input.orig.config.channel_data.type];
if ~isequal(configname(:), input.label(:))
% reorder the channels according to the order in input.label
[sel1, sel2] = match_str(input.label, configname);
configname = configname(sel2);
configtype = configtype(sel2);
configdata = input.orig.config.channel_data(sel2);
end
numloops = zeros(size(configdata));
for i=1:length(configdata)
if isfield(configdata(i).device_data, 'total_loops')
numloops(i) = configdata(i).device_data.total_loops;
end
end
% these are taken from bti2grad
type(configtype==1 & numloops==1) = {'megmag'};
type(configtype==1 & numloops==2) = {'meggrad'};
type(configtype==2) = {'eeg'};
type(configtype==3) = {'ref'}; % not known if mag or grad
type(configtype==4) = {'aux'};
type(configtype==5) = {'trigger'};
% refine the distinction between refmag and refgrad to make the types
% in grad and header consistent
sel = myregexp('^M[CLR][xyz][aA]*$', label);
type(sel) = {'refmag'};
sel = myregexp('^G[xyz][xyz]A$', label);
type(sel) = {'refgrad'};
else
% determine the type on the basis of the channel labels
% all 4D-BTi MEG channels start with "A" followed by a number
% all 4D-BTi reference channels start with M or G
% all 4D-BTi EEG channels start with E, except for the 248-MEG/32-EEG system in Warsaw where they end with -1
sel = myregexp('^A[0-9]+$', label);
type(sel) = {'meg'};
sel = myregexp('^M[CLR][xyz][aA]*$', label);
type(sel) = {'refmag'};
sel = myregexp('^G[xyz][xyz]A$', label);
type(sel) = {'refgrad'};
if isgrad && isfield(input, 'tra')
gradtype = repmat({'unknown'}, size(input.label));
gradtype(strncmp('A', input.label, 1)) = {'meg'};
gradtype(strncmp('M', input.label, 1)) = {'refmag'};
gradtype(strncmp('G', input.label, 1)) = {'refgrad'};
% look at the number of coils of the meg channels
selchan = find(strcmp('meg', gradtype));
for k = 1:length(selchan)
ncoils = length(find(input.tra(selchan(k),:)==1));
if ncoils==1,
gradtype{selchan(k)} = 'megmag';
elseif ncoils==2,
gradtype{selchan(k)} = 'meggrad';
end
end
[selchan, selgrad] = match_str(label, input.label);
type(selchan) = gradtype(selgrad);
end
% deal with additional channel types based on the names
if isheader && issubfield(input, 'orig.channel_data.chan_label')
tmplabel = {input.orig.channel_data.chan_label};
tmplabel = tmplabel(:);
else
tmplabel = label; % might work
end
sel = find(strcmp('unknown', type));
if ~isempty(sel)
type(sel) = ft_chantype(tmplabel(sel));
sel = find(strcmp('unknown', type));
if ~isempty(sel)
% channels that start with E are assumed to be EEG
% channels that end with -1 are also assumed to be EEG, see http://bugzilla.fcdonders.nl/show_bug.cgi?id=2389
type(sel(cellfun(@(x) strcmp(x(end-1:end),'-1') || strcmp(x(1),'E'), label(sel)))) = {'eeg'};
end
end
end
elseif ft_senstype(input, 'itab') && isheader
origtype = [input.orig.ch.type];
type(origtype==0) = {'unknown'};
type(origtype==1) = {'ele'};
type(origtype==2) = {'mag'}; % might be magnetometer or gradiometer, look at the number of coils
type(origtype==4) = {'ele ref'};
type(origtype==8) = {'mag ref'};
type(origtype==16) = {'aux'};
type(origtype==32) = {'param'};
type(origtype==64) = {'digit'};
type(origtype==128) = {'flag'};
% these are the channels that are visible to fieldtrip
chansel = 1:input.orig.nchan;
type = type(chansel);
elseif ft_senstype(input, 'yokogawa') && isheader
% This is to recognize Yokogawa channel types from the original header
% This is from the original documentation
NullChannel = 0;
MagnetoMeter = 1;
AxialGradioMeter = 2;
PlannerGradioMeter = 3;
RefferenceChannelMark = hex2dec('0100');
RefferenceMagnetoMeter = bitor( RefferenceChannelMark, MagnetoMeter );
RefferenceAxialGradioMeter = bitor( RefferenceChannelMark, AxialGradioMeter );
RefferencePlannerGradioMeter = bitor( RefferenceChannelMark, PlannerGradioMeter);
TriggerChannel = -1;
EegChannel = -2;
EcgChannel = -3;
EtcChannel = -4;
if ft_hastoolbox('yokogawa_meg_reader')
% shorten names
ch_info = input.orig.channel_info.channel;
type_orig = [ch_info.type];
sel = (type_orig == NullChannel);
type(sel) = {'null'};
sel = (type_orig == MagnetoMeter);
type(sel) = {'megmag'};
sel = (type_orig == AxialGradioMeter);
type(sel) = {'meggrad'};
sel = (type_orig == PlannerGradioMeter);
type(sel) = {'megplanar'};
sel = (type_orig == RefferenceMagnetoMeter);
type(sel) = {'refmag'};
sel = (type_orig == RefferenceAxialGradioMeter);
type(sel) = {'refgrad'};
sel = (type_orig == RefferencePlannerGradioMeter);
type(sel) = {'refplanar'};
sel = (type_orig == TriggerChannel);
type(sel) = {'trigger'};
sel = (type_orig == EegChannel);
type(sel) = {'eeg'};
sel = (type_orig == EcgChannel);
type(sel) = {'ecg'};
sel = (type_orig == EtcChannel);
type(sel) = {'etc'};
elseif ft_hastoolbox('yokogawa')
sel = (input.orig.channel_info(:, 2) == NullChannel);
type(sel) = {'null'};
sel = (input.orig.channel_info(:, 2) == MagnetoMeter);
type(sel) = {'megmag'};
sel = (input.orig.channel_info(:, 2) == AxialGradioMeter);
type(sel) = {'meggrad'};
sel = (input.orig.channel_info(:, 2) == PlannerGradioMeter);
type(sel) = {'megplanar'};
sel = (input.orig.channel_info(:, 2) == RefferenceMagnetoMeter);
type(sel) = {'refmag'};
sel = (input.orig.channel_info(:, 2) == RefferenceAxialGradioMeter);
type(sel) = {'refgrad'};
sel = (input.orig.channel_info(:, 2) == RefferencePlannerGradioMeter);
type(sel) = {'refplanar'};
sel = (input.orig.channel_info(:, 2) == TriggerChannel);
type(sel) = {'trigger'};
sel = (input.orig.channel_info(:, 2) == EegChannel);
type(sel) = {'eeg'};
sel = (input.orig.channel_info(:, 2) == EcgChannel);
type(sel) = {'ecg'};
sel = (input.orig.channel_info(:, 2) == EtcChannel);
type(sel) = {'etc'};
end
elseif ft_senstype(input, 'yokogawa') && isgrad
% all channels in the gradiometer definition are meg
% type(1:end) = {'meg'};
% channels are identified based on their name: only magnetic as isgrad==1
sel = myregexp('^M[0-9][0-9][0-9]$', input.label);
type(sel) = {'megmag'};
sel = myregexp('^AG[0-9][0-9][0-9]$', input.label);
type(sel) = {'meggrad'};
sel = myregexp('^PG[0-9][0-9][0-9]$', input.label);
type(sel) = {'megplanar'};
sel = myregexp('^RM[0-9][0-9][0-9]$', input.label);
type(sel) = {'refmag'};
sel = myregexp('^RAG[0-9][0-9][0-9]$', input.label);
type(sel) = {'refgrad'};
sel = myregexp('^RPG[0-9][0-9][0-9]$', input.label);
type(sel) = {'refplanar'};
elseif ft_senstype(input, 'yokogawa') && islabel
% the yokogawa channel labels are a mess, so autodetection is not possible
% type(1:end) = {'meg'};
sel = myregexp('[0-9][0-9][0-9]$', label);
type(sel) = {'null'};
sel = myregexp('^M[0-9][0-9][0-9]$', label);
type(sel) = {'megmag'};
sel = myregexp('^AG[0-9][0-9][0-9]$', label);
type(sel) = {'meggrad'};
sel = myregexp('^PG[0-9][0-9][0-9]$', label);
type(sel) = {'megplanar'};
sel = myregexp('^RM[0-9][0-9][0-9]$', label);
type(sel) = {'refmag'};
sel = myregexp('^RAG[0-9][0-9][0-9]$', label);
type(sel) = {'refgrad'};
sel = myregexp('^RPG[0-9][0-9][0-9]$', label);
type(sel) = {'refplanar'};
sel = myregexp('^TRIG[0-9][0-9][0-9]$', label);
type(sel) = {'trigger'};
sel = myregexp('^EEG[0-9][0-9][0-9]$', label);
type(sel) = {'eeg'};
sel = myregexp('^ECG[0-9][0-9][0-9]$', label);
type(sel) = {'ecg'};
sel = myregexp('^ETC[0-9][0-9][0-9]$', label);
type(sel) = {'etc'};
elseif ft_senstype(input, 'itab') && isheader
sel = ([input.orig.ch.type]==0);
type(sel) = {'unknown'};
sel = ([input.orig.ch.type]==1);
type(sel) = {'unknown'};
sel = ([input.orig.ch.type]==2);
type(sel) = {'megmag'};
sel = ([input.orig.ch.type]==8);
type(sel) = {'megref'};
sel = ([input.orig.ch.type]==16);
type(sel) = {'aux'};
sel = ([input.orig.ch.type]==64);
type(sel) = {'digital'};
% not all channels are actually processed by fieldtrip, so only return
% the types fopr the ones that read_header and read_data return
type = type(input.orig.chansel);
elseif ft_senstype(input, 'itab') && isgrad
% the channels have to be identified based on their name alone
sel = myregexp('^MAG_[0-9][0-9][0-9]$', label);
type(sel) = {'megmag'};
sel = myregexp('^MAG_[0-9][0-9]$', label); % for the itab28 system
type(sel) = {'megmag'};
sel = myregexp('^MAG_[0-9]$', label); % for the itab28 system
type(sel) = {'megmag'};
sel = myregexp('^REF_[0-9][0-9][0-9]$', label);
type(sel) = {'megref'};
sel = myregexp('^AUX.*$', label);
type(sel) = {'aux'};
elseif ft_senstype(input, 'itab') && islabel
% the channels have to be identified based on their name alone
sel = myregexp('^MAG_[0-9][0-9][0-9]$', label);
type(sel) = {'megmag'};
sel = myregexp('^REF_[0-9][0-9][0-9]$', label);
type(sel) = {'megref'};
sel = myregexp('^AUX.*$', label);
type(sel) = {'aux'};
elseif ft_senstype(input, 'eeg') && islabel
% use an external helper function to define the list with EEG channel names
type(match_str(label, ft_senslabel('eeg1005'))) = {'eeg'}; % this includes all channels from the 1010 and 1020 arrangement
type(match_str(label, ft_senslabel(ft_senstype(input)))) = {'eeg'}; % this will work for biosemi, egi and other detected channel arrangements
elseif ft_senstype(input, 'eeg') && iselec
% all channels in an electrode definition must be eeg channels
type(:) = {'eeg'};
elseif ft_senstype(input, 'eeg') && isheader
% use an external helper function to define the list with EEG channel names
type(match_str(input.label, ft_senslabel(ft_senstype(input)))) = {'eeg'};
elseif ft_senstype(input, 'plexon') && isheader
% this is a complete header that was read from a Plexon *.nex file using read_plexon_nex
for i=1:numchan
switch input.orig.VarHeader(i).Type
case 0
type{i} = 'spike';
case 1
type{i} = 'event';
case 2
type{i} = 'interval'; % Interval variables?
case 3
type{i} = 'waveform';
case 4
type{i} = 'population'; % Population variables ?
case 5
type{i} = 'analog';
otherwise
% keep the default 'unknown' type
end
end
end % ft_senstype
% if possible, set additional types based on channel labels
label2type = {
{'ecg', 'ekg'};
{'emg'};
{'eog', 'heog', 'veog'};
{'lfp'};
{'eeg'};
{'trigger', 'trig', 'dtrig'};
};
for i = 1:numel(label2type)
for j = 1:numel(label2type{i})
type(intersect(strmatch(label2type{i}{j}, lower(label)), find(strcmp(type, 'unknown')))) = label2type{i}(1);
end
end
if all(strcmp(type, 'unknown')) && ~recursion
% try whether only lowercase channel labels makes a difference
if islabel
recursion = true;
type = ft_chantype(lower(input));
recursion = false;
elseif isfield(input, 'label')
input.label = lower(input.label);
recursion = true;
type = ft_chantype(input);
recursion = false;
end
end
if all(strcmp(type, 'unknown')) && ~recursion
% try whether only uppercase channel labels makes a difference
if islabel
recursion = true;
type = ft_chantype(upper(input));
recursion = false;
elseif isfield(input, 'label')
input.label = upper(input.label);
recursion = true;
type = ft_chantype(input);
recursion = false;
end
end
if nargin>1
% return a boolean vector
if isequal(desired, 'meg') || isequal(desired, 'ref')
% only compare the first three characters, i.e. meggrad or megmag should match
type = strncmp(desired, type, 3);
else
type = strcmp(desired, type);
end
end
% remember the current input and output arguments, so that they can be
% reused on a subsequent call in case the same input argument is given
current_argout = {type};
previous_argin = current_argin;
previous_argout = current_argout;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function match = myregexp(pat, list)
match = false(size(list));
for i=1:numel(list)
match(i) = ~isempty(regexp(list{i}, pat, 'once'));
end
|
github
|
ZijingMao/baselineeegtest-master
|
ft_read_event.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/ft_read_event.m
| 79,562 |
utf_8
|
b69012deb686e2a6d94cb5dd67a0a09a
|
function [event] = ft_read_event(filename, varargin)
% FT_READ_EVENT reads all events from an EEG/MEG dataset and returns
% them in a well defined structure. It is a wrapper around different
% EEG/MEG file importers, directly supported formats are CTF, Neuromag,
% EEP, BrainVision, Neuroscan and Neuralynx.
%
% Use as
% [event] = ft_read_event(filename, ...)
%
% Additional options should be specified in key-value pairs and can be
% 'dataformat' string
% 'headerformat' string
% 'eventformat' string
% 'header' structure, see FT_READ_HEADER
% 'detectflank' string, can be 'bit', 'up', 'down', 'both' or 'auto' (default is system specific)
% 'chanindx' list with channel indices in case of different sampling frequencies (only for EDF)
% 'trigshift' integer, number of samples to shift from flank to detect trigger value (default = 0)
% 'trigindx' list with channel numbers for the trigger detection, only for Yokogawa (default is automatic)
% 'triglabel' list of channel labels for the trigger detection, only for Artinis oxy3-files (default is all ADC* channels)
% 'threshold' threshold for analog trigger channels (default is system specific)
% 'blocking' wait for the selected number of events (default = 'no')
% 'timeout' amount of time in seconds to wait when blocking (default = 5)
% 'tolerance' tolerance in samples when merging analogue trigger
% channels, only for Neuromag (default = 1,
% meaning that an offset of one sample in both directions
% is compensated for)
%
% Furthermore, you can specify optional arguments as key-value pairs
% for filtering the events, e.g. to select only events of a specific
% type, of a specific value, or events between a specific begin and
% end sample. This event filtering is especially usefull for real-time
% processing. See FT_FILTER_EVENT for more details.
%
% Some data formats have trigger channels that are sampled continuously with
% the same rate as the electrophysiological data. The default is to detect
% only the up-going TTL flanks. The trigger events will correspond with the
% first sample where the TTL value is up. This behaviour can be changed
% using the 'detectflank' option, which also allows for detecting the
% down-going flank or both. In case of detecting the down-going flank, the
% sample number of the event will correspond with the first sample at which
% the TTF went down, and the value will correspond to the TTL value just
% prior to going down.
%
% This function returns an event structure with the following fields
% event.type = string
% event.sample = expressed in samples, the first sample of a recording is 1
% event.value = number or string
% event.offset = expressed in samples
% event.duration = expressed in samples
% event.timestamp = expressed in timestamp units, which vary over systems (optional)
%
% The event type and sample fields are always defined, other fields can be empty,
% depending on the type of event file. Events are sorted by the sample on
% which they occur. After reading the event structure, you can use the
% following tricks to extract information about those events in which you
% are interested.
%
% Determine the different event types
% unique({event.type})
%
% Get the index of all trial events
% find(strcmp('trial', {event.type}))
%
% Make a vector with all triggers that occurred on the backpanel
% [event(find(strcmp('backpanel trigger', {event.type}))).value]
%
% Find the events that occurred in trial 26
% t=26; samples_trials = [event(find(strcmp('trial', {event.type}))).sample];
% find([event.sample]>samples_trials(t) & [event.sample]<samples_trials(t+1))
%
% The list of supported file formats can be found in FT_READ_HEADER.
%
% See also FT_READ_HEADER, FT_READ_DATA, FT_WRITE_EVENT, FT_FILTER_EVENT
% Copyright (C) 2004-2012 Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_read_event.m 10482 2015-06-24 14:05:09Z jorhor $
global event_queue % for fcdc_global
persistent sock % for fcdc_tcp
persistent db_blob % for fcdc_mysql
if isempty(db_blob)
db_blob = 0;
end
if iscell(filename)
ft_warning(sprintf('concatenating events from %d files', numel(filename)));
% use recursion to read events from multiple files
hdr = ft_getopt(varargin, 'header');
if isempty(hdr) || ~isfield(hdr, 'orig') || ~iscell(hdr.orig)
for i=1:numel(filename)
% read the individual file headers
hdr{i} = ft_read_header(filename{i}, varargin{:});
end
else
% use the individual file headers that were read previously
hdr = hdr.orig;
end
nsmp = nan(size(filename));
for i=1:numel(filename)
nsmp(i) = hdr{i}.nSamples*hdr{i}.nTrials;
end
offset = [0 cumsum(nsmp(1:end-1))];
event = cell(size(filename));
for i=1:numel(filename)
varargin = ft_setopt(varargin, 'header', hdr{i});
event{i} = ft_read_event(filename{i}, varargin{:});
for j=1:numel(event{i})
% add the offset due to the previous files
event{i}(j).sample = event{i}(j).sample + offset(i);
end
end
% return the concatenated events
event = appendevent(event{:});
return
end
% optionally get the data from the URL and make a temporary local copy
filename = fetch_url(filename);
% get the options
hdr = ft_getopt(varargin, 'header');
detectflank = ft_getopt(varargin, 'detectflank', 'up'); % up, down or both
trigshift = ft_getopt(varargin, 'trigshift'); % default is assigned in subfunction
trigindx = ft_getopt(varargin, 'trigindx'); % this allows to override the automatic trigger channel detection and is useful for Yokogawa
triglabel = ft_getopt(varargin, 'triglabel', 'ADC*'); % this allows subselection of AD channels to be markes as trigger channels (for Artinis oxy3 data)
headerformat = ft_getopt(varargin, 'headerformat');
dataformat = ft_getopt(varargin, 'dataformat');
threshold = ft_getopt(varargin, 'threshold'); % this is used for analog channels
tolerance = ft_getopt(varargin, 'tolerance', 1);
checkmaxfilter = ft_getopt(varargin, 'checkmaxfilter'); % will be passed to ft_read_header
eventformat = ft_getopt(varargin, 'eventformat');
chanindx = ft_getopt(varargin, 'chanindx'); % used for EDF files with variable sampling rate
if isempty(eventformat)
% only do the autodetection if the format was not specified
eventformat = ft_filetype(filename);
end
if iscell(eventformat)
% this happens for datasets specified as cell array for concatenation
eventformat = eventformat{1};
end
% this allows to read only events in a certain range, supported for selected data formats only
flt_type = ft_getopt(varargin, 'type');
flt_value = ft_getopt(varargin, 'value');
flt_minsample = ft_getopt(varargin, 'minsample');
flt_maxsample = ft_getopt(varargin, 'maxsample');
flt_mintimestamp = ft_getopt(varargin, 'mintimestamp');
flt_maxtimestamp = ft_getopt(varargin, 'maxtimestamp');
flt_minnumber = ft_getopt(varargin, 'minnumber');
flt_maxnumber = ft_getopt(varargin, 'maxnumber');
% thie allows blocking reads to avoid having to poll many times for online processing
blocking = ft_getopt(varargin, 'blocking', false); % true or false
timeout = ft_getopt(varargin, 'timeout', 5); % seconds
% convert from 'yes'/'no' into boolean
blocking = istrue(blocking);
if any(strcmp(eventformat, {'brainvision_eeg', 'brainvision_dat'}))
[p, f] = fileparts(filename);
filename = fullfile(p, [f '.vhdr']);
eventformat = 'brainvision_vhdr';
end
if strcmp(eventformat, 'brainvision_vhdr')
% read the headerfile belonging to the dataset and try to determine the corresponding markerfile
eventformat = 'brainvision_vmrk';
hdr = read_brainvision_vhdr(filename);
% replace the filename with the filename of the markerfile
if ~isfield(hdr, 'MarkerFile') || isempty(hdr.MarkerFile)
filename = [];
else
[p, f] = fileparts(filename);
filename = fullfile(p, hdr.MarkerFile);
end
end
% start with an empty event structure
event = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the events with the low-level reading function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch eventformat
case 'fcdc_global'
event = event_queue;
case {'4d' '4d_pdf', '4d_m4d', '4d_xyz'}
if isempty(hdr)
hdr = ft_read_header(filename, 'headerformat', eventformat);
end
% read the trigger channel and do flank detection
trgindx = match_str(hdr.label, 'TRIGGER');
if isfield(hdr, 'orig') && isfield(hdr.orig, 'config_data') && (strcmp(hdr.orig.config_data.site_name, 'Glasgow') || strcmp(hdr.orig.config_data.site_name, 'Marseille')),
trigger = read_trigger(filename, 'header', hdr, 'dataformat', '4d', 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trgindx, 'detectflank', detectflank, 'trigshift', trigshift, 'fix4d8192', true);
else
trigger = read_trigger(filename, 'header', hdr, 'dataformat', '4d', 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trgindx, 'detectflank', detectflank, 'trigshift', trigshift, 'fix4d8192', false);
end
event = appendevent(event, trigger);
respindx = match_str(hdr.label, 'RESPONSE');
if ~isempty(respindx)
response = read_trigger(filename, 'header', hdr, 'dataformat', '4d', 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', respindx, 'detectflank', detectflank, 'trigshift', trigshift);
event = appendevent(event, response);
end
case 'bci2000_dat'
% this requires the load_bcidat mex file to be present on the path
ft_hastoolbox('BCI2000', 1);
if isempty(hdr)
hdr = ft_read_header(filename);
end
if isfield(hdr.orig, 'signal') && isfield(hdr.orig, 'states')
% assume that the complete data is stored in the header, this speeds up subsequent read operations
signal = hdr.orig.signal;
states = hdr.orig.states;
parameters = hdr.orig.parameters;
total_samples = hdr.orig.total_samples;
else
[signal, states, parameters, total_samples] = load_bcidat(filename);
end
list = fieldnames(states);
% loop over all states and detect the flanks, the following code was taken from read_trigger
for i=1:length(list)
channel = list{i};
trig = double(getfield(states, channel));
pad = trig(1);
trigshift = 0;
begsample = 1;
switch detectflank
case 'up'
% convert the trigger into an event with a value at a specific sample
for j=find(diff([pad trig(:)'])>0)
event(end+1).type = channel;
event(end ).sample = j + begsample - 1; % assign the sample at which the trigger has gone down
event(end ).value = trig(j+trigshift); % assign the trigger value just _after_ going up
end
case 'down'
% convert the trigger into an event with a value at a specific sample
for j=find(diff([pad trig(:)'])<0)
event(end+1).type = channel;
event(end ).sample = j + begsample - 1; % assign the sample at which the trigger has gone down
event(end ).value = trig(j-1-trigshift); % assign the trigger value just _before_ going down
end
case 'both'
% convert the trigger into an event with a value at a specific sample
for j=find(diff([pad trig(:)'])>0)
event(end+1).type = [channel '_up']; % distinguish between up and down flank
event(end ).sample = j + begsample - 1; % assign the sample at which the trigger has gone down
event(end ).value = trig(j+trigshift); % assign the trigger value just _after_ going up
end
% convert the trigger into an event with a value at a specific sample
for j=find(diff([pad trig(:)'])<0)
event(end+1).type = [channel '_down']; % distinguish between up and down flank
event(end ).sample = j + begsample - 1; % assign the sample at which the trigger has gone down
event(end ).value = trig(j-1-trigshift); % assign the trigger value just _before_ going down
end
otherwise
error('incorrect specification of ''detectflank''');
end
end
case {'besa_avr', 'besa_swf'}
if isempty(hdr)
hdr = ft_read_header(filename);
end
event(end+1).type = 'average';
event(end ).sample = 1;
event(end ).duration = hdr.nSamples;
event(end ).offset = -hdr.nSamplesPre;
event(end ).value = [];
case {'biosemi_bdf', 'bham_bdf'}
% read the header, required to determine the stimulus channels and trial specification
if isempty(hdr)
hdr = ft_read_header(filename);
end
% specify the range to search for triggers, default is the complete file
if ~isempty(flt_minsample)
begsample = flt_minsample;
else
begsample = 1;
end
if ~isempty(flt_maxsample)
endsample = flt_maxsample;
else
endsample = hdr.nSamples*hdr.nTrials;
end
if ~strcmp(detectflank, 'up')
if strcmp(detectflank, 'both')
warning('only up-going flanks are supported for Biosemi');
detectflank = 'up';
else
error('only up-going flanks are supported for Biosemi');
% FIXME the next section on trigger detection should be merged with the
% READ_CTF_TRIGGER (which also does masking with bit-patterns) into the
% READ_TRIGGER function
end
end
% find the STATUS channel and read the values from it
schan = find(strcmpi(hdr.label,'STATUS'));
sdata = ft_read_data(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', begsample, 'endsample', endsample, 'chanindx', schan);
if ft_platform_supports('int32_logical_operations')
% convert to 32-bit integer representation and only preserve the lowest 24 bits
sdata = bitand(int32(sdata), 2^24-1);
else
% find indices of negative numbers
bit24i = find(sdata < 0);
% make number positive and preserve bits 0-22
sdata(bit24i) = bitcmp(abs(sdata(bit24i))-1,24);
% re-insert the sign bit on its original location, i.e. bit24
sdata(bit24i) = sdata(bit24i)+(2^(24-1));
% typecast the data to ensure that the status channel is represented in 32 bits
sdata = uint32(sdata);
end
byte1 = 2^8 - 1;
byte2 = 2^16 - 1 - byte1;
byte3 = 2^24 - 1 - byte1 - byte2;
% get the respective status and trigger bits
trigger = bitand(sdata, bitor(byte1, byte2)); % this is contained in the lower two bytes
epoch = int8(bitget(sdata, 16+1));
cmrange = int8(bitget(sdata, 20+1));
battery = int8(bitget(sdata, 22+1));
% determine when the respective status bits go up or down
flank_trigger = diff([0 trigger]);
flank_epoch = diff([0 epoch ]);
flank_cmrange = diff([0 cmrange]);
flank_battery = diff([0 battery]);
for i=find(flank_trigger>0)
event(end+1).type = 'STATUS';
event(end ).sample = i + begsample - 1;
event(end ).value = double(trigger(i));
end
for i=find(flank_epoch==1)
event(end+1).type = 'Epoch';
event(end ).sample = i;
end
for i=find(flank_cmrange==1)
event(end+1).type = 'CM_in_range';
event(end ).sample = i;
end
for i=find(flank_cmrange==-1)
event(end+1).type = 'CM_out_of_range';
event(end ).sample = i;
end
for i=find(flank_battery==1)
event(end+1).type = 'Battery_low';
event(end ).sample = i;
end
for i=find(flank_battery==-1)
event(end+1).type = 'Battery_ok';
event(end ).sample = i;
end
case {'biosig', 'gdf'}
% FIXME it would be nice to figure out how sopen/sread return events
% for all possible fileformats that can be processed with biosig
%
% This section of code is opaque with respect to the gdf file being a
% single file or the first out of a sequence with postfix _1, _2, ...
% because it uses private/read_trigger which again uses ft_read_data
if isempty(hdr)
hdr = ft_read_header(filename);
end
% the following applies to Biosemi data that is stored in the gdf format
statusindx = find(strcmp(hdr.label, 'STATUS'));
if length(statusindx)==1
% represent the rising flanks in the STATUS channel as events
event = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', statusindx, 'detectflank', 'up', 'trigshift', trigshift, 'fixbiosemi', true);
else
warning('BIOSIG does not have a consistent event representation, skipping events')
event = [];
end
case 'AnyWave'
event = read_ah5_markers(hdr, filename);
case 'brainvision_vmrk'
fid=fopen(filename,'rt');
if fid==-1,
error('cannot open BrainVision marker file')
end
line = [];
while ischar(line) || isempty(line)
line = fgetl(fid);
if ~isempty(line) && ~(isnumeric(line) && line==-1)
if strncmpi(line, 'Mk', 2)
% this line contains a marker
tok = tokenize(line, '=', 0); % do not squeeze repetitions of the separator
if length(tok)~=2
warning('skipping unexpected formatted line in BrainVision marker file');
else
% the line looks like "MkXXX=YYY", which is ok
% the interesting part now is in the YYY, i.e. the second token
tok = tokenize(tok{2}, ',', 0); % do not squeeze repetitions of the separator
if isempty(tok{1})
tok{1} = [];
end
if isempty(tok{2})
tok{2} = [];
end
event(end+1).type = tok{1};
event(end ).value = tok{2};
event(end ).sample = str2num(tok{3});
event(end ).duration = str2num(tok{4});
end
end
end
end
fclose(fid);
case 'ced_son'
% check that the required low-level toolbox is available
ft_hastoolbox('neuroshare', 1);
orig = read_ced_son(filename,'readevents','yes');
event = struct('type', {orig.events.type},...
'sample', {orig.events.sample},...
'value', {orig.events.value},...
'offset', {orig.events.offset},...
'duration', {orig.events.duration});
case 'ced_spike6mat'
if isempty(hdr)
hdr = ft_read_header(filename);
end
chanindx = [];
for i = 1:numel(hdr.orig)
if ~any(isfield(hdr.orig{i}, {'units', 'scale'}))
chanindx = [chanindx i];
end
end
if ~isempty(chanindx)
trigger = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', chanindx, 'detectflank', detectflank);
event = appendevent(event, trigger);
end
case {'ctf_ds', 'ctf_meg4', 'ctf_res4', 'ctf_old'}
% obtain the dataset name
if ft_filetype(filename, 'ctf_meg4') || ft_filetype(filename, 'ctf_res4')
filename = fileparts(filename);
end
[path, name, ext] = fileparts(filename);
headerfile = fullfile(path, [name ext], [name '.res4']);
datafile = fullfile(path, [name ext], [name '.meg4']);
classfile = fullfile(path, [name ext], 'ClassFile.cls');
markerfile = fullfile(path, [name ext], 'MarkerFile.mrk');
% in case ctf_old was specified as eventformat, the other reading functions should also know about that
if strcmp(eventformat, 'ctf_old')
dataformat = 'ctf_old';
headerformat = 'ctf_old';
end
% read the header, required to determine the stimulus channels and trial specification
if isempty(hdr)
hdr = ft_read_header(headerfile, 'headerformat', headerformat);
end
try
% read the trigger codes from the STIM channel, usefull for (pseudo) continuous data
% this splits the trigger channel into the lowers and highest 16 bits,
% corresponding with the front and back panel of the electronics cabinet at the Donders Centre
[backpanel, frontpanel] = read_ctf_trigger(filename);
for i=find(backpanel(:)')
event(end+1).type = 'backpanel trigger';
event(end ).sample = i;
event(end ).value = backpanel(i);
end
for i=find(frontpanel(:)')
event(end+1).type = 'frontpanel trigger';
event(end ).sample = i;
event(end ).value = frontpanel(i);
end
end
% determine the trigger channels from the header
if isfield(hdr, 'orig') && isfield(hdr.orig, 'sensType')
origSensType = hdr.orig.sensType;
elseif isfield(hdr, 'orig') && isfield(hdr.orig, 'res4')
origSensType = [hdr.orig.res4.senres.sensorTypeIndex];
else
origSensType = [];
end
% meg channels are 5, refmag 0, refgrad 1, adcs 18, trigger 11, eeg 9
trigindx = find(origSensType==11);
if ~isempty(trigindx)
% read the trigger channel and do flank detection
trigger = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trigindx, 'detectflank', detectflank, 'trigshift', trigshift, 'fixctf', true);
event = appendevent(event, trigger);
end
% read the classification file and make an event for each classified trial
[condNumbers,condLabels] = read_ctf_cls(classfile);
if ~isempty(condNumbers)
Ncond = length(condLabels);
for i=1:Ncond
for j=1:length(condNumbers{i})
event(end+1).type = 'classification';
event(end ).value = condLabels{i};
event(end ).sample = (condNumbers{i}(j)-1)*hdr.nSamples + 1;
event(end ).offset = -hdr.nSamplesPre;
event(end ).duration = hdr.nSamples;
end
end
end
if exist(markerfile,'file')
% read the marker file and make an event for each marker
% this depends on the readmarkerfile function that I got from Tom Holroyd
% I have not tested this myself extensively, since at the FCDC we
% don't use the marker files
mrk = readmarkerfile(filename);
for i=1:mrk.number_markers
for j=1:mrk.number_samples(i)
% determine the location of the marker, expressed in samples
trialnum = mrk.trial_times{i}(j,1);
synctime = mrk.trial_times{i}(j,2);
begsample = (trialnum-1)*hdr.nSamples + 1; % of the trial, relative to the start of the datafile
endsample = (trialnum )*hdr.nSamples; % of the trial, relative to the start of the datafile
offset = round(synctime*hdr.Fs); % this is the offset (in samples) relative to time t=0 for this trial
offset = offset + hdr.nSamplesPre; % and time t=0 corrsponds with the nSamplesPre'th sample
% store this marker as an event
event(end+1).type = mrk.marker_names{i};
event(end ).value = [];
event(end ).sample = begsample + offset;
event(end ).duration = 0;
event(end ).offset = offset;
end
end
end
case 'ctf_shm'
% contact Robert Oostenveld if you are interested in real-time acquisition on the CTF system
% read the events from shared memory
event = read_shm_event(filename, varargin{:});
case 'edf'
% EDF itself does not contain events, but EDF+ does define an annotation channel
if isempty(hdr)
hdr = ft_read_header(filename, 'chanindx', chanindx);
end
if issubfield(hdr, 'orig.annotation') && ~isempty(hdr.orig.annotation)
% read the data of the annotation channel as 16 bit
evt = read_edf(filename, hdr);
% undo the faulty calibration
evt = (evt - hdr.orig.Off(hdr.orig.annotation)) ./ hdr.orig.Cal(hdr.orig.annotation);
% convert the 16 bit format into the separate bytes
evt = typecast(int16(evt), 'uint8');
% construct the Time-stamped Annotations Lists (TAL), see http://www.edfplus.info/specs/edfplus.html#tal
tal = tokenize(char(evt), char(0), true);
event = [];
for i=1:length(tal)
% the unprintable characters 20 and 21 are used as separators between time, duration and the annotation
% duration can be skipped in which case its preceding 21 must also be skipped
tok = tokenize(tal{i}, char(20)); % split time and annotation
if any(tok{1}==21)
% the time and duration are specified
dum = tokenize(tok{1}, char(21)); % split time and duration
time = str2double(dum{1});
duration = str2double(dum{2});
else
% only the time is specified
time = str2double(tok{1});
duration = [];
end
% there can be multiple annotations per time, the last cell is always empty
for j=2:length(tok)-1
anot = char(tok{j});
% represent the annotation as event
event(end+1).type = 'annotation';
event(end ).value = anot;
event(end ).sample = round(time*hdr.Fs) + 1; % expressed in samples, first sample in the file is 1
event(end ).duration = round(duration*hdr.Fs); % expressed in samples
event(end ).offset = 0;
end
end
else
event = [];
end
case 'eeglab_set'
if isempty(hdr)
hdr = ft_read_header(filename);
end
event = read_eeglabevent(filename, 'header', hdr);
case 'eeglab_erp'
if isempty(hdr)
hdr = ft_read_header(filename);
end
event = read_erplabevent(filename, 'header', hdr);
case 'spmeeg_mat'
if isempty(hdr)
hdr = ft_read_header(filename);
end
event = read_spmeeg_event(filename, 'header', hdr);
case 'eep_avr'
% check that the required low-level toolbox is available
ft_hastoolbox('eeprobe', 1);
% the headerfile and datafile are the same
if isempty(hdr)
hdr = ft_read_header(filename);
end
event(end+1).type = 'average';
event(end ).sample = 1;
event(end ).duration = hdr.nSamples;
event(end ).offset = -hdr.nSamplesPre;
event(end ).value = [];
case {'eep_cnt' 'eep_trg'}
% check that the required low-level toolbox is available
ft_hastoolbox('eeprobe', 1);
% this requires the header from the cnt file and the triggers from the trg file
if strcmp(eventformat, 'eep_cnt')
trgfile = [filename(1:(end-3)), 'trg'];
cntfile = filename;
elseif strcmp(eventformat, 'eep_trg')
cntfile = [filename(1:(end-3)), 'cnt'];
trgfile = filename;
end
if exist(trgfile, 'file')
trg = read_eep_trg(trgfile);
else
warning('The corresponding "%s" file was not found, cannot read in trigger information. No events can be read in.', trgfile);
trg = []; % make it empty, needed below
end
if isempty(hdr)
if exist(cntfile, 'file')
hdr = ft_read_header(cntfile);
else
warning('The corresponding "%s" file was not found, cannot read in header information. No events can be read in.', cntfile);
hdr = []; % remains empty, needed below
end
end
if ~isempty(trg) && ~isempty(hdr)
if filetype_check_header(filename, 'RIFF')
scaler = 1000; % for 32-bit files from ASAlab triggers are in miliseconds
elseif filetype_check_header(filename, 'RF64');
scaler = 1; % for 64-bit files from ASAlab triggers are in seconds
end
% translate the EEProbe trigger codes to events
for i=1:length(trg)
event(i).type = 'trigger';
event(i).sample = round((trg(i).time/scaler) * hdr.Fs) + 1; % convert from ms to samples
event(i).value = trg(i).code;
event(i).offset = 0;
event(i).duration = 0;
end
end
case 'egi_egis'
if isempty(hdr)
hdr = ft_read_header(filename);
end
fhdr = hdr.orig.fhdr;
chdr = hdr.orig.chdr;
ename = hdr.orig.ename;
cnames = hdr.orig.cnames;
fcom = hdr.orig.fcom;
ftext = hdr.orig.ftext;
eventCount=0;
for cel=1:fhdr(18)
for trial=1:chdr(cel,2)
eventCount=eventCount+1;
event(eventCount).type = 'trial';
event(eventCount).sample = (eventCount-1)*hdr.nSamples + 1;
event(eventCount).offset = -hdr.nSamplesPre;
event(eventCount).duration = hdr.nSamples;
event(eventCount).value = cnames{cel};
end
end
case 'egi_egia'
if isempty(hdr)
hdr = ft_read_header(filename);
end
fhdr = hdr.orig.fhdr;
chdr = hdr.orig.chdr;
ename = hdr.orig.ename;
cnames = hdr.orig.cnames;
fcom = hdr.orig.fcom;
ftext = hdr.orig.ftext;
eventCount=0;
for cel=1:fhdr(18)
for subject=1:chdr(cel,2)
eventCount=eventCount+1;
event(eventCount).type = 'trial';
event(eventCount).sample = (eventCount-1)*hdr.nSamples + 1;
event(eventCount).offset = -hdr.nSamplesPre;
event(eventCount).duration = hdr.nSamples;
event(eventCount).value = ['Sub' sprintf('%03d',subject) cnames{cel}];
end
end
case 'egi_sbin'
if ~exist('segHdr','var')
[EventCodes, segHdr, eventData] = read_sbin_events(filename);
end
if ~exist('header_array','var')
[header_array, CateNames, CatLengths, preBaseline] = read_sbin_header(filename);
end
if isempty(hdr)
hdr = ft_read_header(filename,'headerformat','egi_sbin');
end
version = header_array(1);
unsegmented = ~mod(version, 2);
eventCount=0;
if unsegmented
[evType,sampNum] = find(eventData);
for k = 1:length(evType)
event(k).sample = sampNum(k);
event(k).offset = [];
event(k).duration = 0;
event(k).type = 'trigger';
event(k).value = char(EventCodes(evType(k),:));
end
else
for theEvent=1:size(eventData,1)
for segment=1:hdr.nTrials
if any(eventData(theEvent,((segment-1)*hdr.nSamples +1):segment*hdr.nSamples))
eventCount=eventCount+1;
event(eventCount).sample = min(find(eventData(theEvent,((segment-1)*hdr.nSamples +1):segment*hdr.nSamples))) +(segment-1)*hdr.nSamples;
event(eventCount).offset = -hdr.nSamplesPre;
event(eventCount).duration = length(find(eventData(theEvent,((segment-1)*hdr.nSamples +1):segment*hdr.nSamples )>0))-1;
event(eventCount).type = 'trigger';
event(eventCount).value = char(EventCodes(theEvent,:));
end
end
end
end
if ~unsegmented
for segment=1:hdr.nTrials % cell information
eventCount=eventCount+1;
event(eventCount).type = 'trial';
event(eventCount).sample = (segment-1)*hdr.nSamples + 1;
event(eventCount).offset = -hdr.nSamplesPre;
event(eventCount).duration = hdr.nSamples;
event(eventCount).value = char([CateNames{segHdr(segment,1)}(1:CatLengths(segHdr(segment,1)))]);
end
end;
case {'egi_mff_v1' 'egi_mff'} % this is currently the default
% The following represents the code that was written by Ingrid, Robert
% and Giovanni to get started with the EGI mff dataset format. It might
% not support all details of the file formats.
% An alternative implementation has been provided by EGI, this is
% released as fieldtrip/external/egi_mff and referred further down in
% this function as 'egi_mff_v2'.
if isempty(hdr)
% use the corresponding code to read the header
hdr = ft_read_header(filename, 'headerformat', eventformat);
end
if ~usejava('jvm')
error('the xml2struct requires MATLAB to be running with the Java virtual machine (JVM)');
% an alternative implementation which does not require the JVM but runs much slower is
% available from http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0
end
% get event info from xml files
warning('off', 'MATLAB:REGEXP:deprecated') % due to some small code xml2struct
xmlfiles = dir( fullfile(filename, '*.xml'));
disp('reading xml files to obtain event info... This might take a while if many events/triggers are present')
if isempty(xmlfiles)
xml=struct([]);
else
xml=[];
end;
for i = 1:numel(xmlfiles)
if strcmpi(xmlfiles(i).name(1:6), 'Events')
fieldname = xmlfiles(i).name(1:end-4);
filename_xml = fullfile(filename, xmlfiles(i).name);
xml.(fieldname) = xml2struct(filename_xml);
end
end
warning('on', 'MATLAB:REGEXP:deprecated')
% construct info needed for FieldTrip Event
eventNames = fieldnames(xml);
begTime = hdr.orig.xml.info.recordTime;
begTime(11) = ' '; begTime(end-5:end) = [];
begSDV = datenum(begTime);
% find out if there are epochs in this dataset
if isfield(hdr.orig.xml,'epochs') && length(hdr.orig.xml.epochs) > 1
Msamp2offset = nan(2,size(hdr.orig.epochdef,1),1+max(hdr.orig.epochdef(:,2)-hdr.orig.epochdef(:,1)));
for iEpoch = 1:size(hdr.orig.epochdef,1)
nSampEpoch = hdr.orig.epochdef(iEpoch,2)-hdr.orig.epochdef(iEpoch,1)+1;
Msamp2offset(1,iEpoch,1:nSampEpoch) = hdr.orig.epochdef(iEpoch,1):hdr.orig.epochdef(iEpoch,2); %sample number in samples
Msamp2offset(2,iEpoch,1:nSampEpoch) = hdr.orig.epochdef(iEpoch,3):hdr.orig.epochdef(iEpoch,3)+nSampEpoch-1; %offset in samples
end
end
% construct event according to FieldTrip rules
eventCount = 0;
for iXml = 1:length(eventNames)
eval(['eventField=isfield(xml.' eventNames{iXml} ',''event'');'])
if eventField
for iEvent = 1:length(xml.(eventNames{iXml}))
eventTime = xml.(eventNames{iXml})(iEvent).event.beginTime;
eventTime(11) = ' '; eventTime(end-5:end) = [];
if strcmp('-',eventTime(21))
% event out of range (before recording started): do nothing.
else
eventSDV = datenum(eventTime);
eventOffset = round((eventSDV - begSDV)*24*60*60*hdr.Fs); %in samples, relative to start of recording
if eventOffset < 0
% event out of range (before recording started): do nothing
else
% calculate eventSample, relative to start of epoch
if isfield(hdr.orig.xml,'epochs') && length(hdr.orig.xml.epochs) > 1
SampIndex=[];
for iEpoch = 1:size(hdr.orig.epochdef,1)
[dum,dum2] = intersect(squeeze(Msamp2offset(2,iEpoch,:)), eventOffset);
if ~isempty(dum2)
EpochNum = iEpoch;
SampIndex = dum2;
end
end
if ~isempty(SampIndex)
eventSample = Msamp2offset(1,EpochNum,SampIndex);
else
eventSample=[]; %Drop event if past end of epoch
end;
else
eventSample = eventOffset+1;
end
if ~isempty(eventSample)
eventCount=eventCount+1;
event(eventCount).type = eventNames{iXml}(8:end);
event(eventCount).sample = eventSample;
event(eventCount).offset = 0;
event(eventCount).duration = str2double(xml.(eventNames{iXml})(iEvent).event.duration)./1000000000*hdr.Fs;
event(eventCount).value = xml.(eventNames{iXml})(iEvent).event.code;
event(eventCount).orig = xml.(eventNames{iXml})(iEvent).event;
end;
end %if that takes care of non "-" events that are still out of range
end %if that takes care of "-" events, which are out of range
end %iEvent
end;
end
% add "epoch" events for epoched data, i.e. data with variable length segments
if (hdr.nTrials==1)
eventCount=length(event);
for iEpoch=1:size(hdr.orig.epochdef,1)
eventCount=eventCount+1;
event(eventCount).type = 'epoch';
event(eventCount).sample = hdr.orig.epochdef(iEpoch,1);
event(eventCount).duration = hdr.orig.epochdef(iEpoch,2)-hdr.orig.epochdef(iEpoch,1)+1;
event(eventCount).offset = hdr.orig.epochdef(iEpoch,3);
event(eventCount).value = [];
end % for
end % if
% add "trial" events for segmented data, i.e. data with constant length segments
if (hdr.nTrials >1) && (size(hdr.orig.epochdef,1)==hdr.nTrials)
cellNames=cell(hdr.nTrials,1);
recTime=zeros(hdr.nTrials,1);
epochTimes=cell(hdr.nTrials,1);
for iEpoch=1:hdr.nTrials
epochTimes{iEpoch}=hdr.orig.xml.epochs(iEpoch).epoch.beginTime;
recTime(iEpoch)=((str2num(hdr.orig.xml.epochs(iEpoch).epoch.beginTime)/1000)/(1000/hdr.Fs))+1;
end
for iCat=1:length(hdr.orig.xml.categories)
theTimes=cell(length(hdr.orig.xml.categories(iCat).cat.segments),1);
for i=1:length(hdr.orig.xml.categories(iCat).cat.segments)
theTimes{i}=hdr.orig.xml.categories(iCat).cat.segments(i).seg.beginTime;
end
epochIndex=find(ismember(epochTimes,theTimes));
for i=1:length(epochIndex)
cellNames{epochIndex(i)}=hdr.orig.xml.categories(iCat).cat.name;
end
end
eventCount=length(event);
for iEpoch=1:hdr.nTrials
eventCount=eventCount+1;
event(eventCount).type = 'trial';
event(eventCount).sample = hdr.orig.epochdef(iEpoch,1);
event(eventCount).offset = -hdr.nSamplesPre;
event(eventCount).duration = hdr.nSamples;
event(eventCount).value = cellNames{iEpoch};
end
end
case 'egi_mff_v2'
% ensure that the EGI toolbox is on the path
ft_hastoolbox('egi_mff', 1);
if isunix && filename(1)~=filesep
% add the full path to the dataset directory
filename = fullfile(pwd, filename);
elseif ispc && filename(2)~=':'
% add the full path, including drive letter
filename = fullfile(pwd, filename);
end
% pass the header along to speed it up, it will be read on the fly in case it is empty
event = read_mff_event(filename, hdr);
% clean up the fields in the event structure
fn = fieldnames(event);
fn = setdiff(fn, {'type', 'sample', 'value', 'offset', 'duration', 'timestamp'});
for i=1:length(fn)
event = rmfield(event, fn{i});
end
case 'eyelink_asc'
if isempty(hdr)
hdr = ft_read_header(filename);
end
if isfield(hdr.orig, 'input')
% this is inefficient, since it keeps the complete data in memory
% but it does speed up subsequent read operations without the user
% having to care about it
asc = hdr.orig;
else
asc = read_eyelink_asc(filename);
end
timestamp = [asc.input(:).timestamp];
value = [asc.input(:).value];
% note that in this dataformat the first input trigger can be before
% the start of the data acquisition
for i=1:length(timestamp)
event(end+1).type = 'INPUT';
event(end ).sample = (timestamp(i)-hdr.FirstTimeStamp)/hdr.TimeStampPerSample + 1;
event(end ).timestamp = timestamp(i);
event(end ).value = value(i);
event(end ).duration = 1;
event(end ).offset = 0;
end
case 'fcdc_buffer'
% read from a networked buffer for realtime analysis
[host, port] = filetype_check_uri(filename);
% SK: the following was intended to speed up, but does not work
% the buffer server will try to return exact indices, even
% if the intend here is to filter based on a maximum range.
% We could change the definition of GET_EVT to comply
% with filtering, but that might break other existing code.
%if isempty(flt_minnumber) && isempty(flt_maxnumber)
% evtsel = [];
%else
% evtsel = [0 2^32-1];
% if ~isempty(flt_minnumber)
% evtsel(1) = flt_minnumber-1;
% end
% if ~isempty(flt_maxnumber)
% evtsel(2) = flt_maxnumber-1;
% end
%end
if blocking && isempty(flt_minnumber) && isempty(flt_maxnumber)
warning('disabling blocking because no selection was specified');
blocking = false;
end
if blocking
nsamples = -1; % disable waiting for samples
if isempty(flt_minnumber)
nevents = flt_maxnumber;
elseif isempty(flt_maxnumber)
nevents = flt_minnumber;
else
nevents = max(flt_minnumber, flt_maxnumber);
end
available = buffer_wait_dat([nsamples nevents timeout*1000], host, port);
if available.nevents<nevents
error('buffer timed out while waiting for %d events', nevents);
end
end
try
event = buffer('get_evt', [], host, port);
catch
if strfind(lasterr, 'the buffer returned an error')
% this happens if the buffer contains no events
% which in itself is not a problem and should not result in an error
event = [];
else
rethrow(lasterr);
end
end
case 'fcdc_buffer_offline'
if isdir(filename)
path = filename;
else
[path, file, ext] = fileparts(filename);
end
if isempty(hdr)
headerfile = fullfile(path, 'header');
hdr = read_buffer_offline_header(headerfile);
end
eventfile = fullfile(path, 'events');
event = read_buffer_offline_events(eventfile, hdr);
case 'fcdc_matbin'
% this is multiplexed data in a *.bin file, accompanied by a MATLAB file containing the header and event
[path, file, ext] = fileparts(filename);
filename = fullfile(path, [file '.mat']);
% read the events from the MATLAB file
tmp = load(filename, 'event');
event = tmp.event;
case 'fcdc_fifo'
fifo = filetype_check_uri(filename);
if ~exist(fifo,'file')
warning('the FIFO %s does not exist; attempting to create it', fifo);
fid = fopen(fifo, 'r');
system(sprintf('mkfifo -m 0666 %s',fifo));
end
msg = fread(fid, inf, 'uint8');
fclose(fid);
try
event = mxDeserialize(uint8(msg));
catch
warning(lasterr);
end
case 'fcdc_tcp'
% requires tcp/udp/ip-toolbox
ft_hastoolbox('TCP_UDP_IP', 1);
[host, port] = filetype_check_uri(filename);
if isempty(sock)
sock=pnet('tcpsocket',port);
end
con = pnet(sock, 'tcplisten');
if con~=-1
try
pnet(con,'setreadtimeout',10);
% read packet
msg=pnet(con,'readline'); %,1000,'uint8','network');
if ~isempty(msg)
event = mxDeserialize(uint8(str2num(msg)));
end
% catch
% warning(lasterr);
end
pnet(con,'close');
end
con = [];
case 'fcdc_udp'
% requires tcp/udp/ip-toolbox
ft_hastoolbox('TCP_UDP_IP', 1);
[host, port] = filetype_check_uri(filename);
try
% read from localhost
udp=pnet('udpsocket',port);
% Wait/Read udp packet to read buffer
len=pnet(udp,'readpacket');
if len>0,
% if packet larger then 1 byte then read maximum of 1000 doubles in network byte order
msg=pnet(udp,'read',1000,'uint8');
if ~isempty(msg)
event = mxDeserialize(uint8(msg));
end
end
catch
warning(lasterr);
end
% On break or error close connection
pnet(udp,'close');
case 'fcdc_serial'
% this code is moved to a separate file
event = read_serial_event(filename);
case 'fcdc_mysql'
% check that the required low-level toolbox is available
ft_hastoolbox('mysql', 1);
% read from a MySQL server listening somewhere else on the network
db_open(filename);
if db_blob
event = db_select_blob('fieldtrip.event', 'msg');
else
event = db_select('fieldtrip.event', {'type', 'value', 'sample', 'offset', 'duration'});
end
case 'gtec_mat'
if isempty(hdr)
hdr = ft_read_header(filename);
end
if isempty(trigindx)
% these are probably trigger channels
trigindx = match_str(hdr.label, {'Display', 'Target'});
end
% use a helper function to read the trigger channels and detect the flanks
% pass all the other users options to the read_trigger function
event = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trigindx, 'detectflank', detectflank, 'trigshift', trigshift);
case {'itab_raw' 'itab_mhd'}
if isempty(hdr)
hdr = ft_read_header(filename);
end
for i=1:hdr.orig.nsmpl
event(end+1).type = 'trigger';
event(end ).value = hdr.orig.smpl(i).type;
event(end ).sample = hdr.orig.smpl(i).start + 1;
event(end ).duration = hdr.orig.smpl(i).ntptot;
event(end ).offset = -hdr.orig.smpl(i).ntppre; % number of samples prior to the trigger
end
if isempty(event)
warning('no events found in the event table, reading the trigger channel(s)');
trigindx = find(ft_chantype(hdr, 'flag'));
trigger = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trigindx, 'detectflank', detectflank, 'trigshift', trigshift);
event = appendevent(event, trigger);
end
case 'matlab'
% read the events from a normal MATLAB file
tmp = load(filename, 'event');
event = tmp.event;
case 'micromed_trc'
if isempty(hdr)
hdr = ft_read_header(filename);
end
if isfield(hdr, 'orig') && isfield(hdr.orig, 'Trigger_Area') && isfield(hdr.orig, 'Tigger_Area_Length')
if ~isempty(trigindx)
trigger = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trigindx, 'detectflank', detectflank, 'trigshift', trigshift);
event = appendevent(event, trigger);
else
% routine that reads analog triggers in case no index is specified
event = read_micromed_event(filename);
end
else
error('Not a correct event format')
end
case {'mpi_ds', 'mpi_dap'}
if isempty(hdr)
hdr = ft_read_header(filename);
end
% determine the DAP files that compromise this dataset
if isdir(filename)
ls = dir(filename);
dapfile = {};
for i=1:length(ls)
if ~isempty(regexp(ls(i).name, '.dap$', 'once' ))
dapfile{end+1} = fullfile(filename, ls(i).name);
end
end
dapfile = sort(dapfile);
elseif iscell(filename)
dapfile = filename;
else
dapfile = {filename};
end
% assume that each DAP file is accompanied by a dat file
% read the trigger values from the separate dat files
trg = [];
for i=1:length(dapfile)
datfile = [dapfile{i}(1:(end-4)) '.dat'];
trg = cat(1, trg, textread(datfile, '', 'headerlines', 1));
end
% construct a event structure, one 'trialcode' event per trial
for i=1:length(trg)
event(i).type = 'trialcode'; % string
event(i).sample = (i-1)*hdr.nSamples + 1; % expressed in samples, first sample of file is 1
event(i).value = trg(i); % number or string
event(i).offset = 0; % expressed in samples
event(i).duration = hdr.nSamples; % expressed in samples
end
case {'neuromag_eve'}
% previously this was called babysquid_eve, now it is neuromag_eve
% see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=2170
[p, f, x] = fileparts(filename);
evefile = fullfile(p, [f '.eve']);
fiffile = fullfile(p, [f '.fif']);
if isempty(hdr)
hdr = ft_read_header(fiffile, 'headerformat', 'neuromag_mne');
end
[smp, tim, typ, val] = read_neuromag_eve(evefile);
smp = smp + 1; % should be 1-offset
smp = smp - double(hdr.orig.raw.first_samp); % the recording to disk may start later than the actual acquisition
if ~isempty(smp)
sample = num2cell(smp);
value = num2cell(val);
offset = num2cell(zeros(size(smp)));
type = repmat({'unknown'}, size(typ));
type(typ==0) = {'trigger'};
if any(typ~=0)
% see the comments in read_neuromag_eve
warning('entries in the *.eve file with a type other than 0 are represented as ''unknown''')
end
% convert to a structure array
event = struct('type', type, 'value', value, 'sample', sample, 'offset', offset);
else
event = [];
end
case {'neuromag_fif' 'neuromag_mne' 'neuromag_mex'}
if strcmp(eventformat, 'neuromag_fif')
% the default is to use the MNE reader for fif files
eventformat = 'neuromag_mne';
end
if strcmp(eventformat, 'neuromag_mex')
% check that the required low-level toolbox is available
ft_hastoolbox('meg-pd', 1);
if isempty(headerformat), headerformat = eventformat; end
if isempty(dataformat), dataformat = eventformat; end
elseif strcmp(eventformat, 'neuromag_mne')
% check that the required low-level toolbox is available
ft_hastoolbox('mne', 1);
if isempty(headerformat), headerformat = eventformat; end
if isempty(dataformat), dataformat = eventformat; end
end
if isempty(hdr)
hdr = ft_read_header(filename, 'headerformat', headerformat, 'checkmaxfilter', checkmaxfilter);
end
% note below we've had to include some chunks of code that are only
% called if the file is an averaged file, or if the file is continuous.
% These are defined in hdr by read_header for neuromag_mne, but do not
% exist for neuromag_fif, hence we run the code anyway if the fields do
% not exist (this is what happened previously anyway).
if strcmp(eventformat, 'neuromag_mex')
iscontinuous = 1;
isaverage = 0;
isepoched = 0;
elseif strcmp(eventformat, 'neuromag_mne')
iscontinuous = hdr.orig.iscontinuous;
isaverage = hdr.orig.isaverage;
isepoched = hdr.orig.isepoched;
end
if iscontinuous
analogindx = find(strcmp(ft_chantype(hdr), 'analog trigger'));
binaryindx = find(strcmp(ft_chantype(hdr), 'digital trigger'));
if isempty(binaryindx)&&isempty(analogindx)
% included in case of problems with older systems and MNE reader:
% use a predefined set of channel names
binary = {'STI 014', 'STI 015', 'STI 016'};
binaryindx = match_str(hdr.label, binary);
end
if ~isempty(binaryindx)
trigger = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', binaryindx, 'detectflank', detectflank, 'trigshift', trigshift, 'fixneuromag', false);
event = appendevent(event, trigger);
end
if ~isempty(analogindx)
% add the triggers to the event structure based on trigger channels with the name "STI xxx"
% there are some issues with noise on these analog trigger
% channels, on older systems only
% read the trigger channel and do flank detection
trigger = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', analogindx, 'detectflank', detectflank, 'trigshift', trigshift, 'fixneuromag', true);
event = appendevent(event, trigger);
if ~isempty(trigger)
% throw out everything that is not a (real) trigger...
[sel1, sel2] = match_str({trigger.type}, {'STI001', 'STI002', 'STI003', 'STI004', 'STI005', 'STI006', 'STI007', 'STI008'});
trigger_tmp = trigger(sel1);
%trigger_bits = size(unique(sel2), 1);
all_triggers = unique(sel2);
trigger_bits = max(all_triggers) - min(all_triggers) + 1;
% collect all samples where triggers occured...
all_samples = unique([trigger_tmp.sample]);
new_triggers = [];
i = 1;
while i <= length(all_samples)
cur_triggers = [];
j = 0;
% look also in adjacent samples according to tolerance
while (i+j <= length(all_samples)) && (all_samples(i+j) - all_samples(i) <= tolerance)
if j >= 1
fprintf('Fixing trigger at sample %d\n', all_samples(i));
end %if
cur_triggers = appendevent(cur_triggers, trigger_tmp([trigger_tmp.sample] == all_samples(i+j)));
j = j + 1;
end %while
% construct new trigger field
if ~isempty(cur_triggers)
new_triggers(end+1).type = 'Trigger';
new_triggers(end).sample = all_samples(i);
[sel1, sel2] = match_str({cur_triggers.type}, {'STI001', 'STI002', 'STI003', 'STI004', 'STI005', 'STI006', 'STI007', 'STI008'});
new_triggers(end).value = bin2dec((dec2bin(sum(2.^(sel2-1)), trigger_bits)));
end %if
i = i + j;
end %while
event = appendevent(event, new_triggers);
end %if
end
elseif isaverage
% the length of each average can be variable
nsamples = zeros(1, length(hdr.orig.evoked));
for i=1:length(hdr.orig.evoked)
nsamples(i) = size(hdr.orig.evoked(i).epochs, 2);
end
begsample = cumsum([1 nsamples]);
for i=1:length(hdr.orig.evoked)
event(end+1).type = 'average';
event(end ).sample = begsample(i);
event(end ).value = hdr.orig.evoked(i).comment; % this is a descriptive string
event(end ).offset = hdr.orig.evoked(i).first;
event(end ).duration = hdr.orig.evoked(i).last - hdr.orig.evoked(i).first + 1;
end
elseif isepoched
error('Support for epoched *.fif data is not yet implemented.')
end
% check whether the *.fif file is accompanied by an *.eve file
[p, f, x] = fileparts(filename);
evefile = fullfile(p, [f '.eve']);
if exist(evefile, 'file')
eve = ft_read_event(evefile, 'header', hdr);
if ~isempty(eve)
fprintf('appending %d events from "%s"\n', length(eve), evefile);
event = appendevent(event, eve);
end
end
case {'neuralynx_ttl' 'neuralynx_bin' 'neuralynx_dma' 'neuralynx_sdma'}
if isempty(hdr)
hdr = ft_read_header(filename);
end
% specify the range to search for triggers, default is the complete file
if ~isempty(flt_minsample)
begsample = flt_minsample;
else
begsample = 1;
end
if ~isempty(flt_maxsample)
endsample = flt_maxsample;
else
endsample = hdr.nSamples*hdr.nTrials;
end
if strcmp(eventformat, 'neuralynx_dma')
% read the Parallel_in channel from the DMA log file
ttl = read_neuralynx_dma(filename, begsample, endsample, 'ttl');
elseif strcmp(eventformat, 'neuralynx_sdma')
% determine the separate files with the trigger and timestamp information
[p, f, x] = fileparts(filename);
ttlfile = fullfile(filename, [f '.ttl.bin']);
tslfile = fullfile(filename, [f '.tsl.bin']);
tshfile = fullfile(filename, [f '.tsh.bin']);
if ~exist(ttlfile) && ~exist(tslfile) && ~exist(tshfile)
% perhaps it is an old splitted dma dataset?
ttlfile = fullfile(filename, [f '.ttl']);
tslfile = fullfile(filename, [f '.tsl']);
tshfile = fullfile(filename, [f '.tsh']);
end
if ~exist(ttlfile) && ~exist(tslfile) && ~exist(tshfile)
% these files must be present in a splitted dma dataset
error('could not locate the individual ttl, tsl and tsh files');
end
% read the trigger values from the separate file
ttl = read_neuralynx_bin(ttlfile, begsample, endsample);
elseif strcmp(eventformat, 'neuralynx_ttl')
% determine the optional files with timestamp information
tslfile = [filename(1:(end-4)) '.tsl'];
tshfile = [filename(1:(end-4)) '.tsh'];
% read the triggers from a separate *.ttl file
ttl = read_neuralynx_ttl(filename, begsample, endsample);
elseif strcmp(eventformat, 'neuralynx_bin')
% determine the optional files with timestamp information
tslfile = [filename(1:(end-8)) '.tsl.bin'];
tshfile = [filename(1:(end-8)) '.tsh.bin'];
% read the triggers from a separate *.ttl.bin file
ttl = read_neuralynx_bin(filename, begsample, endsample);
end
ttl = int32(ttl / (2^16)); % parallel port provides int32, but word resolution is int16. Shift the bits and typecast to signed integer.
d1 = (diff(ttl)~=0); % determine the flanks, which can be multiple samples long (this looses one sample)
d2 = (diff(d1)==1); % determine the onset of the flanks (this looses one sample)
smp = find(d2)+2; % find the onset of the flanks, add the two samples again
val = ttl(smp+5); % look some samples further for the trigger value, to avoid the flank
clear d1 d2 ttl
ind = find(val~=0); % look for triggers tith a non-zero value, this avoids downgoing flanks going to zero
smp = smp(ind); % discard triggers with a value of zero
val = val(ind); % discard triggers with a value of zero
if ~isempty(smp)
% try reading the timestamps
if strcmp(eventformat, 'neuralynx_dma')
tsl = read_neuralynx_dma(filename, 1, max(smp), 'tsl');
tsl = typecast(tsl(smp), 'uint32');
tsh = read_neuralynx_dma(filename, 1, max(smp), 'tsh');
tsh = typecast(tsh(smp), 'uint32');
ts = timestamp_neuralynx(tsl, tsh);
elseif exist(tslfile) && exist(tshfile)
tsl = read_neuralynx_bin(tslfile, 1, max(smp));
tsl = tsl(smp);
tsh = read_neuralynx_bin(tshfile, 1, max(smp));
tsh = tsh(smp);
ts = timestamp_neuralynx(tsl, tsh);
else
ts = [];
end
% reformat the values as cell array, since the struct function can work with those
type = repmat({'trigger'},size(smp));
value = num2cell(val);
sample = num2cell(smp + begsample - 1);
duration = repmat({[]},size(smp));
offset = repmat({[]},size(smp));
if ~isempty(ts)
timestamp = reshape(num2cell(ts),size(smp));
else
timestamp = repmat({[]},size(smp));
end
% convert it into a structure array, this can be done in one go
event = struct('type', type, 'value', value, 'sample', sample, 'timestamp', timestamp, 'offset', offset, 'duration', duration);
clear type value sample timestamp offset duration
end
if (strcmp(eventformat, 'neuralynx_bin') || strcmp(eventformat, 'neuralynx_ttl')) && isfield(hdr, 'FirstTimeStamp')
% the header was obtained from an external dataset which could be at a different sampling rate
% use the timestamps to redetermine the sample numbers
fprintf('using sample number of the downsampled file to reposition the TTL events\n');
% convert the timestamps into samples, keeping in mind the FirstTimeStamp and TimeStampPerSample
smp = round(double(ts - uint64(hdr.FirstTimeStamp))./hdr.TimeStampPerSample + 1);
for i=1:length(event)
% update the sample number
event(i).sample = smp(i);
end
end
case 'neuralynx_ds'
% read the header of the dataset
if isempty(hdr)
hdr = ft_read_header(filename);
end
% the event file is contained in the dataset directory
if exist(fullfile(filename, 'Events.Nev'))
filename = fullfile(filename, 'Events.Nev');
elseif exist(fullfile(filename, 'Events.nev'))
filename = fullfile(filename, 'Events.nev');
elseif exist(fullfile(filename, 'events.Nev'))
filename = fullfile(filename, 'events.Nev');
elseif exist(fullfile(filename, 'events.nev'))
filename = fullfile(filename, 'events.nev');
end
% read the events, apply filter is applicable
nev = read_neuralynx_nev(filename, 'type', flt_type, 'value', flt_value, 'mintimestamp', flt_mintimestamp, 'maxtimestamp', flt_maxtimestamp, 'minnumber', flt_minnumber, 'maxnumber', flt_maxnumber);
% the following code should only be executed if there are events,
% otherwise there will be an error subtracting an uint64 from an []
if ~isempty(nev)
% now get the values as cell array, since the struct function can work with those
value = {nev.TTLValue};
timestamp = {nev.TimeStamp};
number = {nev.EventNumber};
type = repmat({'trigger'},size(value));
duration = repmat({[]},size(value));
offset = repmat({[]},size(value));
sample = num2cell(round(double(cell2mat(timestamp) - hdr.FirstTimeStamp)/hdr.TimeStampPerSample + 1));
% convert it into a structure array
event = struct('type', type, 'value', value, 'sample', sample, 'timestamp', timestamp, 'duration', duration, 'offset', offset, 'number', number);
end
case {'neuralynx_nev'}
% instead of the directory containing the combination of nev and ncs files, the nev file was specified
% do NOT read the header of the dataset
% read the events, apply filter is applicable
nev = read_neuralynx_nev(filename, 'type', flt_type, 'value', flt_value, 'mintimestamp', flt_mintimestamp, 'maxtimestamp', flt_maxtimestamp, 'minnumber', flt_minnumber, 'maxnumber', flt_maxnumber);
% the following code should only be executed if there are events,
% otherwise there will be an error subtracting an uint64 from an []
if ~isempty(nev)
% now get the values as cell array, since the struct function can work with those
value = {nev.TTLValue};
timestamp = {nev.TimeStamp};
number = {nev.EventNumber};
type = repmat({'trigger'},size(value));
duration = repmat({[]},size(value));
offset = repmat({[]},size(value));
% since the ncs files are not specified, there is no mapping between lfp samples and timestamps
sample = repmat({nan}, size(value));
% convert it into a structure array
event = struct('type', type, 'value', value, 'sample', sample, 'timestamp', timestamp, 'duration', duration, 'offset', offset, 'number', number);
end
case 'neuralynx_cds'
% this is a combined Neuralynx dataset with separate subdirectories for the LFP, MUA and spike channels
dirlist = dir(filename);
%haslfp = any(filetype_check_extension({dirlist.name}, 'lfp'));
%hasmua = any(filetype_check_extension({dirlist.name}, 'mua'));
%hasspike = any(filetype_check_extension({dirlist.name}, 'spike'));
%hastsl = any(filetype_check_extension({dirlist.name}, 'tsl')); % separate file with original TimeStampLow
%hastsh = any(filetype_check_extension({dirlist.name}, 'tsh')); % separate file with original TimeStampHi
hasttl = any(filetype_check_extension({dirlist.name}, 'ttl')); % separate file with original Parallel_in
hasnev = any(filetype_check_extension({dirlist.name}, 'nev')); % original Events.Nev file
hasmat = 0;
if hasttl
eventfile = fullfile(filename, dirlist(find(filetype_check_extension({dirlist.name}, 'ttl'))).name);
% read the header from the combined dataset
if isempty(hdr)
hdr = ft_read_header(filename);
end
% read the events from the *.ttl file
event = ft_read_event(eventfile);
% convert the sample numbers from the dma or ttl file to the downsampled dataset
% assume that the *.ttl file is sampled at 32556Hz and is aligned with the rest of the data
for i=1:length(event)
event(i).sample = round((event(i).sample-1) * hdr.Fs/32556 + 1);
end
% elseif hasnev
% FIXME, do something here
% elseif hasmat
% FIXME, do something here
else
error('no event file found');
end
% The sample number is missingin the code below, since it is not available
% without looking in the continuously sampled data files. Therefore
% sorting the events (later in this function) based on the sample number
% fails and no events can be returned.
%
% case 'neuralynx_nev'
% [nev] = read_neuralynx_nev(filename);
% % select only the events with a TTL value
% ttl = [nev.TTLValue];
% sel = find(ttl~=0);
% % now get the values as cell array, since teh struct function can work with those
% value = {nev(sel).TTLValue};
% timestamp = {nev(sel).TimeStamp};
% event = struct('value', value, 'timestamp', timestamp);
% for i=1:length(event)
% % assign the other fixed elements
% event(i).type = 'trigger';
% event(i).offset = [];
% event(i).duration = [];
% event(i).sample = [];
% end
case {'neuroprax_eeg', 'neuroprax_mrk'}
event = [];
% start reading the markers, which I believe to be more like clinical annotations
tmp = np_readmarker (filename, 0, inf, 'samples');
for i = 1:numel(tmp.marker)
if isempty(tmp.marker{i})
break;
end
event = appendevent(event, struct('type', tmp.markernames(i), 'sample', num2cell(tmp.marker{i}), 'value', {tmp.markertyp(i)}));
end
% if present, read the digital triggers which are present as channel in the data
if isempty(hdr)
hdr = ft_read_header(filename);
end
trgindx = match_str(hdr.label, 'DTRIG');
if ~isempty(trgindx)
trigger = read_trigger(filename, 'header', hdr, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trgindx, 'detectflank', detectflank, 'trigshift', trigshift);
event = appendevent(event, trigger);
end
case 'nexstim_nxe'
event = read_nexstim_event(filename);
case 'nimh_cortex'
if isempty(hdr)
hdr = ft_read_header(filename);
end
cortex = hdr.orig.trial;
for i=1:length(cortex)
% add one 'trial' event for every trial and add the trigger events
event(end+1).type = 'trial';
event(end ).sample = nan;
event(end ).duration = nan;
event(end ).offset = nan;
event(end ).value = i; % use the trial number as value
for j=1:length(cortex(i).event)
event(end+1).type = 'trigger';
event(end ).sample = nan;
event(end ).duration = nan;
event(end ).offset = nan;
event(end ).value = cortex(i).event(j);
end
end
case 'ns_avg'
if isempty(hdr)
hdr = ft_read_header(filename);
end
event(end+1).type = 'average';
event(end ).sample = 1;
event(end ).duration = hdr.nSamples;
event(end ).offset = -hdr.nSamplesPre;
event(end ).value = [];
case {'ns_cnt', 'ns_cnt16', 'ns_cnt32'}
% read the header, the original header includes the event table
if isempty(hdr)
hdr = ft_read_header(filename, 'headerformat', eventformat);
end
% translate the event table into known FieldTrip event types
for i=1:numel(hdr.orig.event)
event(end+1).type = 'trigger';
event(end ).sample = hdr.orig.event(i).offset + 1; % +1 was in EEGLAB pop_loadcnt
event(end ).value = hdr.orig.event(i).stimtype;
event(end ).offset = 0;
event(end ).duration = 0;
% the code above assumes that all events are stimulus triggers
% howevere, there are also interesting events possible, such as responses
if hdr.orig.event(i).stimtype~=0
event(end+1).type = 'stimtype';
event(end ).sample = hdr.orig.event(i).offset + 1; % +1 was in EEGLAB pop_loadcnt
event(end ).value = hdr.orig.event(i).stimtype;
event(end ).offset = 0;
event(end ).duration = 0;
elseif hdr.orig.event(i).keypad_accept~=0
event(end+1).type = 'keypad_accept';
event(end ).sample = hdr.orig.event(i).offset + 1; % +1 was in EEGLAB pop_loadcnt
event(end ).value = hdr.orig.event(i).keypad_accept;
event(end ).offset = 0;
event(end ).duration = 0;
end
end
case 'ns_eeg'
if isempty(hdr)
hdr = ft_read_header(filename);
end
for i=1:hdr.nTrials
% the *.eeg file has a fixed trigger value for each trial
% furthermore each trial has additional fields like accept, correct, response and rt
tmp = read_ns_eeg(filename, i);
% create an event with the trigger value
event(end+1).type = 'trial';
event(end ).sample = (i-1)*hdr.nSamples + 1;
event(end ).value = tmp.sweep.type; % trigger value
event(end ).offset = -hdr.nSamplesPre;
event(end ).duration = hdr.nSamples;
% create an event with the boolean accept/reject code
event(end+1).type = 'accept';
event(end ).sample = (i-1)*hdr.nSamples + 1;
event(end ).value = tmp.sweep.accept; % boolean value indicating accept/reject
event(end ).offset = -hdr.nSamplesPre;
event(end ).duration = hdr.nSamples;
% create an event with the boolean accept/reject code
event(end+1).type = 'correct';
event(end ).sample = (i-1)*hdr.nSamples + 1;
event(end ).value = tmp.sweep.correct; % boolean value
event(end ).offset = -hdr.nSamplesPre;
event(end ).duration = hdr.nSamples;
% create an event with the boolean accept/reject code
event(end+1).type = 'response';
event(end ).sample = (i-1)*hdr.nSamples + 1;
event(end ).value = tmp.sweep.response; % probably a boolean value
event(end ).offset = -hdr.nSamplesPre;
event(end ).duration = hdr.nSamples;
% create an event with the boolean accept/reject code
event(end+1).type = 'rt';
event(end ).sample = (i-1)*hdr.nSamples + 1;
event(end ).value = tmp.sweep.rt; % time in seconds
event(end ).offset = -hdr.nSamplesPre;
event(end ).duration = hdr.nSamples;
end
case 'plexon_nex'
event = read_nex_event(filename);
case {'yokogawa_ave', 'yokogawa_con', 'yokogawa_raw'}
% check that the required low-level toolbox is available
if ~ft_hastoolbox('yokogawa', 0);
ft_hastoolbox('yokogawa_meg_reader', 1);
end
% the user should be able to specify the analog threshold
% the user should be able to specify the trigger channels
% the user should be able to specify the flank, but the code falls back to 'auto' as default
if isempty(detectflank)
detectflank = 'auto';
end
event = read_yokogawa_event(filename, 'detectflank', detectflank, 'trigindx', trigindx, 'threshold', threshold);
case 'nmc_archive_k'
event = read_nmc_archive_k_event(filename);
case 'netmeg'
warning('FieldTrip:ft_read_event:unsupported_event_format', 'reading of events for the netmeg format is not yet supported');
event = [];
case 'neuroshare' % NOTE: still under development
% check that the required neuroshare toolbox is available
ft_hastoolbox('neuroshare', 1);
tmp = read_neuroshare(filename, 'readevent', 'yes');
for i=1:length(tmp.event.timestamp)
event(i).type = tmp.hdr.eventinfo(i).EventType;
event(i).value = tmp.event.data(i);
event(i).timestamp = tmp.event.timestamp(i);
event(i).sample = tmp.event.sample(i);
end
case 'dataq_wdq'
if isempty(hdr)
hdr = ft_read_header(filename, 'headerformat', 'dataq_wdq');
end
trigger = read_wdq_data(filename, hdr.orig, 'lowbits');
[ix, iy] = find(trigger>1); %it seems as if the value of 1 is meaningless
for i=1:numel(ix)
event(i).type = num2str(ix(i));
event(i).value = trigger(ix(i),iy(i));
event(i).sample = iy(i);
end
case 'bucn_nirs'
event = read_bucn_nirsevent(filename);
case 'oxy3'
ft_hastoolbox('artinis', 1);
event = read_artinis_oxy3(filename, true);
if isempty(hdr)
hdr = read_artinis_oxy3(filename);
end
if isempty(trigindx) % indx gets precedence over labels! numbers before words
trigindx = find(ismember(hdr.label, ft_channelselection(triglabel, hdr.label)));
end
% read the trigger channel and do flank detection
triggers = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'threshold', threshold, 'chanindx', trigindx, 'detectflank', detectflank, 'trigshift', trigshift, 'fixartinis', true);
% remove consecutive triggers
i = 1;
last_trigger_sample = triggers(i).sample;
while i<numel(triggers)
if strcmp(triggers(i).type, triggers(i+1).type) && triggers(i+1).sample-last_trigger_sample <= tolerance
[triggers(i).value, idx] = max([triggers(i).value, triggers(i+1).value]);
fprintf('Merging triggers at sample %d and %d\n', triggers(i).sample, triggers(i+1).sample);
last_trigger_sample = triggers(i+1).sample;
if (idx==2)
triggers(i).sample = triggers(i+1).sample;
end
triggers(i+1) = [];
else
i=i+1;
last_trigger_sample = triggers(i).sample;
end
end
event = appendevent(event, triggers);
case {'manscan_mbi', 'manscan_mb2'}
if isempty(hdr)
hdr = ft_read_header(filename);
end
if isfield(hdr.orig, 'epochs') && ~isempty(hdr.orig.epochs)
trlind = [];
for i = 1:numel(hdr.orig.epochs)
trlind = [trlind i*ones(1, diff(hdr.orig.epochs(i).samples) + 1)];
end
else
trlind = ones(1, hdr.nSamples);
end
if isfield(hdr.orig, 'events')
for i = 1:numel(hdr.orig.events)
for j = 1:length(hdr.orig.events(i).samples)
event(end+1).type = 'trigger';
event(end).value = hdr.orig.events(i).label;
event(end).sample = find(cumsum(trlind == hdr.orig.events(i).epochs(j))...
== hdr.orig.events(i).samples(j), 1, 'first');
end
end
end
otherwise
warning('FieldTrip:ft_read_event:unsupported_event_format','unsupported event format (%s)', eventformat);
event = [];
end
if ~isempty(hdr) && hdr.nTrials>1 && (isempty(event) || ~any(strcmp({event.type}, 'trial')))
% the data suggests multiple trials and trial events have not yet been defined
% make an event for each trial according to the file header
for i=1:hdr.nTrials
event(end+1).type = 'trial';
event(end ).sample = (i-1)*hdr.nSamples + 1;
event(end ).offset = -hdr.nSamplesPre;
event(end ).duration = hdr.nSamples;
event(end ).value = [];
end
end
if ~isempty(event)
% make sure that all required elements are present
if ~isfield(event, 'type'), error('type field not defined for each event'); end
if ~isfield(event, 'sample'), error('sample field not defined for each event'); end
if ~isfield(event, 'value'), for i=1:length(event), event(i).value = []; end; end
if ~isfield(event, 'offset'), for i=1:length(event), event(i).offset = []; end; end
if ~isfield(event, 'duration'), for i=1:length(event), event(i).duration = []; end; end
end
% make sure that all numeric values are double
if ~isempty(event)
for i=1:length(event)
if isnumeric(event(i).value)
event(i).value = double(event(i).value);
end
event(i).sample = double(event(i).sample);
event(i).offset = double(event(i).offset);
event(i).duration = double(event(i).duration);
end
end
if ~isempty(event)
% sort the events on the sample on which they occur
% this has the side effect that events without a sample number are discarded
sample = [event.sample];
if ~all(isnan(sample))
[dum, indx] = sort(sample);
event = event(indx);
end
end
% apply the optional filters
event = ft_filter_event(event, varargin{:});
if isempty(event)
% ensure that it has the correct fields, even if it is empty
event = struct('type', {}, 'value', {}, 'sample', {}, 'offset', {}, 'duration', {});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% poll implementation for backwards compatibility with ft buffer version 1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function available = buffer_wait_dat(selection, host, port)
% selection(1) nsamples
% selection(2) nevents
% selection(3) timeout in msec
% check if backwards compatibilty mode is required
try
% the WAIT_DAT request waits until it has more samples or events
selection(1) = selection(1)-1;
selection(2) = selection(2)-1;
% the following should work for buffer version 2
available = buffer('WAIT_DAT', selection, host, port);
catch
% the error means that the buffer is version 1, which does not support the WAIT_DAT request
% the wait_dat can be implemented by polling the buffer
nsamples = selection(1);
nevents = selection(2);
timeout = selection(3)/1000; % in seconds
stopwatch = tic;
% results are retrieved in the order written to the buffer
orig = buffer('GET_HDR', [], host, port);
if timeout > 0
% wait maximal timeout seconds until more than nsamples samples or nevents events have been received
while toc(stopwatch)<timeout
if nsamples == -1 && nevents == -1, break, end
if nsamples ~= -1 && orig.nsamples >= nsamples, break, end
if nevents ~= -1 && orig.nevents >= nevents, break, end
orig = buffer('GET_HDR', [], host, port);
pause(0.001);
end
else
% no reason to wait
end
available.nsamples = orig.nsamples;
available.nevents = orig.nevents;
end % try buffer v1 or v2
|
github
|
ZijingMao/baselineeegtest-master
|
ft_read_header.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/ft_read_header.m
| 87,065 |
utf_8
|
1b5db49e312253ab18ef5ae4d6c12d13
|
function [hdr] = ft_read_header(filename, varargin)
% FT_READ_HEADER reads header information from a variety of EEG, MEG and LFP
% files and represents the header information in a common data-independent
% format. The supported formats are listed below.
%
% Use as
% hdr = ft_read_header(filename, ...)
%
% Additional options should be specified in key-value pairs and can be
% 'headerformat' string
% 'fallback' can be empty or 'biosig' (default = [])
% 'coordsys' string, 'head' or 'dewar' (default = 'head')
% 'checkmaxfilter' boolean, whether to check that maxfilter has been correctly applied (default = true)
% 'chanindx' list with channel indices in case of different sampling frequencies (only for EDF)
%
% This returns a header structure with the following elements
% hdr.Fs sampling frequency
% hdr.nChans number of channels
% hdr.nSamples number of samples per trial
% hdr.nSamplesPre number of pre-trigger samples in each trial
% hdr.nTrials number of trials
% hdr.label Nx1 cell-array with the label of each channel
% hdr.chantype Nx1 cell-array with the channel type, see FT_CHANTYPE
% hdr.chanunit Nx1 cell-array with the physical units, see FT_CHANUNIT
%
% For continuously recorded data, nSamplesPre=0 and nTrials=1.
%
% For some data formats that are recorded on animal electrophysiology
% systems (e.g. Neuralynx, Plexon), the following optional fields are
% returned, which allows for relating the timing of spike and LFP data
% hdr.FirstTimeStamp number, 32 bit or 64 bit unsigned integer
% hdr.TimeStampPerSample double
%
% Depending on the file format, additional header information can be
% returned in the hdr.orig subfield.
%
% The following MEG dataformats are supported
% CTF - VSM MedTech (*.ds, *.res4, *.meg4)
% Neuromag - Elekta (*.fif)
% BTi - 4D Neuroimaging (*.m4d, *.pdf, *.xyz)
% Yokogawa (*.ave, *.con, *.raw)
% NetMEG (*.nc)
% ITAB - Chieti (*.mhd)
%
% The following EEG dataformats are supported
% ANT - Advanced Neuro Technology, EEProbe (*.avr, *.eeg, *.cnt)
% BCI2000 (*.dat)
% Biosemi (*.bdf)
% BrainVision (*.eeg, *.seg, *.dat, *.vhdr, *.vmrk)
% CED - Cambridge Electronic Design (*.smr)
% EGI - Electrical Geodesics, Inc. (*.egis, *.ave, *.gave, *.ses, *.raw, *.sbin, *.mff)
% GTec (*.mat)
% Generic data formats (*.edf, *.gdf)
% Megis/BESA (*.avr, *.swf)
% NeuroScan (*.eeg, *.cnt, *.avg)
% Nexstim (*.nxe)
%
% The following spike and LFP dataformats are supported
% Neuralynx (*.ncs, *.nse, *.nts, *.nev, *.nrd, *.dma, *.log)
% Plextor (*.nex, *.plx, *.ddt)
% CED - Cambridge Electronic Design (*.smr)
% MPI - Max Planck Institute (*.dap)
% Neurosim (neurosim_spikes, neurosim_signals, neurosim_ds)
% Windaq (*.wdq)
%
% The following NIRS dataformats are supported
% BUCN - Birkbeck college, London (*.txt)
%
% The following Eyetracker dataformats are supported
% EyeLink - SR Research (*.asc)
%
% See also FT_READ_DATA, FT_READ_EVENT, FT_WRITE_DATA, FT_WRITE_EVENT,
% FT_CHANTYPE, FT_CHANUNIT
% Copyright (C) 2003-2015 Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_read_header.m 10521 2015-07-04 13:13:36Z roboos $
% TODO channel renaming should be made a general option (see bham_bdf)
persistent cacheheader % for caching the full header
persistent cachechunk % for caching the res4 chunk when doing realtime analysis on the CTF scanner
persistent db_blob % for fcdc_mysql
if isempty(db_blob)
db_blob = false;
end
if iscell(filename)
% use recursion to read events from multiple files
ft_warning(sprintf('concatenating header from %d files', numel(filename)));
hdr = cell(size(filename));
for i=1:numel(filename)
hdr{i} = ft_read_header(filename{i}, varargin{:});
end
ntrl = nan(size(filename));
nsmp = nan(size(filename));
for i=1:numel(filename)
assert(isequal(hdr{i}.label, hdr{1}.label));
assert(isequal(hdr{i}.Fs, hdr{1}.Fs));
ntrl(i) = hdr{i}.nTrials;
nsmp(i) = hdr{i}.nSamples;
end
combined = hdr{1};
combined.orig = hdr; % store the original header details of each file
if all(ntrl==1)
% each file is a continuous recording
combined.nTrials = ntrl(1);
combined.nSamples = sum(nsmp);
elseif all(nsmp==nsmp(1))
% each file holds segments of the same length
combined.nTrials = sum(ntrl);
combined.nSamples = nsmp(1);
else
error('cannot concatenate files');
end
% return the header of the concatenated datafiles
hdr = combined;
return
end
% get the options
headerformat = ft_getopt(varargin, 'headerformat');
retry = ft_getopt(varargin, 'retry', false); % the default is not to retry reading the header
coordsys = ft_getopt(varargin, 'coordsys', 'head'); % this is used for ctf and neuromag_mne, it can be head or dewar
chanindx = ft_getopt(varargin, 'chanindx'); % this is used for EDF with different sampling rates
% optionally get the data from the URL and make a temporary local copy
filename = fetch_url(filename);
if isempty(headerformat)
% only do the autodetection if the format was not specified
headerformat = ft_filetype(filename);
end
if iscell(headerformat)
% this happens for datasets specified as cell-array for concatenation
headerformat = headerformat{1};
end
if strcmp(headerformat, 'compressed')
% we are dealing with a compressed dataset, inflate it first
filename = inflate_file(filename);
headerformat = ft_filetype(filename);
end
realtime = any(strcmp(headerformat, {'fcdc_buffer', 'ctf_shm', 'fcdc_mysql'}));
% The checkUniqueLabels flag is used for the realtime buffer in case
% it contains fMRI data. It prevents 1000000 voxel names to be checked
% for uniqueness. fMRI users will probably never use channel names
% for anything.
if realtime
% skip the rest of the initial checks to increase the speed for realtime operation
checkUniqueLabels = false;
% the cache and fallback option should always be false for realtime processing
cache = false;
fallback = false;
else
% check whether the file or directory exists
if ~exist(filename, 'file')
error('FILEIO:InvalidFileName', 'file or directory ''%s'' does not exist', filename);
end
checkUniqueLabels = true;
% get the rest of the options, this is skipped for realtime operation
cache = ft_getopt(varargin, 'cache');
fallback = ft_getopt(varargin, 'fallback');
checkmaxfilter = ft_getopt(varargin, 'checkmaxfilter', true);
if isempty(cache),
if strcmp(headerformat, 'bci2000_dat') || strcmp(headerformat, 'eyelink_asc') || strcmp(headerformat, 'gtec_mat') || strcmp(headerformat, 'biosig')
cache = true;
else
cache = false;
end
end
% ensure that the headerfile and datafile are defined, which are sometimes different than the name of the dataset
[filename, headerfile, datafile] = dataset2files(filename, headerformat);
if ~strcmp(filename, headerfile) && ~ft_filetype(filename, 'ctf_ds') && ~ft_filetype(filename, 'fcdc_buffer_offline') && ~ft_filetype(filename, 'fcdc_matbin')
filename = headerfile; % this function should read the headerfile, not the dataset
headerformat = ft_filetype(filename); % update the filetype
end
end % if skip initial check
% implement the caching in a data-format independent way
if cache && exist(headerfile, 'file') && ~isempty(cacheheader)
% try to get the header from cache
details = dir(headerfile);
if isequal(details, cacheheader.details)
% the header file has not been updated, fetch it from the cache
% fprintf('got header from cache\n');
hdr = rmfield(cacheheader, 'details');
switch ft_filetype(datafile)
case {'ctf_ds' 'ctf_meg4' 'ctf_old' 'read_ctf_res4'}
% for realtime analysis EOF chasing the res4 does not correctly
% estimate the number of samples, so we compute it on the fly
sz = 0;
files = dir([filename '/*.*meg4']);
for j=1:numel(files)
sz = sz + files(j).bytes;
end
hdr.nTrials = floor((sz - 8) / (hdr.nChans*4) / hdr.nSamples);
end
return;
end % if the details correspond
end % if cache
% the support for head/dewar coordinates is still limited
if strcmp(coordsys, 'dewar') && ~any(strcmp(headerformat, {'fcdc_buffer', 'ctf_ds', 'ctf_meg4', 'ctf_res4', 'neuromag_fif', 'neuromag_mne'}))
error('dewar coordinates are not supported for %s', headerformat);
end
% start with an empty header
hdr = [];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the data with the low-level reading function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch headerformat
case 'AnyWave'
orig = read_ahdf5_hdr(datafile);
hdr.orig = orig;
hdr.Fs = orig.channels(1).samplingRate;
hdr.nChans = numel(orig.channels);
hdr.nSamples = orig.numberOfSamples;
hdr.nTrials = orig.numberOfBlocks;
hdr.nSamplesPre = 0;
hdr.label = orig.label;
hdr.reference = orig.reference(:);
hdr.chanunit = orig.unit(:);
hdr.chantype = orig.type(:);
case '4d'
orig = read_4d_hdr(datafile);
hdr.Fs = orig.header_data.SampleFrequency;
hdr.nChans = orig.header_data.TotalChannels;
hdr.nSamples = orig.header_data.SlicesPerEpoch;
hdr.nSamplesPre = round(orig.header_data.FirstLatency*orig.header_data.SampleFrequency);
hdr.nTrials = orig.header_data.TotalEpochs;
%hdr.label = {orig.channel_data(:).chan_label}';
hdr.label = orig.Channel;
[hdr.grad, elec] = bti2grad(orig);
if ~isempty(elec),
hdr.elec = elec;
end
% remember original header details
hdr.orig = orig;
case {'4d_pdf', '4d_m4d', '4d_xyz'}
orig = read_bti_m4d(filename);
hdr.Fs = orig.SampleFrequency;
hdr.nChans = orig.TotalChannels;
hdr.nSamples = orig.SlicesPerEpoch;
hdr.nSamplesPre = round(orig.FirstLatency*orig.SampleFrequency);
hdr.nTrials = orig.TotalEpochs;
hdr.label = orig.ChannelOrder(:);
[hdr.grad, elec] = bti2grad(orig);
if ~isempty(elec),
hdr.elec = elec;
end
% remember original header details
hdr.orig = orig;
case 'bci2000_dat'
% this requires the load_bcidat mex file to be present on the path
ft_hastoolbox('BCI2000', 1);
% this is inefficient, since it reads the complete data
[signal, states, parameters, total_samples] = load_bcidat(filename);
% convert into a FieldTrip-like header
hdr = [];
hdr.nChans = size(signal,2);
hdr.nSamples = total_samples;
hdr.nSamplesPre = 0; % it is continuous
hdr.nTrials = 1; % it is continuous
hdr.Fs = parameters.SamplingRate.NumericValue;
% there are some differences in the fields that are present in the
% *.dat files, probably due to different BCI2000 versions
if isfield(parameters, 'ChannelNames') && isfield(parameters.ChannelNames, 'Value') && ~isempty(parameters.ChannelNames.Value)
hdr.label = parameters.ChannelNames.Value;
elseif isfield(parameters, 'ChannelNames') && isfield(parameters.ChannelNames, 'Values') && ~isempty(parameters.ChannelNames.Values)
hdr.label = parameters.ChannelNames.Values;
else
% give this warning only once
ft_warning('creating fake channel names');
for i=1:hdr.nChans
hdr.label{i} = sprintf('%d', i);
end
end
% remember the original header details
hdr.orig.parameters = parameters;
% also remember the complete data upon request
if cache
hdr.orig.signal = signal;
hdr.orig.states = states;
hdr.orig.total_samples = total_samples;
end
case 'besa_avr'
orig = read_besa_avr(filename);
hdr.Fs = 1000/orig.di;
hdr.nChans = size(orig.data,1);
hdr.nSamples = size(orig.data,2);
hdr.nSamplesPre = -(hdr.Fs * orig.tsb/1000); % convert from ms to samples
hdr.nTrials = 1;
if isfield(orig, 'label') && iscell(orig.label)
hdr.label = orig.label;
elseif isfield(orig, 'label') && ischar(orig.label)
hdr.label = tokenize(orig.label, ' ');
else
% give this warning only once
ft_warning('creating fake channel names');
for i=1:hdr.nChans
hdr.label{i} = sprintf('%d', i);
end
end
case 'besa_swf'
orig = read_besa_swf(filename);
hdr.Fs = 1000/orig.di;
hdr.nChans = size(orig.data,1);
hdr.nSamples = size(orig.data,2);
hdr.nSamplesPre = -(hdr.Fs * orig.tsb/1000); % convert from ms to samples
hdr.nTrials = 1;
hdr.label = orig.label;
case 'biosig'
% this requires the biosig toolbox
ft_hastoolbox('BIOSIG', 1);
hdr = read_biosig_header(filename);
case 'gdf'
% this requires the biosig toolbox
ft_hastoolbox('BIOSIG', 1);
% In the case that the gdf files are written by one of the FieldTrip
% realtime applications, such as biosig2ft, the gdf recording can be
% split over multiple 1GB files. The sequence of files is then
% filename.gdf <- this is the one that should be specified as the filename/dataset
% filename_1.gdf
% filename_2.gdf
% ...
[p, f, x] = fileparts(filename);
if exist(sprintf('%s_%d%s', fullfile(p, f), 1, x), 'file')
% there are multiple files, count the number of additional files (excluding the first one)
count = 0;
while exist(sprintf('%s_%d%s', fullfile(p, f), count+1, x), 'file')
count = count+1;
end
hdr = read_biosig_header(filename);
for i=1:count
hdr(i+1) = read_biosig_header(sprintf('%s_%d%s', fullfile(p, f), i, x));
% do some sanity checks
if hdr(i+1).nChans~=hdr(1).nChans
error('multiple GDF files detected that should be appended, but the channel count is inconsistent');
elseif hdr(i+1).Fs~=hdr(1).Fs
error('multiple GDF files detected that should be appended, but the sampling frequency is inconsistent');
elseif ~isequal(hdr(i+1).label, hdr(1).label)
error('multiple GDF files detected that should be appended, but the channel names are inconsistent');
end
end % for count
% combine all headers into one
combinedhdr = [];
combinedhdr.Fs = hdr(1).Fs;
combinedhdr.nChans = hdr(1).nChans;
combinedhdr.nSamples = sum([hdr.nSamples].*[hdr.nTrials]);
combinedhdr.nSamplesPre = 0;
combinedhdr.nTrials = 1;
combinedhdr.label = hdr(1).label;
combinedhdr.orig = hdr; % include all individual file details
hdr = combinedhdr;
else
% there is only a single file
hdr = read_biosig_header(filename);
% the GDF format is always continuous
hdr.nSamples = hdr.nSamples * hdr.nTrials;
hdr.nTrials = 1;
hdr.nSamplesPre = 0;
end % if single or multiple gdf files
case {'biosemi_bdf', 'bham_bdf'}
hdr = read_biosemi_bdf(filename);
if any(diff(hdr.orig.SampleRate))
error('channels with different sampling rate not supported');
end
if ~ft_senstype(hdr, 'ext1020')
% assign the channel type and units for the known channels
hdr.chantype = repmat({'unknown'}, size(hdr.label));
hdr.chanunit = repmat({'unknown'}, size(hdr.label));
chan = ~cellfun(@isempty, regexp(hdr.label, '^[A-D]\d*$'));
hdr.chantype(chan) = {'eeg'};
hdr.chanunit(chan) = {'uV'};
end
if ft_filetype(filename, 'bham_bdf')
% TODO channel renaming should be made a general option
% this is for the Biosemi system used at the University of Birmingham
labelold = { 'A1' 'A2' 'A3' 'A4' 'A5' 'A6' 'A7' 'A8' 'A9' 'A10' 'A11' 'A12' 'A13' 'A14' 'A15' 'A16' 'A17' 'A18' 'A19' 'A20' 'A21' 'A22' 'A23' 'A24' 'A25' 'A26' 'A27' 'A28' 'A29' 'A30' 'A31' 'A32' 'B1' 'B2' 'B3' 'B4' 'B5' 'B6' 'B7' 'B8' 'B9' 'B10' 'B11' 'B12' 'B13' 'B14' 'B15' 'B16' 'B17' 'B18' 'B19' 'B20' 'B21' 'B22' 'B23' 'B24' 'B25' 'B26' 'B27' 'B28' 'B29' 'B30' 'B31' 'B32' 'C1' 'C2' 'C3' 'C4' 'C5' 'C6' 'C7' 'C8' 'C9' 'C10' 'C11' 'C12' 'C13' 'C14' 'C15' 'C16' 'C17' 'C18' 'C19' 'C20' 'C21' 'C22' 'C23' 'C24' 'C25' 'C26' 'C27' 'C28' 'C29' 'C30' 'C31' 'C32' 'D1' 'D2' 'D3' 'D4' 'D5' 'D6' 'D7' 'D8' 'D9' 'D10' 'D11' 'D12' 'D13' 'D14' 'D15' 'D16' 'D17' 'D18' 'D19' 'D20' 'D21' 'D22' 'D23' 'D24' 'D25' 'D26' 'D27' 'D28' 'D29' 'D30' 'D31' 'D32' 'EXG1' 'EXG2' 'EXG3' 'EXG4' 'EXG5' 'EXG6' 'EXG7' 'EXG8' 'Status'};
labelnew = { 'P9' 'PPO9h' 'PO7' 'PPO5h' 'PPO3h' 'PO5h' 'POO9h' 'PO9' 'I1' 'OI1h' 'O1' 'POO1' 'PO3h' 'PPO1h' 'PPO2h' 'POz' 'Oz' 'Iz' 'I2' 'OI2h' 'O2' 'POO2' 'PO4h' 'PPO4h' 'PO6h' 'POO10h' 'PO10' 'PO8' 'PPO6h' 'PPO10h' 'P10' 'P8' 'TPP9h' 'TP7' 'TTP7h' 'CP5' 'TPP7h' 'P7' 'P5' 'CPP5h' 'CCP5h' 'CP3' 'P3' 'CPP3h' 'CCP3h' 'CP1' 'P1' 'Pz' 'CPP1h' 'CPz' 'CPP2h' 'P2' 'CPP4h' 'CP2' 'CCP4h' 'CP4' 'P4' 'P6' 'CPP6h' 'CCP6h' 'CP6' 'TPP8h' 'TP8' 'TPP10h' 'T7' 'FTT7h' 'FT7' 'FC5' 'FCC5h' 'C5' 'C3' 'FCC3h' 'FC3' 'FC1' 'C1' 'CCP1h' 'Cz' 'FCC1h' 'FCz' 'FFC1h' 'Fz' 'FFC2h' 'FC2' 'FCC2h' 'CCP2h' 'C2' 'C4' 'FCC4h' 'FC4' 'FC6' 'FCC6h' 'C6' 'TTP8h' 'T8' 'FTT8h' 'FT8' 'FT9' 'FFT9h' 'F7' 'FFT7h' 'FFC5h' 'F5' 'AFF7h' 'AF7' 'AF5h' 'AFF5h' 'F3' 'FFC3h' 'F1' 'AF3h' 'Fp1' 'Fpz' 'Fp2' 'AFz' 'AF4h' 'F2' 'FFC4h' 'F4' 'AFF6h' 'AF6h' 'AF8' 'AFF8h' 'F6' 'FFC6h' 'FFT8h' 'F8' 'FFT10h' 'FT10'};
% rename the channel labels
for i=1:length(labelnew)
chan = strcmp(labelold(i), hdr.label);
hdr.label(chan) = labelnew(chan);
end
end
case {'biosemi_old'}
% this uses the openbdf and readbdf functions that were copied from EEGLAB
orig = openbdf(filename);
if any(orig.Head.SampleRate~=orig.Head.SampleRate(1))
error('channels with different sampling rate not supported');
end
hdr.Fs = orig.Head.SampleRate(1);
hdr.nChans = orig.Head.NS;
hdr.label = cellstr(orig.Head.Label);
% it is continuous data, therefore append all records in one trial
hdr.nSamples = orig.Head.NRec * orig.Head.Dur * orig.Head.SampleRate(1);
hdr.nSamplesPre = 0;
hdr.nTrials = 1;
hdr.orig = orig;
% close the file between separate read operations
fclose(orig.Head.FILE.FID);
case {'brainvision_vhdr', 'brainvision_seg', 'brainvision_eeg', 'brainvision_dat'}
orig = read_brainvision_vhdr(filename);
hdr.Fs = orig.Fs;
hdr.nChans = orig.NumberOfChannels;
hdr.label = orig.label;
hdr.nSamples = orig.nSamples;
hdr.nSamplesPre = orig.nSamplesPre;
hdr.nTrials = orig.nTrials;
hdr.orig = orig;
% assign the channel type and units for the known channels
hdr.chantype = repmat({'eeg'}, size(hdr.label));
hdr.chanunit = repmat({'uV'}, size(hdr.label));
case 'ced_son'
% check that the required low-level toolbox is available
ft_hastoolbox('neuroshare', 1);
% use the reading function supplied by Gijs van Elswijk
orig = read_ced_son(filename,'readevents','no','readdata','no');
orig = orig.header;
% In Spike2, channels can have different sampling rates, units, length
% etc. etc. Here, channels need to have to same properties.
if length(unique([orig.samplerate]))>1,
error('channels with different sampling rates are not supported');
else
hdr.Fs = orig(1).samplerate;
end;
hdr.nChans = length(orig);
% nsamples of the channel with least samples
hdr.nSamples = min([orig.nsamples]);
hdr.nSamplesPre = 0;
% only continuous data supported
if sum(strcmpi({orig.mode},'continuous')) < hdr.nChans,
error('not all channels contain continuous data');
else
hdr.nTrials = 1;
end;
hdr.label = {orig.label};
case 'combined_ds'
hdr = read_combined_ds(filename);
case {'ctf_ds', 'ctf_meg4', 'ctf_res4'}
% check the presence of the required low-level toolbox
ft_hastoolbox('ctf', 1);
orig = readCTFds(filename);
if isempty(orig)
% this is to deal with data from the 64 channel system and the error
% readCTFds: .meg4 file header=MEG4CPT Valid header options: MEG41CP MEG42CP
error('could not read CTF with this implementation, please try again with the ''ctf_old'' file format');
end
hdr.Fs = orig.res4.sample_rate;
hdr.nChans = orig.res4.no_channels;
hdr.nSamples = orig.res4.no_samples;
hdr.nSamplesPre = orig.res4.preTrigPts;
hdr.nTrials = orig.res4.no_trials;
hdr.label = cellstr(orig.res4.chanNames);
for i=1:numel(hdr.label)
% remove the site-specific numbers from each channel name, e.g. 'MZC01-1706' becomes 'MZC01'
hdr.label{i} = strtok(hdr.label{i}, '-');
end
% read the balance coefficients, these are used to compute the synthetic gradients
coeftype = cellstr(char(orig.res4.scrr(:).coefType));
try
[alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig,'NONE', 'T');
orig.BalanceCoefs.none.alphaMEG = alphaMEG;
orig.BalanceCoefs.none.MEGlist = MEGlist;
orig.BalanceCoefs.none.Refindex = Refindex;
catch
warning('cannot read balancing coefficients for NONE');
end
if any(~cellfun(@isempty,strfind(coeftype, 'G1BR')))
try
[alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig,'G1BR', 'T');
orig.BalanceCoefs.G1BR.alphaMEG = alphaMEG;
orig.BalanceCoefs.G1BR.MEGlist = MEGlist;
orig.BalanceCoefs.G1BR.Refindex = Refindex;
catch
warning('cannot read balancing coefficients for G1BR');
end
end
if any(~cellfun(@isempty,strfind(coeftype, 'G2BR')))
try
[alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig, 'G2BR', 'T');
orig.BalanceCoefs.G2BR.alphaMEG = alphaMEG;
orig.BalanceCoefs.G2BR.MEGlist = MEGlist;
orig.BalanceCoefs.G2BR.Refindex = Refindex;
catch
warning('cannot read balancing coefficients for G2BR');
end
end
if any(~cellfun(@isempty,strfind(coeftype, 'G3BR')))
try
[alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig, 'G3BR', 'T');
orig.BalanceCoefs.G3BR.alphaMEG = alphaMEG;
orig.BalanceCoefs.G3BR.MEGlist = MEGlist;
orig.BalanceCoefs.G3BR.Refindex = Refindex;
catch
warning('cannot read balancing coefficients for G3BR');
end
end
if any(~cellfun(@isempty,strfind(coeftype, 'G3AR')))
try
[alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig, 'G3AR', 'T');
orig.BalanceCoefs.G3AR.alphaMEG = alphaMEG;
orig.BalanceCoefs.G3AR.MEGlist = MEGlist;
orig.BalanceCoefs.G3AR.Refindex = Refindex;
catch
% May not want a warning here if these are not commonly used.
% Already get a (fprintf) warning from getCTFBalanceCoefs.m
% warning('cannot read balancing coefficients for G3AR');
end
end
% add a gradiometer structure for forward and inverse modelling
try
hdr.grad = ctf2grad(orig, strcmp(coordsys, 'dewar'));
catch
% this fails if the res4 file is not correctly closed, e.g. during realtime processing
tmp = lasterror;
disp(tmp.message);
warning('could not construct gradiometer definition from the header');
end
% for realtime analysis EOF chasing the res4 does not correctly
% estimate the number of samples, so we compute it on the fly from the
% meg4 file sizes.
sz = 0;
files = dir([filename '/*.*meg4']);
for j=1:numel(files)
sz = sz + files(j).bytes;
end
hdr.nTrials = floor((sz - 8) / (hdr.nChans*4) / hdr.nSamples);
% add the original header details
hdr.orig = orig;
case {'ctf_old', 'read_ctf_res4'}
% read it using the open-source MATLAB code that originates from CTF and that was modified by the FCDC
orig = read_ctf_res4(headerfile);
hdr.Fs = orig.Fs;
hdr.nChans = orig.nChans;
hdr.nSamples = orig.nSamples;
hdr.nSamplesPre = orig.nSamplesPre;
hdr.nTrials = orig.nTrials;
hdr.label = orig.label;
% add a gradiometer structure for forward and inverse modelling
try
hdr.grad = ctf2grad(orig);
catch
% this fails if the res4 file is not correctly closed, e.g. during realtime processing
tmp = lasterror;
disp(tmp.message);
warning('could not construct gradiometer definition from the header');
end
% add the original header details
hdr.orig = orig;
case 'ctf_read_res4'
% check that the required low-level toolbos ix available
ft_hastoolbox('eegsf', 1);
% read it using the CTF importer from the NIH and Daren Weber
orig = ctf_read_res4(fileparts(headerfile), 0);
% convert the header into a structure that FieldTrip understands
hdr = [];
hdr.Fs = orig.setup.sample_rate;
hdr.nChans = length(orig.sensor.info);
hdr.nSamples = orig.setup.number_samples;
hdr.nSamplesPre = orig.setup.pretrigger_samples;
hdr.nTrials = orig.setup.number_trials;
for i=1:length(orig.sensor.info)
hdr.label{i} = orig.sensor.info(i).label;
end
hdr.label = hdr.label(:);
% add a gradiometer structure for forward and inverse modelling
try
hdr.grad = ctf2grad(orig);
catch
% this fails if the res4 file is not correctly closed, e.g. during realtime processing
tmp = lasterror;
disp(tmp.message);
warning('could not construct gradiometer definition from the header');
end
% add the original header details
hdr.orig = orig;
case 'ctf_shm'
% read the header information from shared memory
hdr = read_shm_header(filename);
case 'dataq_wdq'
orig = read_wdq_header(filename);
hdr = [];
hdr.Fs = orig.fsample;
hdr.nChans = orig.nchan;
hdr.nSamples = orig.nbytesdat/(2*hdr.nChans);
hdr.nSamplesPre = 0;
hdr.nTrials = 1;
for k = 1:hdr.nChans
if isfield(orig.chanhdr(k), 'annot') && ~isempty(orig.chanhdr(k).annot)
hdr.label{k,1} = orig.chanhdr(k).annot;
else
hdr.label{k,1} = orig.chanhdr(k).label;
end
end
% add the original header details
hdr.orig = orig;
case {'deymed_ini' 'deymed_dat'}
% the header is stored in a *.ini file
orig = read_deymed_ini(headerfile);
hdr = [];
hdr.Fs = orig.Fs;
hdr.nChans = orig.nChans;
hdr.nSamples = orig.nSamples;
hdr.nSamplesPre = 0;
hdr.nTrials = 1;
hdr.label = orig.label(:);
hdr.orig = orig; % remember the original details
case 'edf'
% this reader is largely similar to the bdf reader
if isempty(chanindx)
hdr = read_edf(filename);
else
hdr = read_edf(filename,[],1);
if chanindx > hdr.orig.NS
error('FILEIO:InvalidChanIndx', 'selected channels are not present in the data');
else
hdr = read_edf(filename,[],chanindx);
end;
end;
case 'eep_avr'
% check that the required low-level toolbox is available
ft_hastoolbox('eeprobe', 1);
% read the whole average and keep only header info (it is a bit silly, but the easiest to do here)
hdr = read_eep_avr(filename);
hdr.Fs = hdr.rate;
hdr.nChans = size(hdr.data,1);
hdr.nSamples = size(hdr.data,2);
hdr.nSamplesPre = hdr.xmin*hdr.rate/1000;
hdr.nTrials = 1; % it can always be interpreted as continuous data
% remove the data and variance if present
hdr = removefields(hdr, {'data', 'variance'});
case 'eep_cnt'
% check that the required low-level toolbox is available
ft_hastoolbox('eeprobe', 1);
% read the first sample from the continous data, this will also return the header
orig = read_eep_cnt(filename, 1, 1);
hdr.Fs = orig.rate;
hdr.nSamples = orig.nsample;
hdr.nSamplesPre = 0;
hdr.label = orig.label;
hdr.nChans = orig.nchan;
hdr.nTrials = 1; % it can always be interpreted as continuous data
hdr.orig = orig; % remember the original details
case 'eeglab_set'
hdr = read_eeglabheader(filename);
case 'eeglab_erp'
hdr = read_erplabheader(filename);
case 'emotiv_mat'
% This is a MATLAB *.mat file that is created using the Emotiv MATLAB
% example code. It contains a 25xNsamples matrix and some other stuff.
orig = load(filename);
hdr.Fs = 128;
hdr.nChans = 25;
hdr.nSamples = size(orig.data_eeg,1);
hdr.nSamplesPre = 0;
hdr.nTrials = 1;
hdr.label = {'ED_COUNTER','ED_INTERPOLATED','ED_RAW_CQ','ED_AF3','ED_F7','ED_F3','ED_FC5','ED_T7','ED_P7','ED_O1','ED_O2','ED_P8','ED_T8','ED_FC6','ED_F4','ED_F8','ED_AF4','ED_GYROX','ED_GYROY','ED_TIMESTAMP','ED_ES_TIMESTAMP','ED_FUNC_ID','ED_FUNC_VALUE','ED_MARKER','ED_SYNC_SIGNAL'};
% store the complete information in hdr.orig
% ft_read_data and ft_read_event will get it from there
hdr.orig = orig;
case 'eyelink_asc'
asc = read_eyelink_asc(filename);
hdr.nChans = size(asc.dat,1);
hdr.nSamples = size(asc.dat,2);
hdr.nSamplesPre = 0;
hdr.nTrials = 1;
hdr.FirstTimeStamp = asc.dat(1,1);
hdr.TimeStampPerSample = mean(diff(asc.dat(1,:)));
hdr.Fs = 1000/hdr.TimeStampPerSample; % these timestamps are in miliseconds
% give this warning only once
ft_warning('creating fake channel names');
for i=1:hdr.nChans
hdr.label{i} = sprintf('%d', i);
end
% remember the original header details
hdr.orig.header = asc.header;
% remember all header and data details upon request
if cache
hdr.orig = asc;
end
case 'spmeeg_mat'
hdr = read_spmeeg_header(filename);
case 'ced_spike6mat'
hdr = read_spike6mat_header(filename);
case 'egi_egia'
[fhdr,chdr,ename,cnames,fcom,ftext] = read_egis_header(filename);
[p, f, x] = fileparts(filename);
if any(chdr(:,4)-chdr(1,4))
error('Sample rate not the same for all cells.');
end;
hdr.Fs = chdr(1,4); %making assumption that sample rate is same for all cells
hdr.nChans = fhdr(19);
for i = 1:hdr.nChans
% this should be consistent with ft_senslabel
hdr.label{i,1} = ['E' num2str(i)];
end;
%since NetStation does not properly set the fhdr(11) field, use the number of subjects from the chdr instead
hdr.nTrials = chdr(1,2)*fhdr(18); %number of trials is numSubjects * numCells
hdr.nSamplesPre = ceil(fhdr(14)/(1000/hdr.Fs));
if any(chdr(:,3)-chdr(1,3))
error('Number of samples not the same for all cells.');
end;
hdr.nSamples = chdr(1,3); %making assumption that number of samples is same for all cells
% remember the original header details
hdr.orig.fhdr = fhdr;
hdr.orig.chdr = chdr;
hdr.orig.ename = ename;
hdr.orig.cnames = cnames;
hdr.orig.fcom = fcom;
hdr.orig.ftext = ftext;
case 'egi_egis'
[fhdr,chdr,ename,cnames,fcom,ftext] = read_egis_header(filename);
[p, f, x] = fileparts(filename);
if any(chdr(:,4)-chdr(1,4))
error('Sample rate not the same for all cells.');
end;
hdr.Fs = chdr(1,4); %making assumption that sample rate is same for all cells
hdr.nChans = fhdr(19);
for i = 1:hdr.nChans
% this should be consistent with ft_senslabel
hdr.label{i,1} = ['E' num2str(i)];
end;
hdr.nTrials = sum(chdr(:,2));
hdr.nSamplesPre = ceil(fhdr(14)/(1000/hdr.Fs));
% assuming that a utility was used to insert the correct baseline
% duration into the header since it is normally absent. This slot is
% actually allocated to the age of the subject, although NetStation
% does not use it when generating an EGIS session file.
if any(chdr(:,3)-chdr(1,3))
error('Number of samples not the same for all cells.');
end;
hdr.nSamples = chdr(1,3); %making assumption that number of samples is same for all cells
% remember the original header details
hdr.orig.fhdr = fhdr;
hdr.orig.chdr = chdr;
hdr.orig.ename = ename;
hdr.orig.cnames = cnames;
hdr.orig.fcom = fcom;
hdr.orig.ftext = ftext;
case 'egi_sbin'
[header_array, CateNames, CatLengths, preBaseline] = read_sbin_header(filename);
[p, f, x] = fileparts(filename);
hdr.Fs = header_array(9);
hdr.nChans = header_array(10);
for i = 1:hdr.nChans
% this should be consistent with ft_senslabel
hdr.label{i,1} = ['E' num2str(i)];
end;
hdr.nTrials = header_array(15);
hdr.nSamplesPre = preBaseline;
hdr.nSamples = header_array(16); % making assumption that number of samples is same for all cells
% remember the original header details
hdr.orig.header_array = header_array;
hdr.orig.CateNames = CateNames;
hdr.orig.CatLengths = CatLengths;
case {'egi_mff_v1' 'egi_mff'} % this is currently the default
% The following represents the code that was written by Ingrid, Robert
% and Giovanni to get started with the EGI mff dataset format. It might
% not support all details of the file formats.
%
% An alternative implementation has been provided by EGI, this is
% released as fieldtrip/external/egi_mff and referred further down in
% this function as 'egi_mff_v2'.
if ~usejava('jvm')
error('the xml2struct requires MATLAB to be running with the Java virtual machine (JVM)');
% an alternative implementation which does not require the JVM but runs much slower is
% available from http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0
end
% get header info from .bin files
binfiles = dir(fullfile(filename, 'signal*.bin'));
if isempty(binfiles)
error('could not find any signal.bin in mff directory')
end
orig = [];
for iSig = 1:length(binfiles)
signalname = binfiles(iSig).name;
fullsignalname = fullfile(filename, signalname);
orig.signal(iSig).blockhdr = read_mff_bin(fullsignalname);
end
% get hdr info from xml files
warning('off', 'MATLAB:REGEXP:deprecated') % due to some small code xml2struct
xmlfiles = dir( fullfile(filename, '*.xml'));
disp('reading xml files to obtain header info...')
for i = 1:numel(xmlfiles)
if strcmpi(xmlfiles(i).name(1:2), '._') % Mac sometimes creates this useless files, don't use them
elseif strcmpi(xmlfiles(i).name(1:6), 'Events') % don't read in events here, can take a lot of time, and we can do that in ft_read_event
else
fieldname = xmlfiles(i).name(1:end-4);
filename_xml = fullfile(filename, xmlfiles(i).name);
orig.xml.(fieldname) = xml2struct(filename_xml);
end
end
warning('on', 'MATLAB:REGEXP:deprecated')
% epochs.xml seems the most common version, but epoch.xml might also
% occur, so use only one name
if isfield(orig.xml, 'epoch')
orig.xml.epochs = orig.xml.epoch;
orig.xml = rmfield(orig.xml, 'epoch');
end
% make hdr according to FieldTrip rules
hdr = [];
Fs = zeros(length(orig.signal),1);
nChans = zeros(length(orig.signal),1);
nSamples = zeros(length(orig.signal),1);
for iSig = 1:length(orig.signal)
Fs(iSig) = orig.signal(iSig).blockhdr(1).fsample(1);
nChans(iSig) = orig.signal(iSig).blockhdr(1).nsignals;
% the number of samples per block can be different
nSamples_Block = zeros(length(orig.signal(iSig).blockhdr),1);
for iBlock = 1:length(orig.signal(iSig).blockhdr)
nSamples_Block(iBlock) = orig.signal(iSig).blockhdr(iBlock).nsamples(1);
end
nSamples(iSig) = sum(nSamples_Block);
end
if length(unique(Fs)) > 1 || length(unique(nSamples)) > 1
error('Fs and nSamples should be the same in all signals')
end
hdr.Fs = Fs(1);
hdr.nChans = sum(nChans);
hdr.nSamplesPre = 0;
hdr.nSamples = nSamples(1);
hdr.nTrials = 1;
% get channel labels for signal 1 (main net), otherwise create them
if isfield(orig.xml, 'sensorLayout') % asuming that signal1 is hdEEG sensornet, and channels are in xml file sensorLayout
for iSens = 1:numel(orig.xml.sensorLayout.sensors)
if ~isempty(orig.xml.sensorLayout.sensors(iSens).sensor.name) && ~(isstruct(orig.xml.sensorLayout.sensors(iSens).sensor.name) && numel(fieldnames(orig.xml.sensorLayout.sensors(iSens).sensor.name))==0)
%only get name when channel is EEG (type 0), or REF (type 1),
%rest are non interesting channels like place holders and COM and should not be added.
if strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '0') || strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '1')
% get the sensor name from the datafile
hdr.label{iSens} = orig.xml.sensorLayout.sensors(iSens).sensor.name;
end
elseif strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '0') % EEG chan
% this should be consistent with ft_senslabel
hdr.label{iSens} = ['E' num2str(orig.xml.sensorLayout.sensors(iSens).sensor.number)];
elseif strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '1') % REF chan
% ingnie: I now choose REF as name for REF channel since our discussion see bug 1407. Arbitrary choice...
hdr.label{iSens} = ['REF' num2str(iSens)];
else
% non interesting channels like place holders and COM
end
end
% check if the amount of lables corresponds with nChannels in signal 1
if length(hdr.label) == nChans(1)
% good
elseif length(hdr.label) > orig.signal(1).blockhdr(1).nsignals
warning('found more lables in xml.sensorLayout than channels in signal 1, thus can not use info in sensorLayout, creating labels on the fly')
for iSens = 1:orig.signal(1).blockhdr(1).nsignals
% this should be consistent with ft_senslabel
hdr.label{iSens} = ['E' num2str(iSens)];
end
else warning('found less lables in xml.sensorLayout than channels in signal 1, thus can not use info in sensorLayout, creating labels on the fly')
for iSens = 1:orig.signal(1).blockhdr(1).nsignals
% this should be consistent with ft_senslabel
hdr.label{iSens} = ['E' num2str(iSens)];
end
end
% get lables for other signals
if length(orig.signal) == 2
if isfield(orig.xml, 'pnsSet') % signal2 is PIB box, and lables are in xml file pnsSet
nbEEGchan = length(hdr.label);
for iSens = 1:numel(orig.xml.pnsSet.sensors)
hdr.label{nbEEGchan+iSens} = num2str(orig.xml.pnsSet.sensors(iSens).sensor.name);
end
if length(hdr.label) == orig.signal(2).blockhdr(1).nsignals + orig.signal(2).blockhdr(1).nsignals
% good
elseif length(hdr.label) < orig.signal(1).blockhdr(1).nsignals + orig.signal(2).blockhdr(1).nsignals
warning('found less lables in xml.pnsSet than channels in signal 2, labeling with s2_unknownN instead')
for iSens = length(hdr.label)+1 : orig.signal(1).blockhdr(1).nsignals + orig.signal(2).blockhdr(1).nsignals
hdr.label{iSens} = ['s2_unknown', num2str(iSens)];
end
else warning('found more lables in xml.pnsSet than channels in signal 2, thus can not use info in pnsSet, and labeling with s2_eN instead')
for iSens = orig.signal(1).blockhdr(1).nsignals+1 : orig.signal(1).blockhdr(1).nsignals + orig.signal(2).blockhdr(1).nsignals
hdr.label{iSens} = ['s2_E', num2str(iSens)];
end
end
else % signal2 is not PIBbox
warning('creating channel labels for signal 2 on the fly')
for iSens = 1:orig.signal(2).blockhdr(1).nsignals
hdr.label{end+1} = ['s2_E', num2str(iSens)];
end
end
elseif length(orig.signal) > 2
% loop over signals and label channels accordingly
warning('creating channel labels for signal 2 to signal N on the fly')
for iSig = 2:length(orig.signal)
for iSens = 1:orig.signal(iSig).blockhdr(1).nsignals
if iSig == 1 && iSens == 1
hdr.label{1} = ['s',num2str(iSig),'_E', num2str(iSens)];
else
hdr.label{end+1} = ['s',num2str(iSig),'_E', num2str(iSens)];
end
end
end
end
else % no xml.sensorLayout present
warning('no sensorLayout found in xml files, creating channel labels on the fly')
for iSig = 1:length(orig.signal)
for iSens = 1:orig.signal(iSig).blockhdr(1).nsignals
if iSig == 1 && iSens == 1
hdr.label{1} = ['s',num2str(iSig),'_E', num2str(iSens)];
else
hdr.label{end+1} = ['s',num2str(iSig),'_E', num2str(iSens)];
end
end
end
end
% check if multiple epochs are present
if isfield(orig.xml,'epochs')
% add info to header about which sample correspond to which epochs, becasue this is quite hard for user to get...
epochdef = zeros(length(orig.xml.epochs),3);
for iEpoch = 1:length(orig.xml.epochs)
if iEpoch == 1
epochdef(iEpoch,1) = round(str2double(orig.xml.epochs(iEpoch).epoch.beginTime)./(1000000./hdr.Fs))+1;
epochdef(iEpoch,2) = round(str2double(orig.xml.epochs(iEpoch).epoch.endTime )./(1000000./hdr.Fs));
epochdef(iEpoch,3) = round(str2double(orig.xml.epochs(iEpoch).epoch.beginTime)./(1000000./hdr.Fs)); % offset corresponds to timing
else
NbSampEpoch = round(str2double(orig.xml.epochs(iEpoch).epoch.endTime)./(1000000./hdr.Fs) - str2double(orig.xml.epochs(iEpoch).epoch.beginTime)./(1000000./hdr.Fs));
epochdef(iEpoch,1) = epochdef(iEpoch-1,2) + 1;
epochdef(iEpoch,2) = epochdef(iEpoch-1,2) + NbSampEpoch;
epochdef(iEpoch,3) = round(str2double(orig.xml.epochs(iEpoch).epoch.beginTime)./(1000000./hdr.Fs)); % offset corresponds to timing
end
end
if epochdef(end,2) ~= hdr.nSamples
% check for NS 4.5.4 picosecond timing
if (epochdef(end,2)/1000) == hdr.nSamples
for iEpoch=1:size(epochdef,1)
epochdef(iEpoch,1) = ((epochdef(iEpoch,1)-1)/1000)+1;
epochdef(iEpoch,2) = epochdef(iEpoch,2)/1000;
epochdef(iEpoch,3) = epochdef(iEpoch,3)/1000;
end;
warning('mff apparently generated by NetStation 4.5.4. Adjusting time scale to microseconds from nanoseconds.');
else
error('number of samples in all epochs do not add up to total number of samples')
end
end
epochLengths = epochdef(:,2)-epochdef(:,1)+1;
if ~any(diff(epochLengths))
hdr.nSamples = epochLengths(1);
hdr.nTrials = length(epochLengths);
else
warning('the data contains multiple epochs with variable length, possibly causing discontinuities in the data')
% sanity check
if epochdef(end,2) ~= hdr.nSamples
% check for NS 4.5.4 picosecond timing
if (epochdef(end,2)/1000) == hdr.nSamples
for iEpoch=1:size(epochdef,1)
epochdef(iEpoch,1)=((epochdef(iEpoch,1)-1)/1000)+1;
epochdef(iEpoch,2)=epochdef(iEpoch,2)/1000;
epochdef(iEpoch,3)=epochdef(iEpoch,3)/1000;
end;
disp('mff apparently generated by NetStation 4.5.4. Adjusting time scale to microseconds from nanoseconds.');
else
error('number of samples in all epochs do not add up to total number of samples')
end;
end
end
orig.epochdef = epochdef;
end;
hdr.orig = orig;
case 'egi_mff_v2'
% ensure that the EGI_MFF toolbox is on the path
ft_hastoolbox('egi_mff', 1);
% ensure that the JVM is running and the jar file is on the path
%%%%%%%%%%%%%%%%%%%%%%
%workaround for MATLAB bug resulting in global variables being cleared
globalTemp=cell(0);
globalList=whos('global');
varList=whos;
for i=1:length(globalList)
eval(['global ' globalList(i).name ';']);
eval(['globalTemp{end+1}=' globalList(i).name ';']);
end;
%%%%%%%%%%%%%%%%%%%%%%
mff_setup;
%%%%%%%%%%%%%%%%%%%%%%
%workaround for MATLAB bug resulting in global variables being cleared
varNames={varList.name};
for i=1:length(globalList)
eval(['global ' globalList(i).name ';']);
eval([globalList(i).name '=globalTemp{i};']);
if ~any(strcmp(globalList(i).name,varNames)) %was global variable originally out of scope?
eval(['clear ' globalList(i).name ';']); %clears link to global variable without affecting it
end;
end;
clear globalTemp globalList varNames varList;
%%%%%%%%%%%%%%%%%%%%%%
if isunix && filename(1)~=filesep
% add the full path to the dataset directory
filename = fullfile(pwd, filename);
elseif ispc && filename(2)~=':'
% add the full path, including drive letter
filename = fullfile(pwd, filename);
end
hdr = read_mff_header(filename);
case 'fcdc_buffer'
% read from a networked buffer for realtime analysis
[host, port] = filetype_check_uri(filename);
if retry
orig = [];
while isempty(orig)
try
% try reading the header, catch the error and retry
orig = buffer('get_hdr', [], host, port);
catch
warning('could not read header from %s, retrying in 1 second', filename);
pause(1);
end
end % while
else
% try reading the header only once, give error if it fails
orig = buffer('get_hdr', [], host, port);
end % if retry
% construct the standard header elements
hdr.Fs = orig.fsample;
hdr.nChans = orig.nchans;
hdr.nSamples = orig.nsamples;
hdr.nSamplesPre = 0; % since continuous
hdr.nTrials = 1; % since continuous
hdr.orig = []; % this will contain the chunks (if present)
% add the contents of attached FIF_header chunk after decoding to MATLAB structure
if isfield(orig, 'neuromag_header')
if isempty(cachechunk)
% this only needs to be decoded once
cachechunk = decode_fif(orig);
end
% convert to fieldtrip format header
hdr.label = cachechunk.ch_names(:);
hdr.nChans = cachechunk.nchan;
hdr.Fs = cachechunk.sfreq;
% add a gradiometer structure for forward and inverse modelling
try
[grad, elec] = mne2grad(cachechunk, 1); % 1: 'coordsys' = 'dewar'
if ~isempty(grad)
hdr.grad = grad;
end
if ~isempty(elec)
hdr.elec = elec;
end
catch
disp(lasterr);
end
% store the original details
hdr.orig = cachechunk;
end
% add the contents of attached RES4 chunk after decoding to MATLAB structure
if isfield(orig, 'ctf_res4')
if isempty(cachechunk)
% this only needs to be decoded once
cachechunk = decode_res4(orig.ctf_res4);
end
% copy the gradiometer details
hdr.grad = cachechunk.grad;
hdr.orig = cachechunk.orig;
if isfield(orig, 'channel_names')
% get the same selection of channels from the two chunks
[selbuf, selres4] = match_str(orig.channel_names, cachechunk.label);
if length(selres4)<length(orig.channel_names)
error('the res4 chunk did not contain all channels')
end
% copy some of the channel details
hdr.label = cachechunk.label(selres4);
hdr.chantype = cachechunk.chantype(selres4);
hdr.chanunit = cachechunk.chanunit(selres4);
% add the channel names chunk as well
hdr.orig.channel_names = orig.channel_names;
end
% add the raw chunk as well
hdr.orig.ctf_res4 = orig.ctf_res4;
end
% add the contents of attached NIFTI-1 chunk after decoding to MATLAB structure
if isfield(orig, 'nifti_1')
hdr.nifti_1 = decode_nifti1(orig.nifti_1);
% add the raw chunk as well
hdr.orig.nifti_1 = orig.nifti_1;
end
% add the contents of attached SiemensAP chunk after decoding to MATLAB structure
if isfield(orig, 'siemensap') && exist('sap2matlab')==3 % only run this if MEX file is present
hdr.siemensap = sap2matlab(orig.siemensap);
% add the raw chunk as well
hdr.orig.siemensap = orig.siemensap;
end
if ~isfield(hdr, 'label')
% prevent overwriting the labels that we might have gotten from a RES4 chunk
if isfield(orig, 'channel_names')
hdr.label = orig.channel_names;
else
hdr.label = cell(hdr.nChans,1);
if hdr.nChans < 2000 % don't do this for fMRI etc.
ft_warning('creating fake channel names'); % give this warning only once
for i=1:hdr.nChans
hdr.label{i} = sprintf('%d', i);
end
else
ft_warning('skipping fake channel names'); % give this warning only once
checkUniqueLabels = false;
end
end
end
if ~isfield(hdr, 'chantype')
% prevent overwriting the chantypes that we might have gotten from a RES4 chunk
hdr.chantype = cell(hdr.nChans,1);
if hdr.nChans < 2000 % don't do this for fMRI etc.
hdr.chantype = repmat({'unknown'}, 1, hdr.nChans);
end
end
if ~isfield(hdr, 'chanunit')
% prevent overwriting the chanunits that we might have gotten from a RES4 chunk
hdr.chanunit = cell(hdr.nChans,1);
if hdr.nChans < 2000 % don't do this for fMRI etc.
hdr.chanunit = repmat({'unknown'}, 1, hdr.nChans);
end
end
hdr.orig.bufsize = orig.bufsize;
case 'fcdc_buffer_offline'
[hdr, nameFlag] = read_buffer_offline_header(headerfile);
switch nameFlag
case 0
% no labels generated (fMRI etc)
checkUniqueLabels = false; % no need to check these
case 1
% has generated fake channels
% give this warning only once
ft_warning('creating fake channel names');
checkUniqueLabels = false; % no need to check these
case 2
% got labels from chunk, check those
checkUniqueLabels = true;
end
case 'fcdc_matbin'
% this is multiplexed data in a *.bin file, accompanied by a MATLAB file containing the header
load(headerfile, 'hdr');
case 'fcdc_mysql'
% check that the required low-level toolbox is available
ft_hastoolbox('mysql', 1);
% read from a MySQL server listening somewhere else on the network
db_open(filename);
if db_blob
hdr = db_select_blob('fieldtrip.header', 'msg', 1);
else
hdr = db_select('fieldtrip.header', {'nChans', 'nSamples', 'nSamplesPre', 'Fs', 'label'}, 1);
hdr.label = mxDeserialize(hdr.label);
end
case 'gtec_mat'
% this is a simple MATLAB format, it contains a log and a names variable
tmp = load(headerfile);
log = tmp.log;
names = tmp.names;
hdr.label = cellstr(names);
hdr.nChans = size(log,1);
hdr.nSamples = size(log,2);
hdr.nSamplesPre = 0;
hdr.nTrials = 1; % assume continuous data, not epoched
% compute the sampling frequency from the time channel
sel = strcmp(hdr.label, 'Time');
time = log(sel,:);
hdr.Fs = 1./(time(2)-time(1));
% also remember the complete data upon request
if cache
hdr.orig.log = log;
hdr.orig.names = names;
end
case {'itab_raw' 'itab_mhd'}
% read the full header information frtom the binary header structure
header_info = read_itab_mhd(headerfile);
% these are the channels that are visible to fieldtrip
chansel = 1:header_info.nchan;
% convert the header information into a fieldtrip compatible format
hdr.nChans = length(chansel);
hdr.label = {header_info.ch(chansel).label};
hdr.label = hdr.label(:); % should be column vector
hdr.Fs = header_info.smpfq;
% it will always be continuous data
hdr.nSamples = header_info.ntpdata;
hdr.nSamplesPre = 0; % it is a single continuous trial
hdr.nTrials = 1; % it is a single continuous trial
% keep the original details AND the list of channels as used by fieldtrip
hdr.orig = header_info;
hdr.orig.chansel = chansel;
% add the gradiometer definition
hdr.grad = itab2grad(header_info);
case 'jaga16'
% this is hard-coded for the Jinga-Hi JAGA16 system with 16 channels
packetsize = (4*2 + 6*2 + 16*43*2); % in bytes
% read the first packet
fid = fopen(filename, 'r');
buf = fread(fid, packetsize/2, 'uint16');
fclose(fid);
if buf(1)==0
% it does not have timestamps, i.e. it is the raw UDP stream
packetsize = packetsize - 8; % in bytes
packet = jaga16_packet(buf(1:(packetsize/2)), false);
else
% each packet starts with a timestamp
packet = jaga16_packet(buf, true);
end
% determine the number of packets from the file size
info = dir(filename);
npackets = floor((info.bytes)/packetsize/2);
hdr = [];
hdr.Fs = packet.fsample;
hdr.nChans = packet.nchan;
hdr.nSamples = 43;
hdr.nSamplesPre = 0;
hdr.nTrials = npackets;
hdr.label = cell(hdr.nChans,1);
hdr.chantype = cell(hdr.nChans,1);
hdr.chanunit = cell(hdr.nChans,1);
for i=1:hdr.nChans
hdr.label{i} = sprintf('%d', i);
hdr.chantype{i} = 'eeg';
hdr.chanunit{i} = 'uV';
end
% store some low-level details
hdr.orig.offset = 0;
hdr.orig.packetsize = packetsize;
hdr.orig.packet = packet;
hdr.orig.info = info;
case 'micromed_trc'
orig = read_micromed_trc(filename);
hdr = [];
hdr.Fs = orig.Rate_Min; % FIXME is this correct?
hdr.nChans = orig.Num_Chan;
hdr.nSamples = orig.Num_Samples;
hdr.nSamplesPre = 0; % continuous
hdr.nTrials = 1; % continuous
hdr.label = cell(1,hdr.nChans);
% give this warning only once
warning('creating fake channel names');
for i=1:hdr.nChans
hdr.label{i} = sprintf('%d', i);
end
% this should be a column vector
hdr.label = hdr.label(:);
% remember the original header details
hdr.orig = orig;
case {'mpi_ds', 'mpi_dap'}
hdr = read_mpi_ds(filename);
case 'netmeg'
ft_hastoolbox('netcdf', 1);
% this will read all NetCDF data from the file and subsequently convert
% each of the three elements into a more easy to parse MATLAB structure
s = netcdf(filename);
for i=1:numel(s.AttArray)
fname = fixname(s.AttArray(i).Str);
fval = s.AttArray(i).Val;
if ischar(fval)
fval = fval(fval~=0); % remove the \0 characters
fval = strtrim(fval); % remove insignificant whitespace
end
Att.(fname) = fval;
end
for i=1:numel(s.VarArray)
fname = fixname(s.VarArray(i).Str);
fval = s.VarArray(i).Data;
if ischar(fval)
fval = fval(fval~=0); % remove the \0 characters
fval = strtrim(fval); % remove insignificant whitespace
end
Var.(fname) = fval;
end
for i=1:numel(s.DimArray)
fname = fixname(s.DimArray(i).Str);
fval = s.DimArray(i).Dim;
if ischar(fval)
fval = fval(fval~=0); % remove the \0 characters
fval = strtrim(fval); % remove insignificant whitespace
end
Dim.(fname) = fval;
end
% convert the relevant fields into teh default header structure
hdr.Fs = 1000/Var.samplinginterval;
hdr.nChans = length(Var.channelstatus);
hdr.nSamples = Var.numsamples;
hdr.nSamplesPre = 0;
hdr.nTrials = size(Var.waveforms, 1);
hdr.chanunit = cellstr(reshape(Var.channelunits, hdr.nChans, 2));
hdr.chantype = cellstr(reshape(lower(Var.channeltypes), hdr.nChans, 3));
ft_warning('creating fake channel names');
hdr.label = cell(hdr.nChans, 1);
for i=1:hdr.nChans
hdr.label{i} = sprintf('%d', i);
end
% remember the original details of the file
% note that this also includes the data
% this is large, but can be reused elsewhere
hdr.orig.Att = Att;
hdr.orig.Var = Var;
hdr.orig.Dim = Dim;
% construct the gradiometer structure from the complete header information
hdr.grad = netmeg2grad(hdr);
case 'neuralynx_dma'
hdr = read_neuralynx_dma(filename);
case 'neuralynx_sdma'
hdr = read_neuralynx_sdma(filename);
case 'neuralynx_ncs'
ncs = read_neuralynx_ncs(filename, 1, 0);
[p, f, x] = fileparts(filename);
hdr.Fs = ncs.hdr.SamplingFrequency;
hdr.label = {f};
hdr.nChans = 1;
hdr.nTrials = 1;
hdr.nSamplesPre = 0;
hdr.nSamples = ncs.NRecords * 512;
hdr.orig = ncs.hdr;
FirstTimeStamp = ncs.hdr.FirstTimeStamp; % this is the first timestamp of the first block
LastTimeStamp = ncs.hdr.LastTimeStamp; % this is the first timestamp of the last block, i.e. not the timestamp of the last sample
hdr.TimeStampPerSample = double(LastTimeStamp - FirstTimeStamp) ./ ((ncs.NRecords-1)*512);
hdr.FirstTimeStamp = FirstTimeStamp;
case 'neuralynx_nse'
nse = read_neuralynx_nse(filename, 1, 0);
[p, f, x] = fileparts(filename);
hdr.Fs = nse.hdr.SamplingFrequency;
hdr.label = {f};
hdr.nChans = 1;
hdr.nTrials = nse.NRecords; % each record contains one waveform
hdr.nSamples = 32; % there are 32 samples in each waveform
hdr.nSamplesPre = 0;
hdr.orig = nse.hdr;
% FIXME add hdr.FirstTimeStamp and hdr.TimeStampPerSample
case {'neuralynx_ttl', 'neuralynx_tsl', 'neuralynx_tsh'}
% these are hardcoded, they contain an 8-byte header and int32 values for a single channel
% FIXME this should be done similar as neuralynx_bin, i.e. move the hdr into the function
hdr = [];
hdr.Fs = 32556;
hdr.nChans = 1;
hdr.nSamples = (filesize(filename)-8)/4;
hdr.nSamplesPre = 1;
hdr.nTrials = 1;
hdr.label = {headerformat((end-3):end)};
case 'neuralynx_bin'
hdr = read_neuralynx_bin(filename);
case 'neuralynx_ds'
hdr = read_neuralynx_ds(filename);
case 'neuralynx_cds'
hdr = read_neuralynx_cds(filename);
case 'nexstim_nxe'
hdr = read_nexstim_nxe(filename);
case {'neuromag_fif' 'neuromag_mne'}
% check that the required low-level toolbox is available
ft_hastoolbox('mne', 1);
info = fiff_read_meas_info(filename);
% convert to fieldtrip format header
hdr.label = info.ch_names(:);
hdr.nChans = info.nchan;
hdr.Fs = info.sfreq;
% add a gradiometer structure for forward and inverse modelling
try
[grad, elec] = mne2grad(info, strcmp(coordsys, 'dewar'));
if ~isempty(grad)
hdr.grad = grad;
end
if ~isempty(elec)
hdr.elec = elec;
end
catch
disp(lasterr);
end
iscontinuous = 0;
isepoched = 0;
isaverage = 0;
if isempty(fiff_find_evoked(filename)) % true if file contains no evoked responses
try
epochs = fiff_read_epochs(filename);
isepoched = 1;
catch
% the "catch me" syntax is broken on MATLAB74, this fixes it
me = lasterror;
if strcmp(me.identifier, 'MNE:fiff_read_events')
iscontinuous = 1;
else
rethrow(me)
end
end
else
isaverage = 1;
end
if iscontinuous
try
% we only use 1 input argument here to allow backward
% compatibility up to MNE 2.6.x:
raw = fiff_setup_read_raw(filename);
catch
% the "catch me" syntax is broken on MATLAB74, this fixes it
me = lasterror;
% there is an error - we try to use MNE 2.7.x (if present) to
% determine if the cause is maxshielding:
try
allow_maxshield = true;
raw = fiff_setup_read_raw(filename,allow_maxshield);
catch
% unknown problem, or MNE version 2.6.x or less:
rethrow(me);
end
% no error message from fiff_setup_read_raw? Then maxshield
% was applied, but maxfilter wasn't, so return this error:
if istrue(checkmaxfilter)
error('Maxshield data should be corrected using Maxfilter prior to importing in FieldTrip.');
else
ft_warning('Maxshield data should be corrected using Maxfilter prior to importing in FieldTrip.');
end
end
hdr.nSamples = raw.last_samp - raw.first_samp + 1; % number of samples per trial
hdr.nSamplesPre = 0;
% otherwise conflicts will occur in read_data
hdr.nTrials = 1;
info.raw = raw; % keep all the details
elseif isepoched
hdr.nSamples = length(epochs.times);
hdr.nSamplesPre = sum(epochs.times < 0);
hdr.nTrials = size(epochs.data, 1);
info.epochs = epochs; % this is used by read_data to get the actual data, i.e. to prevent re-reading
elseif isaverage
try,
evoked_data = fiff_read_evoked_all(filename);
vartriallength = any(diff([evoked_data.evoked.first])) || any(diff([evoked_data.evoked.last]));
if vartriallength
% there are trials averages with variable durations in the file
warning('EVOKED FILE with VARIABLE TRIAL LENGTH! - check data have been processed accurately');
hdr.nSamples = 0;
for i=1:length(evoked_data.evoked)
hdr.nSamples = hdr.nSamples + size(evoked_data.evoked(i).epochs, 2);
end
% represent it as a continuous file with a single trial
% all trial average details will be available through read_event
hdr.nSamplesPre = 0;
hdr.nTrials = 1;
info.evoked = evoked_data.evoked; % this is used by read_data to get the actual data, i.e. to prevent re-reading
info.info = evoked_data.info; % keep all the details
info.vartriallength = 1;
else
% represent it as a file with multiple trials, each trial has the same length
% all trial average details will be available through read_event
hdr.nSamples = evoked_data.evoked(1).last - evoked_data.evoked(1).first + 1;
hdr.nSamplesPre = -evoked_data.evoked(1).first; % represented as negative number in fif file
hdr.nTrials = length(evoked_data.evoked);
info.evoked = evoked_data.evoked; % this is used by read_data to get the actual data, i.e. to prevent re-reading
info.info = evoked_data.info; % keep all the details
info.vartriallength = 0;
end
catch
% this happens if fiff_read_evoked_all cannot find evoked
% responses, in which case it errors due to not assigning the
% output variable "data"
warning('%s does not contain data', filename);
hdr.nSamples = 0;
hdr.nSamplesPre = 0;
hdr.nTrials = 0;
end
end
% remember the original header details
hdr.orig = info;
% these are useful to know in ft_read_event and ft_read_data
hdr.orig.isaverage = isaverage;
hdr.orig.iscontinuous = iscontinuous;
hdr.orig.isepoched = isepoched;
case 'neuromag_mex'
% check that the required low-level toolbox is available
ft_hastoolbox('meg-pd', 1);
rawdata('any',filename);
rawdata('goto', 0);
megmodel('head',[0 0 0],filename);
% get the available information from the fif file
[orig.rawdata.range,orig.rawdata.calib] = rawdata('range');
[orig.rawdata.sf] = rawdata('sf');
[orig.rawdata.samples] = rawdata('samples');
[orig.chaninfo.N,orig.chaninfo.S,orig.chaninfo.T] = chaninfo; % Numbers, names & places
[orig.chaninfo.TY,orig.chaninfo.NA] = chaninfo('type'); % Coil type
[orig.chaninfo.NO] = chaninfo('noise'); % Default noise level
[orig.channames.NA,orig.channames.KI,orig.channames.NU] = channames(filename); % names, kind, logical numbers
% read a single trial to determine the data size
[buf, status] = rawdata('next');
rawdata('close');
% This is to solve a problem reported by Doug Davidson: The problem
% is that rawdata('samples') is not returning the number of samples
% correctly. It appears that the example script rawchannels in meg-pd
% might work, however, so I want to use rawchannels to read in one
% channel of data in order to get the number of samples in the file:
if orig.rawdata.samples<0
tmpchannel = 1;
tmpvar = rawchannels(filename,tmpchannel);
[orig.rawdata.samples] = size(tmpvar,2);
clear tmpvar tmpchannel;
end
% convert to fieldtrip format header
hdr.label = orig.channames.NA;
hdr.Fs = orig.rawdata.sf;
hdr.nSamplesPre = 0; % I don't know how to get this out of the file
hdr.nChans = size(buf,1);
hdr.nSamples = size(buf,2); % number of samples per trial
hdr.nTrials = orig.rawdata.samples ./ hdr.nSamples;
% add a gradiometer structure for forward and inverse modelling
hdr.grad = fif2grad(filename);
% remember the original header details
hdr.orig = orig;
case 'neuroprax_eeg'
orig = np_readfileinfo(filename);
hdr.Fs = orig.fa;
hdr.nChans = orig.K;
hdr.nSamples = orig.N;
hdr.nSamplesPre = 0; % continuous
hdr.nTrials = 1; % continuous
hdr.label = orig.channels(:);
hdr.unit = orig.units(:);
% remember the original header details
hdr.orig = orig;
case 'neuroscope_bin'
[p,f,e] = fileparts(filename);
headerfile = fullfile(p,[f,'.xml']);
hdr = ft_read_header(headerfile, 'headerformat', 'neuroscope_xml');
case 'neuroscope_ds'
listing = dir(filename);
filenames = {listing.name}';
headerfile = filenames{~cellfun('isempty',strfind(filenames,'.xml'))};
hdr = ft_read_header(headerfile, 'headerformat', 'neuroscope_xml');
case 'neuroscope_xml'
ft_hastoolbox('neuroscope', 1);
ft_hastoolbox('gifti', 1);
% this pertains to generic header file, and the other neuroscope
% formats will recurse into this one
[p,f,e] = fileparts(filename);
listing = dir(p);
filenames = {listing.name}';
lfpfile_idx = find(~cellfun('isempty',strfind(filenames,'.eeg')));
rawfile_idx = find(~cellfun('isempty',strfind(filenames,'.dat')));
if ~isempty(lfpfile_idx)
% FIXME this assumes only 1 such file, or at least it only takes the
% first one.
lfpfile = filenames{lfpfile_idx(1)};
end
if ~isempty(rawfile_idx)
rawfile = filenames{rawfile_idx(1)};
end
params = LoadParameters(filename);
hdr = [];
hdr.nChans = params.nChannels;
hdr.nTrials = 1; % is it always continuous? FIXME
hdr.nSamplesPre = 0;
if ~isempty(lfpfile)
% use the sampling of the lfp-file to be leading
hdr.Fs = params.rates.lfp;
hdr.nSamples = listing(strcmp(filenames,lfpfile)).bytes./(hdr.nChans*params.nBits/8);
hdr.TimeStampPerSample = params.rates.wideband./params.rates.lfp;
else
% use the sampling of the raw-file to be leading
hdr.Fs = params.rates.wideband;
hdr.nSamples = listing(strcmp(filenames,rawfile)).bytes./(hdr.nChans*params.nBits/8);
hdr.TimeStampPerSample = 1;
end
hdr.orig = params;
hdr.label = cell(hdr.nChans,1);
for k = 1:hdr.nChans
hdr.label{k} = ['chan',num2str(k,'%0.3d')];
end
case 'neurosim_evolution'
hdr = read_neurosim_evolution(filename);
case {'neurosim_ds' 'neurosim_signals'}
hdr = read_neurosim_signals(filename);
case 'neurosim_spikes'
headerOnly=true;
hdr= read_neurosim_spikes(filename,headerOnly);
case 'nimh_cortex'
cortex = read_nimh_cortex(filename, 'epp', 'no', 'eog', 'no');
% look at the first trial to determine whether it contains data in the EPP and EOG channels
trial1 = read_nimh_cortex(filename, 'epp', 'yes', 'eog', 'yes', 'begtrial', 1, 'endtrial', 1);
hasepp = ~isempty(trial1.epp);
haseog = ~isempty(trial1.eog);
if hasepp
warning('EPP channels are not yet supported');
end
% at the moment only the EOG channels are supported here
if haseog
hdr.label = {'EOGx' 'EOGy'};
hdr.nChans = 2;
else
hdr.label = {};
hdr.nChans = 0;
end
hdr.nTrials = length(cortex);
hdr.nSamples = inf;
hdr.nSamplesPre = 0;
hdr.orig.trial = cortex;
hdr.orig.hasepp = hasepp;
hdr.orig.haseog = haseog;
case 'ns_avg'
orig = read_ns_hdr(filename);
% do some reformatting/renaming of the header items
hdr.Fs = orig.rate;
hdr.nSamples = orig.npnt;
hdr.nSamplesPre = round(-orig.rate*orig.xmin/1000);
hdr.nChans = orig.nchan;
hdr.label = orig.label(:);
hdr.nTrials = 1; % the number of trials in this datafile is only one, i.e. the average
% remember the original header details
hdr.orig = orig;
case {'ns_cnt' 'ns_cnt16', 'ns_cnt32'}
ft_hastoolbox('eeglab', 1);
if strcmp(headerformat, 'ns_cnt')
orig = loadcnt(filename); % let loadcnt figure it out
elseif strcmp(headerformat, 'ns_cnt16')
orig = loadcnt(filename, 'dataformat', 'int16');
elseif strcmp(headerformat, 'ns_cnt32')
orig = loadcnt(filename, 'dataformat', 'int32');
end
% do some reformatting/renaming of the header items
hdr.Fs = orig.header.rate;
hdr.nChans = orig.header.nchannels;
hdr.nSamples = orig.ldnsamples;
hdr.nSamplesPre = 0;
hdr.nTrials = 1;
for i=1:hdr.nChans
hdr.label{i} = deblank(orig.electloc(i).lab);
end
% remember the original header details
hdr.orig = orig;
case 'ns_eeg'
orig = read_ns_hdr(filename);
% do some reformatting/renaming of the header items
hdr.label = orig.label;
hdr.Fs = orig.rate;
hdr.nSamples = orig.npnt;
hdr.nSamplesPre = round(-orig.rate*orig.xmin/1000);
hdr.nChans = orig.nchan;
hdr.nTrials = orig.nsweeps;
% remember the original header details
hdr.orig = orig;
case 'oxy3'
ft_hastoolbox('artinis', 1);
hdr = read_artinis_oxy3(filename);
case 'plexon_ds'
hdr = read_plexon_ds(filename);
case 'plexon_ddt'
orig = read_plexon_ddt(filename);
hdr.nChans = orig.NChannels;
hdr.Fs = orig.Freq;
hdr.nSamples = orig.NSamples;
hdr.nSamplesPre = 0; % continuous
hdr.nTrials = 1; % continuous
hdr.label = cell(1,hdr.nChans);
% give this warning only once
warning('creating fake channel names');
for i=1:hdr.nChans
hdr.label{i} = sprintf('%d', i);
end
% also remember the original header
hdr.orig = orig;
case {'read_nex_data'} % this is an alternative reader for nex files
orig = read_nex_header(filename);
% assign the obligatory items to the output FCDC header
numsmp = cell2mat({orig.varheader.numsmp});
adindx = find(cell2mat({orig.varheader.typ})==5);
if isempty(adindx)
error('file does not contain continuous channels');
end
hdr.nChans = length(orig.varheader);
hdr.Fs = orig.varheader(adindx(1)).wfrequency; % take the sampling frequency from the first A/D channel
hdr.nSamples = max(numsmp(adindx)); % take the number of samples from the longest A/D channel
hdr.nTrials = 1; % it can always be interpreted as continuous data
hdr.nSamplesPre = 0; % and therefore it is not trial based
for i=1:hdr.nChans
hdr.label{i} = deblank(char(orig.varheader(i).nam));
end
hdr.label = hdr.label(:);
% also remember the original header details
hdr.orig = orig;
case {'read_plexon_nex' 'plexon_nex'} % this is the default reader for nex files
orig = read_plexon_nex(filename);
numsmp = cell2mat({orig.VarHeader.NPointsWave});
adindx = find(cell2mat({orig.VarHeader.Type})==5);
if isempty(adindx)
error('file does not contain continuous channels');
end
hdr.nChans = length(orig.VarHeader);
hdr.Fs = orig.VarHeader(adindx(1)).WFrequency; % take the sampling frequency from the first A/D channel
hdr.nSamples = max(numsmp(adindx)); % take the number of samples from the longest A/D channel
hdr.nTrials = 1; % it can always be interpreted as continuous data
hdr.nSamplesPre = 0; % and therefore it is not trial based
for i=1:hdr.nChans
hdr.label{i} = deblank(char(orig.VarHeader(i).Name));
end
hdr.label = hdr.label(:);
hdr.FirstTimeStamp = orig.FileHeader.Beg;
hdr.TimeStampPerSample = orig.FileHeader.Frequency ./ hdr.Fs;
% also remember the original header details
hdr.orig = orig;
case 'plexon_plx'
orig = read_plexon_plx(filename);
if orig.NumSlowChannels==0
error('file does not contain continuous channels');
end
fsample = [orig.SlowChannelHeader.ADFreq];
if any(fsample~=fsample(1))
error('different sampling rates in continuous data not supported');
end
for i=1:length(orig.SlowChannelHeader)
label{i} = deblank(orig.SlowChannelHeader(i).Name);
end
% continuous channels don't always contain data, remove the empty ones
sel = [orig.DataBlockHeader.Type]==5; % continuous
chan = [orig.DataBlockHeader.Channel];
for i=1:length(label)
chansel(i) = any(chan(sel)==orig.SlowChannelHeader(i).Channel);
end
chansel = find(chansel); % this is required for timestamp selection
label = label(chansel);
% only the continuous channels are returned as visible
hdr.nChans = length(label);
hdr.Fs = fsample(1);
hdr.label = label;
% also remember the original header
hdr.orig = orig;
% select the first continuous channel that has data
sel = ([orig.DataBlockHeader.Type]==5 & [orig.DataBlockHeader.Channel]==orig.SlowChannelHeader(chansel(1)).Channel);
% get the timestamps that correspond with the continuous data
tsl = [orig.DataBlockHeader(sel).TimeStamp]';
tsh = [orig.DataBlockHeader(sel).UpperByteOf5ByteTimestamp]';
ts = timestamp_plexon(tsl, tsh); % use helper function, this returns an uint64 array
% determine the number of samples in the continuous channels
num = [orig.DataBlockHeader(sel).NumberOfWordsInWaveform];
hdr.nSamples = sum(num);
hdr.nSamplesPre = 0; % continuous
hdr.nTrials = 1; % continuous
% the timestamps indicate the beginning of each block, hence the timestamp of the last block corresponds with the end of the previous block
hdr.TimeStampPerSample = double(ts(end)-ts(1))/sum(num(1:(end-1)));
hdr.FirstTimeStamp = ts(1); % the timestamp of the first continuous sample
% also make the spike channels visible
for i=1:length(orig.ChannelHeader)
hdr.label{end+1} = deblank(orig.ChannelHeader(i).Name);
end
hdr.label = hdr.label(:);
hdr.nChans = length(hdr.label);
case {'tdt_tsq', 'tdt_tev'}
% FIXME the code below is not yet functional, it requires more input from the ESI in Frankfurt
% tsq = read_tdt_tsq(headerfile);
% k = 0;
% chan = unique([tsq.channel]);
% % loop over the physical channels
% for i=1:length(chan)
% chansel = [tsq.channel]==chan(i);
% code = unique({tsq(chansel).code});
% % loop over the logical channels
% for j=1:length(code)
% codesel = false(size(tsq));
% for k=1:numel(codesel)
% codesel(k) = identical(tsq(k).code, code{j});
% end
% % find the first instance of this logical channel
% this = find(chansel(:) & codesel(:), 1);
% % add it to the list of channels
% k = k + 1;
% frequency(k) = tsq(this).frequency;
% label{k} = [char(typecast(tsq(this).code, 'uint8')) num2str(tsq(this).channel)];
% tsqorig(k) = tsq(this);
% end
% end
error('not yet implemented');
case {'yokogawa_ave', 'yokogawa_con', 'yokogawa_raw', 'yokogawa_mrk'}
% header can be read with two toolboxes: Yokogawa MEG Reader and Yokogawa MEG160 (old inofficial toolbox)
% newest toolbox takes precedence.
if ft_hastoolbox('yokogawa_meg_reader', 3); % stay silent if it cannot be added
hdr = read_yokogawa_header_new(filename);
% add a gradiometer structure for forward and inverse modelling
hdr.grad = yokogawa2grad_new(hdr);
else
ft_hastoolbox('yokogawa', 1); % try it with the old version of the toolbox
hdr = read_yokogawa_header(filename);
% add a gradiometer structure for forward and inverse modelling
hdr.grad = yokogawa2grad(hdr);
end
case 'nmc_archive_k'
hdr = read_nmc_archive_k_hdr(filename);
case 'neuroshare' % NOTE: still under development
% check that the required neuroshare toolbox is available
ft_hastoolbox('neuroshare', 1);
tmp = read_neuroshare(filename);
hdr.Fs = tmp.hdr.analoginfo(end).SampleRate; % take the sampling freq from the last analog channel (assuming this is the same for all chans)
hdr.nChans = length(tmp.list.analog(tmp.analog.contcount~=0)); % get the analog channels, only the ones that are not empty
hdr.nSamples = max([tmp.hdr.entityinfo(tmp.list.analog).ItemCount]); % take the number of samples from the longest channel
hdr.nSamplesPre = 0; % continuous data
hdr.nTrials = 1; % continuous data
hdr.label = {tmp.hdr.entityinfo(tmp.list.analog(tmp.analog.contcount~=0)).EntityLabel}; %%% contains non-unique chans?
hdr.orig = tmp; % remember the original header
case 'bucn_nirs'
orig = read_bucn_nirshdr(filename);
hdr = rmfield(orig, 'time');
hdr.orig = orig;
case 'riff_wave'
[y, fs, nbits, opts] = wavread(filename, 1); % read one sample
siz = wavread(filename,'size');
hdr.Fs = fs;
hdr.nChans = siz(2);
hdr.nSamples = siz(1);
hdr.nSamplesPre = 0;
hdr.nTrials = 1;
[p, f, x] = fileparts(filename);
if hdr.nChans>1
for i=1:hdr.nChans
% use the file name and channel number
hdr.label{i,1} = sprintf('%s channel %d', f, i);
hdr.chantype{i,1} = 'audio';
end
else
hdr.label{1,1} = f;
hdr.chantype{1,1} = 'audio';
end
% remember the details
hdr.orig = opts;
case {'manscan_mbi', 'manscan_mb2'}
orig = in_fopen_manscan(filename);
hdr.Fs = orig.prop.sfreq;
hdr.nChans = numel(orig.channelmat.Channel);
hdr.nTrials = 1;
if isfield(orig, 'epochs') && ~isempty(orig.epochs)
hdr.nSamples = 0;
for i = 1:numel(orig.epochs)
hdr.nSamples = hdr.nSamples + diff(orig.epochs(i).samples) + 1;
end
else
hdr.nSamples = diff(orig.prop.samples) + 1;
end
if orig.prop.times(1) < 0
hdr.nSamplesPre = round(orig.prop.times(1)/hdr.Fs);
else
hdr.nSamplesPre = 0;
end
for i=1:hdr.nChans
hdr.label{i,1} = orig.channelmat.Channel(i).Name;
hdr.chantype{i,1} = lower(orig.channelmat.Channel(i).Type);
if isequal(hdr.chantype{i,1}, 'eeg')
hdr.chanunit{i, 1} = 'uV';
else
hdr.chanunit{i, 1} = 'unknown';
end
end
hdr.orig = orig;
otherwise
if strcmp(fallback, 'biosig') && ft_hastoolbox('BIOSIG', 1)
hdr = read_biosig_header(filename);
else
error('unsupported header format (%s)', headerformat);
end
end % switch headerformat
% Sometimes, the not all labels are correctly filled in by low-level reading
% functions. See for example bug #1572.
% First, make sure that there are enough (potentially empty) labels:
if numel(hdr.label) < hdr.nChans
warning('low-level reading function did not supply enough channel labels');
hdr.label{hdr.nChans} = [];
end
% Now, replace all empty labels with new name:
if any(cellfun(@isempty, hdr.label))
warning('channel labels should not be empty, creating unique labels');
hdr.label = fix_empty(hdr.label);
end
if checkUniqueLabels
if length(hdr.label)~=length(unique(hdr.label))
% all channels must have unique names
warning('all channels must have unique labels, creating unique labels');
megflag = ft_chantype(hdr, 'meg');
eegflag = ft_chantype(hdr, 'eeg');
for i=1:hdr.nChans
sel = find(strcmp(hdr.label{i}, hdr.label));
if length(sel)>1
% there is no need to rename the first instance
% can be particularly disruptive when part of standard MEG
% or EEG channel set, so should be avoided
if any(megflag(sel))
sel = setdiff(sel, sel(find(megflag(sel), 1)));
elseif any(eegflag(sel))
sel = setdiff(sel, sel(find(eegflag(sel), 1)));
else
sel = sel(2:end);
end
for j=1:length(sel)
hdr.label{sel(j)} = sprintf('%s-%d', hdr.label{sel(j)}, j);
end
end
end
end
end
% ensure that it is a column array
hdr.label = hdr.label(:);
% as of November 2011, the header is supposed to include the channel type (see FT_CHANTYPE,
% e.g. meggrad, megref, eeg) and the units of each channel (see FT_CHANUNIT, e.g. uV, fT)
if ~isfield(hdr, 'chantype')
% use a helper function which has some built in intelligence
hdr.chantype = ft_chantype(hdr);
end % for
if ~isfield(hdr, 'chanunit')
% use a helper function which has some built in intelligence
hdr.chanunit = ft_chanunit(hdr);
end % for
% ensure that the output grad is according to the latest definition
if isfield(hdr, 'grad')
hdr.grad = ft_datatype_sens(hdr.grad);
end
% ensure that the output elec is according to the latest definition
if isfield(hdr, 'elec')
hdr.elec = ft_datatype_sens(hdr.elec);
end
% ensure that these are double precision and not integers, otherwise
% subsequent computations that depend on these might be messed up
hdr.Fs = double(hdr.Fs);
hdr.nSamples = double(hdr.nSamples);
hdr.nSamplesPre = double(hdr.nSamplesPre);
hdr.nTrials = double(hdr.nTrials);
hdr.nChans = double(hdr.nChans);
if cache && exist(headerfile, 'file')
% put the header in the cache
cacheheader = hdr;
% update the header details (including time stampp, size and name)
cacheheader.details = dir(headerfile);
% fprintf('added header to cache\n');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to determine the file size in bytes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [siz] = filesize(filename)
l = dir(filename);
if l.isdir
error('"%s" is not a file', filename);
end
siz = l.bytes;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to determine the file size in bytes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [hdr] = recursive_read_header(filename)
[p, f, x] = fileparts(filename);
ls = dir(filename);
ls = ls(~strcmp({ls.name}, '.')); % exclude this directory
ls = ls(~strcmp({ls.name}, '..')); % exclude parent directory
for i=1:length(ls)
% make sure that the directory listing includes the complete path
ls(i).name = fullfile(filename, ls(i).name);
end
lst = {ls.name};
hdr = cell(size(lst));
sel = zeros(size(lst));
for i=1:length(lst)
% read the header of each individual file
try
thishdr = ft_read_header(lst{i});
if isstruct(thishdr)
thishdr.filename = lst{i};
end
catch
thishdr = [];
warning(lasterr);
fprintf('while reading %s\n\n', lst{i});
end
if ~isempty(thishdr)
hdr{i} = thishdr;
sel(i) = true;
else
sel(i) = false;
end
end
sel = logical(sel(:));
hdr = hdr(sel);
tmp = {};
for i=1:length(hdr)
if isstruct(hdr{i})
tmp = cat(1, tmp, hdr(i));
elseif iscell(hdr{i})
tmp = cat(1, tmp, hdr{i}{:});
end
end
hdr = tmp;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to fill in empty labels
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function labels = fix_empty(labels)
for i = find(cellfun(@isempty, {labels{:}}));
labels{i} = sprintf('%d', i);
end
|
github
|
ZijingMao/baselineeegtest-master
|
ft_read_mri.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/ft_read_mri.m
| 15,468 |
utf_8
|
a921a393da75a56940c3100fde50e10a
|
function [mri] = ft_read_mri(filename, varargin)
% FT_READ_MRI reads anatomical and functional MRI data from different
% file formats. The output data is structured in such a way that it is
% comparable to a FieldTrip source reconstruction.
%
% Use as
% [mri] = ft_read_mri(filename)
%
% Additional options should be specified in key-value pairs and can be
% 'dataformat' string specifying the file format, determining the low-
% level reading routine to be used. if no format is
% given, it is determined automatically (at least the
% function tries). the following values for dataformat can
% be used:
% 'afni_head'/'afni_brik', uses afni
% 'analyze_img'/'analyze_hdr', uses spm
% 'analyze_old', uses Darren Webber's code
% 'asa_mri'
% 'ctf_mri'
% 'ctf_mri4'
% 'ctf_svl'
% 'dicom', uses freesurfer
% 'dicom_old', uses own code
% 'freesurfer_mgh', uses freesurfer
% 'freesurfer_mgz', uses freesurfer
% 'minc', uses spm (<= version spm5)
% 'nifti', uses freesurfer
% 'nifti_fsl', uses freesurfer
% 'nifti_spm', uses spm
% 'neuromag_fif', uses mne toolbox
% 'neuromag_fif_old', uses meg-pd toolbox
% 'yokogawa_mri'
% 'matlab' assumes mri to be in a fieldtrip-style
% structure, in a .mat file
%
% The following MRI file formats are supported
% CTF - VSM MedTech (*.svl, *.mri version 4 and 5)
% NIFTi (*.nii) and zipped NIFTi (*.nii.gz)
% Analyze (*.img, *.hdr)
% DICOM (*.dcm, *.ima)
% AFNI (*.head, *.brik)
% FreeSurfer (*.mgz, *.mgh)
% MINC (*.mnc)
% Neuromag - Elekta (*.fif)
% ANT - Advanced Neuro Technology (*.mri)
% Yokogawa (*.mrk, incomplete)
%
% The output MRI may have a homogenous transformation matrix that converts
% the coordinates of each voxel (in xgrid/ygrid/zgrid) into head
% coordinates.
%
% See also FT_WRITE_MRI, FT_READ_DATA, FT_READ_HEADER, FT_READ_EVENT
% Copyright (C) 2008-2013, Robert Oostenveld & Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_read_mri.m 9149 2014-01-29 13:59:29Z eelspa $
% optionally get the data from the URL and make a temporary local copy
filename = fetch_url(filename);
% get the options
mriformat = ft_getopt(varargin, 'dataformat');
% the following is added for backward compatibility of using 'format' rather than 'dataformat'
format = ft_getopt(varargin, 'format');
if ~isempty(format)
warning('the option ''format'' will be deprecated soon, please use ''dataformat'' instead');
if isempty(mriformat)
mriformat = format;
end
end
if isempty(mriformat)
% only do the autodetection if the format was not specified
mriformat = ft_filetype(filename);
end
% extract if needed
if strcmp(mriformat, 'compressed')
filename = inflate_file(filename);
mriformat = ft_filetype(filename);
end
% test whether the file exists
if ~exist(filename, 'file')
error('file ''%s'' does not exist', filename);
end
% test for the presence of some external functions from other toolboxes
hasspm2 = ft_hastoolbox('spm2'); % see http://www.fil.ion.ucl.ac.uk/spm/
hasspm5 = ft_hastoolbox('spm5'); % see http://www.fil.ion.ucl.ac.uk/spm/
hasspm8 = ft_hastoolbox('spm8'); % see http://www.fil.ion.ucl.ac.uk/spm/
hasspm12 = ft_hastoolbox('spm12'); % see http://www.fil.ion.ucl.ac.uk/spm/
hasspm = (hasspm2 || hasspm5 || hasspm8 || hasspm12);
switch mriformat
case 'ctf_mri'
[img, hdr] = read_ctf_mri(filename);
transform = hdr.transformMRI2Head;
coordsys = 'ctf';
case 'ctf_mri4'
[img, hdr] = read_ctf_mri4(filename);
transform = hdr.transformMRI2Head;
coordsys = 'ctf';
case 'ctf_svl'
[img, hdr] = read_ctf_svl(filename);
transform = hdr.transform;
case 'asa_mri'
[img, seg, hdr] = read_asa_mri(filename);
transform = hdr.transformMRI2Head;
case 'minc'
if ~(hasspm2 || hasspm5)
fprintf('the SPM2 or SPM5 toolbox is required to read *.mnc files\n');
ft_hastoolbox('spm2',1);
end
% use the functions from SPM
hdr = spm_vol_minc(filename);
img = spm_read_vols(hdr);
transform = hdr.mat;
case 'nifti_spm'
if ~(hasspm5 || hasspm8 || hasspm12)
fprintf('the SPM5 or newer toolbox is required to read *.nii files\n');
ft_hastoolbox('spm8', 1);
end
% use the functions from SPM
hdr = spm_vol_nifti(filename);
img = spm_read_vols(hdr);
transform = hdr.mat;
case {'analyze_img' 'analyze_hdr'}
ft_hastoolbox('spm8', 1);
% use the image file instead of the header
filename((end-2):end) = 'img';
% use the functions from SPM to read the Analyze MRI
hdr = spm_vol(filename);
img = spm_read_vols(hdr);
transform = hdr.mat;
case 'analyze_old'
% use the functions from Darren Weber's mri_toolbox to read the Analyze MRI
ft_hastoolbox('mri', 1); % from Darren Weber, see http://eeg.sourceforge.net/
avw = avw_img_read(filename, 0); % returned volume is LAS*
img = avw.img;
hdr = avw.hdr;
% The default Analyze orientation is axial unflipped (LAS*), which means
% that the resulting volume is according to the radiological convention.
% Most other fMRI and EEG/MEG software (except Mayo/Analyze) uses
% neurological conventions and a right-handed coordinate system, hence
% the first axis of the 3D volume (right-left) should be flipped to make
% the coordinate system comparable to SPM
warning('flipping 1st dimension (L-R) to obtain volume in neurological convention');
img = flipdim(img, 1);
transform = diag(hdr.dime.pixdim(2:4));
transform(4,4) = 1;
case {'afni_brik' 'afni_head'}
% needs afni
ft_hastoolbox('afni', 1); % see http://afni.nimh.nih.gov/
[err, img, hdr, ErrMessage] = BrikLoad(filename);
if err
error('could not read AFNI file');
end
% FIXME: this should be checked, but I only have a single BRIK file
% construct the homogenous transformation matrix that defines the axes
warning('homogenous transformation might be incorrect for AFNI file');
transform = eye(4);
transform(1:3,4) = hdr.ORIGIN(:);
transform(1,1) = hdr.DELTA(1);
transform(2,2) = hdr.DELTA(2);
transform(3,3) = hdr.DELTA(3);
% FIXME: I am not sure about the "RAI" image orientation
img = flipdim(img,1);
img = flipdim(img,2);
dim = size(img);
transform(1,4) = -dim(1) - transform(1,4);
transform(2,4) = -dim(2) - transform(2,4);
case 'neuromag_fif'
% needs mne toolbox
ft_hastoolbox('mne', 1);
% use the mne functions to read the Neuromag MRI
hdr = fiff_read_mri(filename);
img_t = cat(3, hdr.slices.data);
img = permute(img_t,[2 1 3]);
hdr.slices = rmfield(hdr.slices, 'data'); % remove the image data to save memory
% information below is from MNE - fiff_define_constants.m
% coordinate system 4 - is the MEG head coordinate system (fiducials)
% coordinate system 5 - is the MRI coordinate system
% coordinate system 2001 - MRI voxel coordinates
% coordinate system 2002 - Surface RAS coordinates (is mainly vertical
% shift, no rotation to 2001)
% MEG sensor positions come in system 4
% MRI comes in system 2001
transform = eye(4);
if isfield(hdr, 'trans') && issubfield(hdr.trans, 'trans')
if (hdr.trans.from == 4) && (hdr.trans.to == 5)
transform = hdr.trans.trans;
else
warning('W: trans does not transform from 4 to 5.');
warning('W: Please check the MRI fif-file');
end
else
warning('W: trans structure is not defined.');
warning('W: Maybe coregistration is missing?');
end
if isfield(hdr, 'voxel_trans') && issubfield(hdr.voxel_trans, 'trans')
% centers the coordinate system
% and switches from mm to m
if (hdr.voxel_trans.from == 2001) && (hdr.voxel_trans.to == 5)
% matlab_shift compensates for the different index conventions
% between C and matlab
% the lines below is old code (prior to Jan 3, 2013) and only works with
% 1 mm resolution MRIs
%matlab_shift = [ 0 0 0 0.001; 0 0 0 -0.001; 0 0 0 0.001; 0 0 0 0];
% transform transforms from 2001 to 5 and further to 4
%transform = transform\(hdr.voxel_trans.trans+matlab_shift);
% the lines below should work with arbitrary resolution
matlab_shift = eye(4);
matlab_shift(1:3,4) = [-1,-1,-1];
transform = transform\(hdr.voxel_trans.trans * matlab_shift);
coordsys = 'neuromag';
mri.unit = 'm';
else
warning('W: voxel_trans does not transform from 2001 to 5.');
warning('W: Please check the MRI fif-file');
end
else
warning('W: voxel_trans structure is not defined.');
warning('W: Please check the MRI fif-file');
end
case 'neuromag_fif_old'
% needs meg_pd toolbox
ft_hastoolbox('meg-pd', 1);
% use the meg_pd functions to read the Neuromag MRI
[img,coords] = loadmri(filename);
dev = loadtrans(filename,'MRI','HEAD');
transform = dev*coords;
hdr.coords = coords;
hdr.dev = dev;
case 'dicom'
% this seems to return a right-handed volume with the transformation
% matrix stored in the file headers.
% needs the freesurfer toolbox
ft_hastoolbox('freesurfer', 1);
[dcmdir,junk1,junk2] = fileparts(filename);
if isempty(dcmdir),
dcmdir = '.';
end
[img,transform,hdr,mr_params] = load_dicom_series(dcmdir,dcmdir,filename);
transform = vox2ras_0to1(transform);
case 'dicom_old'
% this does not necessarily return a right-handed volume and only a
% transformation-matrix with the voxel size
% this uses the Image processing toolbox
% the DICOM file probably represents a stack of slices, possibly even multiple volumes
orig = dicominfo(filename);
dim(1) = orig.Rows;
dim(2) = orig.Columns;
[p, f] = fileparts(filename);
% this works for the Siemens scanners at the FCDC
tok = tokenize(f, '.');
for i=5:length(tok)
tok{i} = '*';
end
filename = sprintf('%s.', tok{:}); % reconstruct the filename with wildcards and '.' between the segments
filename = filename(1:end-1); % remove the last '.'
dirlist = dir(fullfile(p, filename));
dirlist = {dirlist.name};
if length(dirlist)==1
% try something else to get a list of all the slices
dirlist = dir(fullfile(p, '*'));
dirlist = {dirlist(~[dirlist.isdir]).name};
end
keep = false(1, length(dirlist));
for i=1:length(dirlist)
filename = char(fullfile(p, dirlist{i}));
if ~strcmp(mriformat, 'dicom')
keep(i) = false;
fprintf('skipping ''%s'' because of incorrect filetype\n', filename);
end
% read the header information
info = dicominfo(filename);
if info.SeriesNumber~=orig.SeriesNumber
keep(i) = false;
fprintf('skipping ''%s'' because of different SeriesNumber\n', filename);
else
keep(i) = true;
hdr(i) = info;
end
end
% remove the files that were skipped
hdr = hdr(keep);
dirlist = dirlist(keep);
% pre-allocate enough space for the subsequent slices
dim(3) = length(dirlist);
img = zeros(dim(1), dim(2), dim(3));
for i=1:length(dirlist)
filename = char(fullfile(p, dirlist{i}));
fprintf('reading image data from ''%s''\n', filename);
img(:,:,i) = dicomread(hdr(i));
end
% reorder the slices
[z, indx] = sort(cell2mat({hdr.SliceLocation}));
hdr = hdr(indx);
img = img(:,:,indx);
try
% construct a homgeneous transformation matrix that performs the scaling from voxels to mm
dx = hdr(1).PixelSpacing(1);
dy = hdr(1).PixelSpacing(2);
dz = hdr(2).SliceLocation - hdr(1).SliceLocation;
transform = eye(4);
transform(1,1) = dx;
transform(2,2) = dy;
transform(3,3) = dz;
end
case {'nifti', 'freesurfer_mgz', 'freesurfer_mgh', 'nifti_fsl'}
if strcmp(mriformat, 'freesurfer_mgz') && ispc
error('Compressed .mgz files cannot be read on a PC');
end
ft_hastoolbox('freesurfer', 1);
tmp = MRIread(filename);
ndims = numel(size(tmp.vol));
if ndims==3
img = permute(tmp.vol, [2 1 3]); %FIXME although this is probably correct
%see the help of MRIread, anecdotally columns and rows seem to need a swap
%in order to match the transform matrix (alternatively a row switch of the
%latter can be done)
elseif ndims==4
img = permute(tmp.vol, [2 1 3 4]);
end
hdr = rmfield(tmp, 'vol');
transform = tmp.vox2ras1;
case 'yokogawa_mri'
ft_hastoolbox('yokogawa', 1);
fid = fopen(filename, 'rb');
mri_info = GetMeg160MriInfoM(fid);
patient_info = GetMeg160PatientInfoFromMriFileM(fid);
[data_style, model, marker, image_parameter, normalize, besa_fiducial_point] = GetMeg160MriFileHeaderInfoM(fid);
fclose(fid);
% gather all meta-information
hdr.mri_info = mri_info;
hdr.patient_info = patient_info;
hdr.data_style = data_style;
hdr.model = model;
hdr.marker = marker;
hdr.image_parameter = image_parameter;
hdr.normalize = normalize;
hdr.besa_fiducial_point = besa_fiducial_point;
error('FIXME yokogawa_mri implementation is incomplete');
case 'matlab'
mri = loadvar(filename, 'mri');
otherwise
error(sprintf('unrecognized filetype ''%s'' for ''%s''', mriformat, filename));
end
if exist('img', 'var')
% set up the axes of the volume in voxel coordinates
nx = size(img,1);
ny = size(img,2);
nz = size(img,3);
mri.dim = [nx ny nz];
% store the anatomical data
mri.anatomy = img;
end
if exist('hdr', 'var')
% store the header with all file format specific details
mri.hdr = hdr;
end
try
% store the homogenous transformation matrix if present
mri.transform = transform;
end
try
% try to determine the units of the coordinate system
mri = ft_convert_units(mri);
end
try
% try to add a descriptive label for the coordinate system
mri.coordsys = coordsys;
end
function value = loadvar(filename, varname)
var = whos('-file', filename);
if length(var)==1
filecontent = load(filename); % read the one variable in the file, regardless of how it is called
value = filecontent.(var.name);
clear filecontent
else
filecontent = load(filename, varname);
value = filecontent.(varname); % read the variable named according to the input specification
clear filecontent
end
|
github
|
ZijingMao/baselineeegtest-master
|
ft_filetype.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/ft_filetype.m
| 63,157 |
utf_8
|
99253abe6d86f298e9e92dc7dc18cc03
|
function [type] = ft_filetype(filename, desired, varargin)
% FT_FILETYPE determines the filetype of many EEG/MEG/MRI data files by
% looking at the name, extension and optionally (part of) its contents.
% It tries to determine the global type of file (which usually
% corresponds to the manufacturer, the recording system or to the
% software used to create the file) and the particular subtype (e.g.
% continuous, average).
%
% Use as
% type = ft_filetype(filename)
% type = ft_filetype(dirname)
%
% This gives you a descriptive string with the data type, and can be
% used in a switch-statement. The descriptive string that is returned
% usually is something like 'XXX_YYY'/ where XXX refers to the
% manufacturer and YYY to the type of the data.
%
% Alternatively, use as
% flag = ft_filetype(filename, type)
% flag = ft_filetype(dirname, type)
% This gives you a boolean flag (0 or 1) indicating whether the file
% is of the desired type, and can be used to check whether the
% user-supplied file is what your subsequent code expects.
%
% Alternatively, use as
% flag = ft_filetype(dirlist, type)
% where the dirlist contains a list of files contained within one
% directory. This gives you a boolean vector indicating for each file
% whether it is of the desired type.
%
% Most filetypes of the following manufacturers and/or software programs are recognized
% - 4D/BTi
% - AFNI
% - ASA
% - Analyse
% - Analyze/SPM
% - BESA
% - BrainSuite
% - BrainVisa
% - BrainVision
% - Curry
% - Dataq
% - EDF
% - EEProbe
% - Elektra/Neuromag
% - FreeSurfer
% - LORETA
% - Localite
% - MINC
% - Neuralynx
% - Neuroscan
% - Plexon
% - SR Research Eyelink
% - Stanford *.ply
% - Tucker Davis Technology
% - VSM-Medtech/CTF
% - Yokogawa
% - nifti, gifti
% Copyright (C) 2003-2013 Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_filetype.m 10380 2015-05-06 20:10:14Z roboos $
% these are for remembering the type on subsequent calls with the same input arguments
persistent previous_argin previous_argout previous_pwd
if nargin<2
% ensure that all input arguments are defined
desired = [];
end
current_argin = {filename, desired, varargin{:}};
current_pwd = pwd;
if isequal(current_argin, previous_argin) && isequal(current_pwd, previous_pwd)
% don't do the detection again, but return the previous value from cache
type = previous_argout{1};
return
end
if isa(filename, 'memmapfile')
filename = filename.Filename;
end
% % get the optional arguments
% checkheader = ft_getopt(varargin, 'checkheader', true);
%
% if ~checkheader
% % assume that the header is always ok, e.g when the file does not yet exist
% % this replaces the normal function with a function that always returns true
% filetype_check_header = @filetype_true;
% end
if iscell(filename)
if ~isempty(desired)
% perform the test for each filename, return a boolean vector
type = false(size(filename));
else
% return a string with the type for each filename
type = cell(size(filename));
end
for i=1:length(filename)
if strcmp(filename{i}(end), '.')
% do not recurse into this directory or the parent directory
continue
else
if iscell(type)
type{i} = ft_filetype(filename{i}, desired);
else
type(i) = ft_filetype(filename{i}, desired);
end
end
end
return
end
% start with unknown values
type = 'unknown';
manufacturer = 'unknown';
content = 'unknown';
if isempty(filename)
if isempty(desired)
% return the "unknown" outputs
return
else
% return that it is a non-match
type = false;
return
end
end
% the parts of the filename are used further down
if isdir(filename)
p = filename;
f = '';
x = '';
else
[p, f, x] = fileparts(filename);
end
% prevent this test if the filename resembles an URI, i.e. like "scheme://"
if isempty(strfind(filename , '://')) && isdir(filename)
% the directory listing is needed below
ls = dir(filename);
% remove the parent directory and the directory itself from the list
ls = ls(~strcmp({ls.name}, '.'));
ls = ls(~strcmp({ls.name}, '..'));
for i=1:length(ls)
% make sure that the directory listing includes the complete path
ls(i).name = fullfile(filename, ls(i).name);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% start determining the filetype
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this checks for a compressed file (of arbitrary type)
if filetype_check_extension(filename, 'zip')...
|| (filetype_check_extension(filename, '.gz') && ~filetype_check_extension(filename, '.nii.gz'))...
|| filetype_check_extension(filename, 'tgz')...
|| filetype_check_extension(filename, 'tar')
type = 'compressed';
manufacturer = 'undefined';
content = 'unknown, extract first';
% these are some streams for asynchronous BCI
elseif filetype_check_uri(filename, 'fifo')
type = 'fcdc_fifo';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'stream';
elseif filetype_check_uri(filename, 'buffer')
type = 'fcdc_buffer';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'stream';
elseif filetype_check_uri(filename, 'mysql')
type = 'fcdc_mysql';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'stream';
elseif filetype_check_uri(filename, 'tcp')
type = 'fcdc_tcp';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'stream';
elseif filetype_check_uri(filename, 'udp')
type = 'fcdc_udp';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'stream';
elseif filetype_check_uri(filename, 'rfb')
type = 'fcdc_rfb';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'stream';
elseif filetype_check_uri(filename, 'serial')
type = 'fcdc_serial';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'stream';
elseif filetype_check_uri(filename, 'global')
type = 'fcdc_global';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'global variable';
elseif filetype_check_uri(filename, 'shm')
type = 'ctf_shm';
manufacturer = 'CTF';
content = 'real-time shared memory buffer';
elseif filetype_check_uri(filename, 'empty')
type = 'empty';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = '/dev/null';
% known CTF file types
elseif isdir(filename) && filetype_check_extension(filename, '.ds') && exist(fullfile(filename, [f '.res4']))
type = 'ctf_ds';
manufacturer = 'CTF';
content = 'MEG dataset';
elseif isdir(filename) && ~isempty(dir(fullfile(filename, '*.res4'))) && ~isempty(dir(fullfile(filename, '*.meg4')))
type = 'ctf_ds';
manufacturer = 'CTF';
content = 'MEG dataset';
elseif filetype_check_extension(filename, '.res4') && (filetype_check_header(filename, 'MEG41RS') || filetype_check_header(filename, 'MEG42RS') || filetype_check_header(filename, 'MEG4RES') || filetype_check_header(filename, 'MEG3RES')) %'MEG3RES' pertains to ctf64.ds
type = 'ctf_res4';
manufacturer = 'CTF';
content = 'MEG/EEG header information';
elseif filetype_check_extension(filename, '.meg4') && (filetype_check_header(filename, 'MEG41CP') || filetype_check_header(filename, 'MEG4CPT')) %'MEG4CPT' pertains to ctf64.ds
type = 'ctf_meg4';
manufacturer = 'CTF';
content = 'MEG/EEG';
elseif strcmp(f, 'MarkerFile') && filetype_check_extension(filename, '.mrk') && filetype_check_header(filename, 'PATH OF DATASET:')
type = 'ctf_mrk';
manufacturer = 'CTF';
content = 'marker file';
elseif filetype_check_extension(filename, '.mri') && filetype_check_header(filename, 'CTF_MRI_FORMAT VER 2.2')
type = 'ctf_mri';
manufacturer = 'CTF';
content = 'MRI';
elseif filetype_check_extension(filename, '.mri') && filetype_check_header(filename, 'CTF_MRI_FORMAT VER 4', 31)
type = 'ctf_mri4';
manufacturer = 'CTF';
content = 'MRI';
elseif filetype_check_extension(filename, '.hdm')
type = 'ctf_hdm';
manufacturer = 'CTF';
content = 'volume conduction model';
elseif filetype_check_extension(filename, '.hc')
type = 'ctf_hc';
manufacturer = 'CTF';
content = 'headcoil locations';
elseif filetype_check_extension(filename, '.shape')
type = 'ctf_shape';
manufacturer = 'CTF';
content = 'headshape points';
elseif filetype_check_extension(filename, '.shape_info')
type = 'ctf_shapeinfo';
manufacturer = 'CTF';
content = 'headshape information';
elseif filetype_check_extension(filename, '.wts')
type = 'ctf_wts';
manufacturer = 'CTF';
content = 'SAM coefficients, i.e. spatial filter weights';
elseif filetype_check_extension(filename, '.svl')
type = 'ctf_svl';
manufacturer = 'CTF';
content = 'SAM (pseudo-)statistic volumes';
% known Micromed file types
elseif filetype_check_extension(filename, '.trc') && filetype_check_header(filename, '* MICROMED')
type = 'micromed_trc';
manufacturer = 'Micromed';
content = 'Electrophysiological data';
% known Neuromag file types
elseif filetype_check_extension(filename, '.fif')
type = 'neuromag_fif';
manufacturer = 'Neuromag';
content = 'MEG header and data';
elseif filetype_check_extension(filename, '.bdip')
type = 'neuromag_bdip';
manufacturer = 'Neuromag';
content = 'dipole model';
elseif filetype_check_extension(filename, '.eve') && exist(fullfile(p, [f '.fif']), 'file')
type = 'neuromag_eve'; % these are being used by Tristan Technologies for the BabySQUID system
manufacturer = 'Neuromag';
content = 'events';
% known Yokogawa file types
elseif filetype_check_extension(filename, '.ave') || filetype_check_extension(filename, '.sqd')
type = 'yokogawa_ave';
manufacturer = 'Yokogawa';
content = 'averaged MEG data';
elseif filetype_check_extension(filename, '.con')
type = 'yokogawa_con';
manufacturer = 'Yokogawa';
content = 'continuous MEG data';
elseif filetype_check_extension(filename, '.raw') && filetype_check_header(filename, char([0 0 0 0])) % FIXME, this detection should possibly be improved
type = 'yokogawa_raw';
manufacturer = 'Yokogawa';
content = 'evoked/trialbased MEG data';
elseif filetype_check_extension(filename, '.mrk') && filetype_check_header(filename, char([0 0 0 0])) % FIXME, this detection should possibly be improved
type = 'yokogawa_mrk';
manufacturer = 'Yokogawa';
content = 'headcoil locations';
elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-coregis')) == 1
type = 'yokogawa_coregis';
manufacturer = 'Yokogawa';
content = 'exported fiducials';
elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-calib')) == 1
type = 'yokogawa_calib';
manufacturer = 'Yokogawa';
elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-channel')) == 1
type = 'yokogawa_channel';
manufacturer = 'Yokogawa';
elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-property')) == 1
type = 'yokogawa_property';
manufacturer = 'Yokogawa';
elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-TextData')) == 1
type = 'yokogawa_textdata';
manufacturer = 'Yokogawa';
elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-FLL')) == 1
type = 'yokogawa_fll';
manufacturer = 'Yokogawa';
elseif filetype_check_extension(filename, '.hsp')
type = 'yokogawa_hsp';
manufacturer = 'Yokogawa';
% Neurosim files; this has to go before the 4D detection
elseif ~isdir(filename) && (strcmp(f,'spikes') || filetype_check_header(filename,'# Spike information'))
type = 'neurosim_spikes';
manufacturer = 'Jan van der Eerden (DCCN)';
content = 'simulated spikes';
elseif ~isdir(filename) && (strcmp(f,'evolution') || filetype_check_header(filename,'# Voltages'))
type = 'neurosim_evolution';
manufacturer = 'Jan van der Eerden (DCCN)';
content = 'simulated membrane voltages and currents';
elseif ~isdir(filename) && (strcmp(f,'signals') || filetype_check_header(filename,'# Internal',2))
type = 'neurosim_signals';
manufacturer = 'Jan van der Eerden (DCCN)';
content = 'simulated network signals';
elseif isdir(filename) && exist(fullfile(filename, 'signals'), 'file') && exist(fullfile(filename, 'spikes'), 'file')
type = 'neurosim_ds';
manufacturer = 'Jan van der Eerden (DCCN)';
content = 'simulated spikes and continuous signals';
% known 4D/BTI file types
elseif filetype_check_extension(filename, '.pdf') && filetype_check_header(filename, 'E|lk') % I am not sure whether this header always applies
type = '4d_pdf';
manufacturer = '4D/BTI';
content = 'raw MEG data (processed data file)';
elseif exist([filename '.m4d'], 'file') && exist([filename '.xyz'], 'file') % these two ascii header files accompany the raw data
type = '4d_pdf';
manufacturer = '4D/BTI';
content = 'raw MEG data (processed data file)';
elseif filetype_check_extension(filename, '.m4d') && exist([filename(1:(end-3)) 'xyz'], 'file') % these come in pairs
type = '4d_m4d';
manufacturer = '4D/BTI';
content = 'MEG header information';
elseif filetype_check_extension(filename, '.xyz') && exist([filename(1:(end-3)) 'm4d'], 'file') % these come in pairs
type = '4d_xyz';
manufacturer = '4D/BTI';
content = 'MEG sensor positions';
elseif isequal(f, 'hs_file') % the filename is "hs_file"
type = '4d_hs';
manufacturer = '4D/BTI';
content = 'head shape';
elseif length(filename)>=4 && ~isempty(strfind(filename,',rf'))
type = '4d';
manufacturer = '4D/BTi';
content = '';
elseif filetype_check_extension(filename, '.el.ascii') && filetype_check_ascii(filename, 20) % assume that there are at least 20 bytes in the file, the example one has 4277 bytes
type = '4d_el_ascii';
manufacturer = '4D/BTi';
content = 'electrode positions';
elseif length(f)<=4 && filetype_check_dir(p, 'config')%&& ~isempty(p) && exist(fullfile(p,'config'), 'file') %&& exist(fullfile(p,'hs_file'), 'file')
% this could be a 4D file with non-standard/processed name
% it will be detected as a 4D file when there is a config file in the
% same directory as the specified file
type = '4d';
manufacturer = '4D/BTi';
content = '';
% known EEProbe file types
elseif filetype_check_extension(filename, '.cnt') && (filetype_check_header(filename, 'RIFF') || filetype_check_header(filename, 'RF64'))
type = 'eep_cnt';
manufacturer = 'EEProbe';
content = 'EEG';
elseif filetype_check_extension(filename, '.avr') && filetype_check_header(filename, char([38 0 16 0]))
type = 'eep_avr';
manufacturer = 'EEProbe';
content = 'ERP';
elseif filetype_check_extension(filename, '.trg')
type = 'eep_trg';
manufacturer = 'EEProbe';
content = 'trigger information';
elseif filetype_check_extension(filename, '.rej')
type = 'eep_rej';
manufacturer = 'EEProbe';
content = 'rejection marks';
% the yokogawa_mri has to be checked prior to asa_mri, because this one is more strict
elseif filetype_check_extension(filename, '.mri') && filetype_check_header(filename, char(0)) % FIXME, this detection should possibly be improved
type = 'yokogawa_mri';
manufacturer = 'Yokogawa';
content = 'anatomical MRI';
% known ASA file types
elseif filetype_check_extension(filename, '.elc')
type = 'asa_elc';
manufacturer = 'ASA';
content = 'electrode positions';
elseif filetype_check_extension(filename, '.vol')
type = 'asa_vol';
manufacturer = 'ASA';
content = 'volume conduction model';
elseif filetype_check_extension(filename, '.bnd')
type = 'asa_bnd';
manufacturer = 'ASA';
content = 'boundary element model details';
elseif filetype_check_extension(filename, '.msm')
type = 'asa_msm';
manufacturer = 'ASA';
content = 'ERP';
elseif filetype_check_extension(filename, '.msr')
type = 'asa_msr';
manufacturer = 'ASA';
content = 'ERP';
elseif filetype_check_extension(filename, '.dip')
% FIXME, can also be CTF dipole file
type = 'asa_dip';
manufacturer = 'ASA';
elseif filetype_check_extension(filename, '.mri')
% FIXME, can also be CTF mri file
type = 'asa_mri';
manufacturer = 'ASA';
content = 'MRI image header';
elseif filetype_check_extension(filename, '.iso')
type = 'asa_iso';
manufacturer = 'ASA';
content = 'MRI image data';
% known BCI2000 file types
elseif filetype_check_extension(filename, '.dat') && (filetype_check_header(filename, 'BCI2000') || filetype_check_header(filename, 'HeaderLen='))
type = 'bci2000_dat';
manufacturer = 'BCI2000';
content = 'continuous EEG';
% known Neuroscan file types
elseif filetype_check_extension(filename, '.avg') && filetype_check_header(filename, 'Version 3.0')
type = 'ns_avg';
manufacturer = 'Neuroscan';
content = 'averaged EEG';
elseif filetype_check_extension(filename, '.cnt') && filetype_check_header(filename, 'Version 3.0')
type = 'ns_cnt';
manufacturer = 'Neuroscan';
content = 'continuous EEG';
elseif filetype_check_extension(filename, '.eeg') && filetype_check_header(filename, 'Version 3.0')
type = 'ns_eeg';
manufacturer = 'Neuroscan';
content = 'epoched EEG';
elseif filetype_check_extension(filename, '.eeg') && filetype_check_header(filename, 'V3.0')
type = 'neuroprax_eeg';
manufacturer = 'eldith GmbH';
content = 'continuous EEG';
elseif filetype_check_extension(filename, '.ee_')
type = 'neuroprax_mrk';
manufacturer = 'eldith GmbH';
content = 'EEG markers';
% known Analyze & SPM file types
elseif filetype_check_extension(filename, '.hdr')
type = 'analyze_hdr';
manufacturer = 'Mayo Analyze';
content = 'PET/MRI image header';
elseif filetype_check_extension(filename, '.img')
type = 'analyze_img';
manufacturer = 'Mayo Analyze';
content = 'PET/MRI image data';
elseif filetype_check_extension(filename, '.mnc')
type = 'minc';
content = 'MRI image data';
elseif filetype_check_extension(filename, '.nii') && filetype_check_header(filename, {[92 1 0 0], [0 0 1 92]}) % header starts with the number 348
type = 'nifti';
content = 'MRI image data';
elseif filetype_check_extension(filename, '.nii') && filetype_check_header(filename, {[28 2 0 0], [0 0 2 28]}) % header starts with the number 540
type = 'nifti2';
content = 'MRI image data';
% known FSL file types
elseif filetype_check_extension(filename, '.nii.gz')
type = 'nifti_fsl';
content = 'MRI image data';
% known LORETA file types
elseif filetype_check_extension(filename, '.lorb')
type = 'loreta_lorb';
manufacturer = 'old LORETA';
content = 'source reconstruction';
elseif filetype_check_extension(filename, '.slor')
type = 'loreta_slor';
manufacturer = 'sLORETA';
content = 'source reconstruction';
% known AFNI file types
elseif filetype_check_extension(filename, '.brik') || filetype_check_extension(filename, '.BRIK')
type = 'afni_brik';
content = 'MRI image data';
elseif filetype_check_extension(filename, '.head') || filetype_check_extension(filename, '.HEAD')
type = 'afni_head';
content = 'MRI header data';
% known BrainVison file types
elseif filetype_check_extension(filename, '.vhdr')
type = 'brainvision_vhdr';
manufacturer = 'BrainProducts';
content = 'EEG header';
elseif filetype_check_extension(filename, '.vmrk')
type = 'brainvision_vmrk';
manufacturer = 'BrainProducts';
content = 'EEG markers';
elseif filetype_check_extension(filename, '.vabs')
type = 'brainvision_vabs';
manufacturer = 'BrainProducts';
content = 'Brain Vison Analyzer macro';
elseif filetype_check_extension(filename, '.eeg') && exist(fullfile(p, [f '.vhdr']), 'file')
type = 'brainvision_eeg';
manufacturer = 'BrainProducts';
content = 'continuous EEG data';
elseif filetype_check_extension(filename, '.seg')
type = 'brainvision_seg';
manufacturer = 'BrainProducts';
content = 'segmented EEG data';
elseif filetype_check_extension(filename, '.dat') && exist(fullfile(p, [f '.vhdr']), 'file') &&...
~filetype_check_header(filename, 'HeaderLen=') && ~filetype_check_header(filename, 'BESA_SA_IMAGE') &&...
~(exist(fullfile(p, [f '.gen']), 'file') || exist(fullfile(p, [f '.generic']), 'file'))
% WARNING this is a very general name, it could be exported BrainVision
% data but also a BESA beamformer source reconstruction or BCI2000
type = 'brainvision_dat';
manufacturer = 'BrainProducts';
content = 'exported EEG data';
elseif filetype_check_extension(filename, '.marker')
type = 'brainvision_marker';
manufacturer = 'BrainProducts';
content = 'rejection markers';
% known Polhemus file types
elseif filetype_check_extension(filename, '.pos')
type = 'polhemus_pos';
manufacturer = 'BrainProducts/CTF/Polhemus?'; % actually I don't know whose software it is
content = 'electrode positions';
% known Neuralynx file types
elseif filetype_check_extension(filename, '.nev') || filetype_check_extension(filename, '.Nev')
type = 'neuralynx_nev';
manufacturer = 'Neuralynx';
content = 'event information';
elseif filetype_check_extension(filename, '.ncs') && filetype_check_header(filename, '####')
type = 'neuralynx_ncs';
manufacturer = 'Neuralynx';
content = 'continuous single channel recordings';
elseif filetype_check_extension(filename, '.nse') && filetype_check_header(filename, '####')
type = 'neuralynx_nse';
manufacturer = 'Neuralynx';
content = 'spike waveforms';
elseif filetype_check_extension(filename, '.nts') && filetype_check_header(filename, '####')
type = 'neuralynx_nts';
manufacturer = 'Neuralynx';
content = 'timestamps only';
elseif filetype_check_extension(filename, '.nvt')
type = 'neuralynx_nvt';
manufacturer = 'Neuralynx';
content = 'video tracker';
elseif filetype_check_extension(filename, '.nst')
type = 'neuralynx_nst';
manufacturer = 'Neuralynx';
content = 'continuous stereotrode recordings';
elseif filetype_check_extension(filename, '.ntt')
type = 'neuralynx_ntt';
manufacturer = 'Neuralynx';
content = 'continuous tetrode recordings';
elseif strcmpi(f, 'logfile') && strcmpi(x, '.txt') % case insensitive
type = 'neuralynx_log';
manufacturer = 'Neuralynx';
content = 'log information in ASCII format';
elseif ~isempty(strfind(lower(f), 'dma')) && strcmpi(x, '.log') % this is not a very strong detection
type = 'neuralynx_dma';
manufacturer = 'Neuralynx';
content = 'raw aplifier data directly from DMA';
elseif filetype_check_extension(filename, '.nrd') % see also above, since Cheetah 5.x the file extension has changed
type = 'neuralynx_dma';
manufacturer = 'Neuralynx';
content = 'raw aplifier data directly from DMA';
elseif isdir(filename) && (any(filetype_check_extension({ls.name}, '.nev')) || any(filetype_check_extension({ls.name}, '.Nev')))
% a regular Neuralynx dataset directory that contains an event file
type = 'neuralynx_ds';
manufacturer = 'Neuralynx';
content = 'dataset';
elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.ncs'))
% a directory containing continuously sampled channels in Neuralynx format
type = 'neuralynx_ds';
manufacturer = 'Neuralynx';
content = 'continuously sampled channels';
elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.nse'))
% a directory containing spike waveforms in Neuralynx format
type = 'neuralynx_ds';
manufacturer = 'Neuralynx';
content = 'spike waveforms';
elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.nte'))
% a directory containing spike timestamps in Neuralynx format
type = 'neuralynx_ds';
manufacturer = 'Neuralynx';
content = 'spike timestamps';
elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.ntt'))
% a directory containing tetrode recordings in Neuralynx format
type = 'neuralynx_ds';
manufacturer = 'Neuralynx';
content = 'tetrode recordings ';
elseif isdir(p) && exist(fullfile(p, 'header'), 'file') && exist(fullfile(p, 'samples'), 'file') && exist(fullfile(p, 'events'), 'file')
type = 'fcdc_buffer_offline';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'FieldTrip buffer offline dataset';
elseif isdir(filename) && exist(fullfile(filename, 'info.xml'), 'file') && exist(fullfile(filename, 'signal1.bin'), 'file')
% this is an OS X package directory representing a complete EEG dataset
% it contains a Content file, multiple xml files and one or more signalN.bin files
type = 'egi_mff';
manufacturer = 'Electrical Geodesics Incorporated';
content = 'raw EEG data';
elseif ~isdir(filename) && isdir(p) && exist(fullfile(p, 'info.xml'), 'file') && exist(fullfile(p, 'signal1.bin'), 'file')
% the file that the user specified is one of the files in an mff package directory
type = 'egi_mff';
manufacturer = 'Electrical Geodesics Incorporated';
content = 'raw EEG data';
% these are formally not Neuralynx file formats, but at the FCDC we use them together with Neuralynx
elseif isdir(filename) && filetype_check_neuralynx_cds(filename)
% a downsampled Neuralynx DMA file can be split into three separate lfp/mua/spike directories
% treat them as one combined dataset
type = 'neuralynx_cds';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'dataset containing separate lfp/mua/spike directories';
elseif filetype_check_extension(filename, '.tsl') && filetype_check_header(filename, 'tsl')
type = 'neuralynx_tsl';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'timestamps from DMA log file';
elseif filetype_check_extension(filename, '.tsh') && filetype_check_header(filename, 'tsh')
type = 'neuralynx_tsh';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'timestamps from DMA log file';
elseif filetype_check_extension(filename, '.ttl') && filetype_check_header(filename, 'ttl')
type = 'neuralynx_ttl';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'Parallel_in from DMA log file';
elseif filetype_check_extension(filename, '.bin') && filetype_check_header(filename, {'uint8', 'uint16', 'uint32', 'int8', 'int16', 'int32', 'int64', 'float32', 'float64'})
type = 'neuralynx_bin';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'single channel continuous data';
elseif isdir(filename) && any(filetype_check_extension({ls.name}, '.ttl')) && any(filetype_check_extension({ls.name}, '.tsl')) && any(filetype_check_extension({ls.name}, '.tsh'))
% a directory containing the split channels from a DMA logfile
type = 'neuralynx_sdma';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'split DMA log file';
elseif isdir(filename) && filetype_check_extension(filename, '.sdma')
% a directory containing the split channels from a DMA logfile
type = 'neuralynx_sdma';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'split DMA log file';
% known Plexon file types
elseif filetype_check_extension(filename, '.nex') && filetype_check_header(filename, 'NEX1')
type = 'plexon_nex';
manufacturer = 'Plexon';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.plx') && filetype_check_header(filename, 'PLEX')
type = 'plexon_plx';
manufacturer = 'Plexon';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.ddt')
type = 'plexon_ddt';
manufacturer = 'Plexon';
elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.nex')) && most(filetype_check_header({ls.name}, 'NEX1'))
% a directory containing multiple plexon NEX files
type = 'plexon_ds';
manufacturer = 'Plexon';
content = 'electrophysiological data';
% known Cambridge Electronic Design file types
elseif filetype_check_extension(filename, '.smr')
type = 'ced_son';
manufacturer = 'Cambridge Electronic Design';
content = 'Spike2 SON filing system';
% known BESA file types
elseif filetype_check_extension(filename, '.avr') && strcmp(type, 'unknown')
type = 'besa_avr'; % FIXME, can also be EEProbe average EEG
manufacturer = 'BESA';
content = 'average EEG';
elseif filetype_check_extension(filename, '.elp')
type = 'besa_elp';
manufacturer = 'BESA';
content = 'electrode positions';
elseif filetype_check_extension(filename, '.eps')
type = 'besa_eps';
manufacturer = 'BESA';
content = 'digitizer information';
elseif filetype_check_extension(filename, '.sfp')
type = 'besa_sfp';
manufacturer = 'BESA';
content = 'sensor positions';
elseif filetype_check_extension(filename, '.ela')
type = 'besa_ela';
manufacturer = 'BESA';
content = 'sensor information';
elseif filetype_check_extension(filename, '.pdg')
type = 'besa_pdg';
manufacturer = 'BESA';
content = 'paradigm file';
elseif filetype_check_extension(filename, '.tfc')
type = 'besa_tfc';
manufacturer = 'BESA';
content = 'time frequency coherence';
elseif filetype_check_extension(filename, '.mul')
type = 'besa_mul';
manufacturer = 'BESA';
content = 'multiplexed ascii format';
elseif filetype_check_extension(filename, '.dat') && filetype_check_header(filename, 'BESA_SA') % header can start with BESA_SA_IMAGE or BESA_SA_MN_IMAGE
type = 'besa_src';
manufacturer = 'BESA';
content = 'beamformer source reconstruction';
elseif filetype_check_extension(filename, '.swf') && filetype_check_header(filename, 'Npts=')
type = 'besa_swf';
manufacturer = 'BESA';
content = 'beamformer source waveform';
elseif filetype_check_extension(filename, '.bsa')
type = 'besa_bsa';
manufacturer = 'BESA';
content = 'beamformer source locations and orientations';
elseif exist(fullfile(p, [f '.dat']), 'file') && (exist(fullfile(p, [f '.gen']), 'file') || exist(fullfile(p, [f '.generic']), 'file'))
type = 'besa_sb';
manufacturer = 'BESA';
content = 'simple binary channel data with a separate generic ascii header';
elseif filetype_check_extension(filename, '.sfh') && filetype_check_header(filename, 'NrOfPoints')
type = 'besa_sfh';
manufacturer = 'BESA';
content = 'electrode and fiducial information';
elseif filetype_check_extension(filename, '.srf') && filetype_check_header(filename, [0 0 0 0], 4)
type = 'brainvoyager_srf';
manufacturer = 'BrainVoyager'; % see http://support.brainvoyager.com/installation-introduction/23-file-formats/375-users-guide-23-the-format-of-srf-files.html
content = 'surface';
% known Dataq file formats
elseif filetype_check_extension(upper(filename), '.WDQ')
type = 'dataq_wdq';
manufacturer = 'dataq instruments';
content = 'electrophysiological data';
% old files from Pascal Fries' PhD research at the MPI
elseif filetype_check_extension(filename, '.dap') && filetype_check_header(filename, char(1))
type = 'mpi_dap';
manufacturer = 'MPI Frankfurt';
content = 'electrophysiological data';
elseif isdir(filename) && ~isempty(cell2mat(regexp({ls.name}, '.dap$')))
type = 'mpi_ds';
manufacturer = 'MPI Frankfurt';
content = 'electrophysiological data';
% Frankfurt SPASS format, which uses the Labview Datalog (DTLG) format
elseif filetype_check_extension(filename, '.ana') && filetype_check_header(filename, 'DTLG')
type = 'spass_ana';
manufacturer = 'MPI Frankfurt';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.swa') && filetype_check_header(filename, 'DTLG')
type = 'spass_swa';
manufacturer = 'MPI Frankfurt';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.spi') && filetype_check_header(filename, 'DTLG')
type = 'spass_spi';
manufacturer = 'MPI Frankfurt';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.stm') && filetype_check_header(filename, 'DTLG')
type = 'spass_stm';
manufacturer = 'MPI Frankfurt';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.bhv') && filetype_check_header(filename, 'DTLG')
type = 'spass_bhv';
manufacturer = 'MPI Frankfurt';
content = 'electrophysiological data';
% known Chieti ITAB file types
elseif filetype_check_extension(filename, '.raw') && (filetype_check_header(filename, 'FORMAT: ATB-BIOMAGDATA') || filetype_check_header(filename, '[HeaderType]'))
type = 'itab_raw';
manufacturer = 'Chieti ITAB';
content = 'MEG data, including sensor positions';
elseif filetype_check_extension(filename, '.raw.mhd')
type = 'itab_mhd';
manufacturer = 'Chieti ITAB';
content = 'MEG header data, including sensor positions';
elseif filetype_check_extension(filename, '.asc') && ~filetype_check_header(filename, '**')
type = 'itab_asc';
manufacturer = 'Chieti ITAB';
content = 'headshape digitization file';
% known Nexstim file types
elseif filetype_check_extension(filename, '.nxe')
type = 'nexstim_nxe';
manufacturer = 'Nexstim';
content = 'electrophysiological data';
% known Tucker-Davis-Technology file types
elseif filetype_check_extension(filename, '.tbk')
type = 'tdt_tbk';
manufacturer = 'Tucker-Davis-Technology';
content = 'database/tank meta-information';
elseif filetype_check_extension(filename, '.tdx')
type = 'tdt_tdx';
manufacturer = 'Tucker-Davis-Technology';
content = 'database/tank meta-information';
elseif filetype_check_extension(filename, '.tsq')
type = 'tdt_tsq';
manufacturer = 'Tucker-Davis-Technology';
content = 'block header information';
elseif filetype_check_extension(filename, '.tev')
type = 'tdt_tev';
manufacturer = 'Tucker-Davis-Technology';
content = 'electrophysiological data';
elseif (filetype_check_extension(filename, '.dat') || filetype_check_extension(filename, '.Dat')) && (exist(fullfile(p, [f '.ini']), 'file') || exist(fullfile(p, [f '.Ini']), 'file'))
% this should go before curry_dat
type = 'deymed_dat';
manufacturer = 'Deymed';
content = 'raw eeg data';
elseif (filetype_check_extension(filename, '.ini') || filetype_check_extension(filename, '.Ini')) && (exist(fullfile(p, [f '.dat']), 'file') || exist(fullfile(p, [f '.Dat']), 'file'))
type = 'deymed_ini';
manufacturer = 'Deymed';
content = 'eeg header information';
elseif filetype_check_extension(filename, '.dat') && (filetype_check_header(filename, [0 0 16 0 16 0], 8) || filetype_check_header(filename, [0 0 16 0 16 0], 0))
% this should go before curry_dat
type = 'jaga16';
manufacturer = 'Jinga-Hi';
content = 'electrophysiological data';
% known Curry V4 file types
elseif filetype_check_extension(filename, '.dap')
type = 'curry_dap'; % FIXME, can also be MPI Frankfurt electrophysiological data
manufacturer = 'Curry';
content = 'data parameter file';
elseif filetype_check_extension(filename, '.dat')
type = 'curry_dat';
manufacturer = 'Curry';
content = 'raw data file';
elseif filetype_check_extension(filename, '.rs4')
type = 'curry_rs4';
manufacturer = 'Curry';
content = 'sensor geometry file';
elseif filetype_check_extension(filename, '.par')
type = 'curry_par';
manufacturer = 'Curry';
content = 'data or image parameter file';
elseif filetype_check_extension(filename, '.bd0') || filetype_check_extension(filename, '.bd1') || filetype_check_extension(filename, '.bd2') || filetype_check_extension(filename, '.bd3') || filetype_check_extension(filename, '.bd4') || filetype_check_extension(filename, '.bd5') || filetype_check_extension(filename, '.bd6') || filetype_check_extension(filename, '.bd7') || filetype_check_extension(filename, '.bd8') || filetype_check_extension(filename, '.bd9')
type = 'curry_bd';
manufacturer = 'Curry';
content = 'BEM description file';
elseif filetype_check_extension(filename, '.bt0') || filetype_check_extension(filename, '.bt1') || filetype_check_extension(filename, '.bt2') || filetype_check_extension(filename, '.bt3') || filetype_check_extension(filename, '.bt4') || filetype_check_extension(filename, '.bt5') || filetype_check_extension(filename, '.bt6') || filetype_check_extension(filename, '.bt7') || filetype_check_extension(filename, '.bt8') || filetype_check_extension(filename, '.bt9')
type = 'curry_bt';
manufacturer = 'Curry';
content = 'BEM transfer matrix file';
elseif filetype_check_extension(filename, '.bm0') || filetype_check_extension(filename, '.bm1') || filetype_check_extension(filename, '.bm2') || filetype_check_extension(filename, '.bm3') || filetype_check_extension(filename, '.bm4') || filetype_check_extension(filename, '.bm5') || filetype_check_extension(filename, '.bm6') || filetype_check_extension(filename, '.bm7') || filetype_check_extension(filename, '.bm8') || filetype_check_extension(filename, '.bm9')
type = 'curry_bm';
manufacturer = 'Curry';
content = 'BEM full matrix file';
elseif filetype_check_extension(filename, '.dig')
type = 'curry_dig';
manufacturer = 'Curry';
content = 'digitizer file';
% known SR Research eyelink file formats
elseif filetype_check_extension(filename, '.asc') && filetype_check_header(filename, '**')
type = 'eyelink_asc';
manufacturer = 'SR Research (ascii)';
content = 'eyetracker data';
elseif filetype_check_extension(filename, '.edf') && filetype_check_header(filename, 'SR_RESEARCH')
type = 'eyelink_edf';
manufacturer = 'SR Research';
content = 'eyetracker data (binary)';
% known Curry V2 file types
elseif filetype_check_extension(filename, '.sp0') || filetype_check_extension(filename, '.sp1') || filetype_check_extension(filename, '.sp2') || filetype_check_extension(filename, '.sp3') || filetype_check_extension(filename, '.sp4') || filetype_check_extension(filename, '.sp5') || filetype_check_extension(filename, '.sp6') || filetype_check_extension(filename, '.sp7') || filetype_check_extension(filename, '.sp8') || filetype_check_extension(filename, '.sp9')
type = 'curry_sp';
manufacturer = 'Curry';
content = 'point list';
elseif filetype_check_extension(filename, '.s10') || filetype_check_extension(filename, '.s11') || filetype_check_extension(filename, '.s12') || filetype_check_extension(filename, '.s13') || filetype_check_extension(filename, '.s14') || filetype_check_extension(filename, '.s15') || filetype_check_extension(filename, '.s16') || filetype_check_extension(filename, '.s17') || filetype_check_extension(filename, '.s18') || filetype_check_extension(filename, '.s19') || filetype_check_extension(filename, '.s20') || filetype_check_extension(filename, '.s21') || filetype_check_extension(filename, '.s22') || filetype_check_extension(filename, '.s23') || filetype_check_extension(filename, '.s24') || filetype_check_extension(filename, '.s25') || filetype_check_extension(filename, '.s26') || filetype_check_extension(filename, '.s27') || filetype_check_extension(filename, '.s28') || filetype_check_extension(filename, '.s29') || filetype_check_extension(filename, '.s30') || filetype_check_extension(filename, '.s31') || filetype_check_extension(filename, '.s32') || filetype_check_extension(filename, '.s33') || filetype_check_extension(filename, '.s34') || filetype_check_extension(filename, '.s35') || filetype_check_extension(filename, '.s36') || filetype_check_extension(filename, '.s37') || filetype_check_extension(filename, '.s38') || filetype_check_extension(filename, '.s39')
type = 'curry_s';
manufacturer = 'Curry';
content = 'triangle or tetraedra list';
elseif filetype_check_extension(filename, '.pom')
type = 'curry_pom';
manufacturer = 'Curry';
content = 'anatomical localization file';
elseif filetype_check_extension(filename, '.res')
type = 'curry_res';
manufacturer = 'Curry';
content = 'functional localization file';
% known MBFYS file types
elseif filetype_check_extension(filename, '.tri')
type = 'mbfys_tri';
manufacturer = 'MBFYS';
content = 'triangulated surface';
elseif filetype_check_extension(filename, '.ama') && filetype_check_header(filename, [10 0 0 0])
type = 'mbfys_ama';
manufacturer = 'MBFYS';
content = 'BEM volume conduction model';
% Electrical Geodesics Incorporated formats
% the egi_mff format is checked earlier
elseif (filetype_check_extension(filename, '.egis') || filetype_check_extension(filename, '.ave') || filetype_check_extension(filename, '.gave') || filetype_check_extension(filename, '.raw')) && (filetype_check_header(filename, [char(1) char(2) char(3) char(4) char(255) char(255)]) || filetype_check_header(filename, [char(3) char(4) char(1) char(2) char(255) char(255)]))
type = 'egi_egia';
manufacturer = 'Electrical Geodesics Incorporated';
content = 'averaged EEG data';
elseif (filetype_check_extension(filename, '.egis') || filetype_check_extension(filename, '.ses') || filetype_check_extension(filename, '.raw')) && (filetype_check_header(filename, [char(1) char(2) char(3) char(4) char(0) char(3)]) || filetype_check_header(filename, [char(3) char(4) char(1) char(2) char(0) char(3)]))
type = 'egi_egis';
manufacturer = 'Electrical Geodesics Incorporated';
content = 'raw EEG data';
elseif (filetype_check_extension(filename, '.sbin') || filetype_check_extension(filename, '.raw'))
% note that the Chieti MEG data format also has the extension *.raw
% but that can be detected by looking at the file header
type = 'egi_sbin';
manufacturer = 'Electrical Geodesics Incorporated';
content = 'averaged EEG data';
% FreeSurfer file formats, see also http://www.grahamwideman.com/gw/brain/fs/surfacefileformats.htm
elseif filetype_check_extension(filename, '.mgz')
type = 'freesurfer_mgz';
manufacturer = 'FreeSurfer';
content = 'anatomical MRI';
elseif filetype_check_extension(filename, '.mgh')
type = 'freesurfer_mgh';
manufacturer = 'FreeSurfer';
content = 'anatomical MRI';
elseif filetype_check_header(filename, [255 255 254])
% FreeSurfer Triangle Surface Binary Format
type = 'freesurfer_triangle_binary'; % there is also an ascii triangle format
manufacturer = 'FreeSurfer';
content = 'surface description';
elseif filetype_check_header(filename, [255 255 255])
% Quadrangle File
type = 'freesurfer_quadrangle'; % there is no ascii quadrangle format
manufacturer = 'FreeSurfer';
content = 'surface description';
elseif filetype_check_header(filename, [255 255 253]) && ~exist([filename(1:(end-4)) '.mat'], 'file')
% "New" Quadrangle File
type = 'freesurfer_quadrangle_new';
manufacturer = 'FreeSurfer';
content = 'surface description';
elseif filetype_check_extension(filename, '.curv') && filetype_check_header(filename, [255 255 255])
% "New" Curv File
type = 'freesurfer_curv_new';
manufacturer = 'FreeSurfer';
content = 'surface description';
elseif filetype_check_extension(filename, '.annot')
% Freesurfer annotation file
type = 'freesurfer_annot';
manufacturer = 'FreeSurfer';
content = 'parcellation annotation';
elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'_nrs_')) == 1
% This may be improved by looking into the file, rather than assuming the
% filename has "_nrs_" somewhere. Also, distinction by the different file
% types could be made
type = 'bucn_nirs';
manufacturer = 'BUCN';
content = 'ascii formatted nirs data';
% known Artinis file format
elseif filetype_check_extension(filename, '.oxy3')
type = 'oxy3';
manufacturer = 'Artinis Medical Systems';
content = '(f)NIRS data';
% known TETGEN file types, see http://tetgen.berlios.de/fformats.html
elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.poly']), 'file')
type = 'tetgen_poly';
manufacturer = 'TetGen, see http://tetgen.berlios.de';
content = 'geometrical data desribed with piecewise linear complex';
elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.smesh']), 'file')
type = 'tetgensmesh';
manufacturer = 'TetGen, see http://tetgen.berlios.de';
content = 'geometrical data desribed with simple piecewise linear complex';
elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.ele']), 'file')
type = 'tetgen_ele';
manufacturer = 'TetGen, see http://tetgen.berlios.de';
content = 'geometrical data desribed with tetrahedra';
elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.face']), 'file')
type = 'tetgen_face';
manufacturer = 'TetGen, see http://tetgen.berlios.de';
content = 'geometrical data desribed with triangular faces';
elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.edge']), 'file')
type = 'tetgen_edge';
manufacturer = 'TetGen, see http://tetgen.berlios.de';
content = 'geometrical data desribed with boundary edges';
elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.vol']), 'file')
type = 'tetgen_vol';
manufacturer = 'TetGen, see http://tetgen.berlios.de';
content = 'geometrical data desribed with maximum volumes';
elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.var']), 'file')
type = 'tetgen_var';
manufacturer = 'TetGen, see http://tetgen.berlios.de';
content = 'geometrical data desribed with variant constraints for facets/segments';
elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.neigh']), 'file')
type = 'tetgen_neigh';
manufacturer = 'TetGen, see http://tetgen.berlios.de';
content = 'geometrical data desribed with neighbors';
elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100)
type = 'tetgen_node';
manufacturer = 'TetGen, see http://tetgen.berlios.de';
content = 'geometrical data desribed with only nodes';
% some BrainSuite file formats, see http://brainsuite.bmap.ucla.edu/
elseif filetype_check_extension(filename, '.dfs') && filetype_check_header(filename, 'DFS_LE v2.0')
type = 'brainsuite_dfs';
manufacturer = 'BrainSuite, see http://brainsuite.bmap.ucla.edu';
content = 'list of triangles and vertices';
elseif filetype_check_extension(filename, '.bst') && filetype_check_ascii(filename)
type = 'brainsuite_dst';
manufacturer = 'BrainSuite, see http://brainsuite.bmap.ucla.edu';
content = 'a collection of files with geometrical data'; % it seems to be similar to a Caret *.spec file
elseif filetype_check_extension(filename, '.dfc') && filetype_check_header(filename, 'LONIDFC')
type = 'loni_dfc';
manufacturer = 'LONI'; % it is used in BrainSuite
content = 'curvature information';
% some BrainVISA file formats, see http://brainvisa.info
elseif filetype_check_extension(filename, '.mesh') && (filetype_check_header(filename, 'ascii') || filetype_check_header(filename, 'binarABCD') || filetype_check_header(filename, 'binarDCBA')) % http://brainvisa.info/doc/documents-4.4/formats/mesh.pdf
type = 'brainvisa_mesh';
manufacturer = 'BrainVISA';
content = 'vertices and triangles';
elseif filetype_check_extension(filename, '.minf') && filetype_check_ascii(filename)
type = 'brainvisa_minf';
manufacturer = 'BrainVISA';
content = 'annotation/metadata';
% some other known file types
elseif length(filename)>4 && exist([filename(1:(end-4)) '.mat'], 'file') && exist([filename(1:(end-4)) '.bin'], 'file')
% this is a self-defined FCDC data format, consisting of two files
% there is a MATLAB V6 file with the header and a binary file with the data (multiplexed, ieee-le, double)
type = 'fcdc_matbin';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'multiplexed electrophysiology data';
elseif filetype_check_extension(filename, '.lay')
type = 'layout';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'layout of channels for plotting';
elseif filetype_check_extension(filename, '.stl')
type = 'stl';
manufacturer = 'various';
content = 'stereo litography file';
elseif filetype_check_extension(filename, '.dcm') || filetype_check_extension(filename, '.ima') || filetype_check_header(filename, 'DICM', 128)
type = 'dicom';
manufacturer = 'Dicom';
content = 'image data';
elseif filetype_check_extension(filename, '.trl')
type = 'fcdc_trl';
manufacturer = 'Donders Centre for Cognitive Neuroimaging';
content = 'trial definitions';
elseif filetype_check_extension(filename, '.bdf') && filetype_check_header(filename, [255 'BIOSEMI'])
type = 'biosemi_bdf';
manufacturer = 'Biosemi Data Format';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.edf')
type = 'edf';
manufacturer = 'European Data Format';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.gdf') && filetype_check_header(filename, 'GDF')
type = 'gdf';
manufacturer = 'BIOSIG - Alois Schloegl';
content = 'biosignals';
elseif filetype_check_extension(filename, '.mat') && filetype_check_header(filename, 'MATLAB') && filetype_check_spmeeg_mat(filename)
type = 'spmeeg_mat';
manufacturer = 'Wellcome Trust Centre for Neuroimaging, UCL, UK';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.mat') && filetype_check_header(filename, 'MATLAB') && filetype_check_gtec_mat(filename)
type = 'gtec_mat';
manufacturer = 'Guger Technologies, http://www.gtec.at';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.mat') && filetype_check_header(filename, 'MATLAB') && filetype_check_ced_spike6mat(filename)
type = 'ced_spike6mat';
manufacturer = 'Cambridge Electronic Design Limited';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.mat') && filetype_check_header(filename, 'MATLAB')
type = 'matlab';
manufacturer = 'MATLAB';
content = 'MATLAB binary data';
elseif filetype_check_header(filename, 'RIFF', 0) && filetype_check_header(filename, 'WAVE', 8)
type = 'riff_wave';
manufacturer = 'Microsoft';
content = 'audio';
elseif filetype_check_extension(filename, '.txt') && filetype_check_header(filename, 'Site')
type = 'easycap_txt';
manufacturer = 'Easycap';
content = 'electrode positions';
elseif filetype_check_extension(filename, '.txt')
type = 'ascii_txt';
manufacturer = '';
content = '';
elseif filetype_check_extension(filename, '.pol')
type = 'polhemus_fil';
manufacturer = 'Functional Imaging Lab, London, UK';
content = 'headshape points';
elseif filetype_check_extension(filename, '.set')
type = 'eeglab_set';
manufacturer = 'Swartz Center for Computational Neuroscience, San Diego, USA';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.erp')
type = 'eeglab_erp';
manufacturer = 'Swartz Center for Computational Neuroscience, San Diego, USA';
content = 'electrophysiological data';
elseif filetype_check_extension(filename, '.t') && filetype_check_header(filename, '%%BEGINHEADER')
type = 'mclust_t';
manufacturer = 'MClust';
content = 'sorted spikes';
elseif filetype_check_header(filename, 26)
type = 'nimh_cortex';
manufacturer = 'NIMH Laboratory of Neuropsychology, http://www.cortex.salk.edu';
content = 'events and eye channels';
elseif filetype_check_extension(filename, '.foci') && filetype_check_header(filename, '<?xml')
type = 'caret_foci';
manufacturer = 'Caret and ConnectomeWB';
elseif filetype_check_extension(filename, '.border') && filetype_check_header(filename, '<?xml')
type = 'caret_border';
manufacturer = 'Caret and ConnectomeWB';
elseif filetype_check_extension(filename, '.spec') && (filetype_check_header(filename, '<?xml') || filetype_check_header(filename, 'BeginHeader'))
type = 'caret_spec';
manufacturer = 'Caret and ConnectomeWB';
elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.coord.')) && filetype_check_header(filename, '<?xml')
type = 'caret_coord';
manufacturer = 'Caret and ConnectomeWB';
elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.topo.')) && filetype_check_header(filename, '<?xml')
type = 'caret_topo';
manufacturer = 'Caret and ConnectomeWB';
elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.surf.')) && filetype_check_header(filename, '<?xml')
type = 'caret_surf';
manufacturer = 'Caret and ConnectomeWB';
elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.label.')) && filetype_check_header(filename, '<?xml')
type = 'caret_label';
manufacturer = 'Caret and ConnectomeWB';
elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.func.')) && filetype_check_header(filename, '<?xml')
type = 'caret_func';
manufacturer = 'Caret and ConnectomeWB';
elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.shape.')) && filetype_check_header(filename, '<?xml')
type = 'caret_shape';
manufacturer = 'Caret and ConnectomeWB';
elseif filetype_check_extension(filename, '.gii') && filetype_check_header(filename, '<?xml')
type = 'gifti';
manufacturer = 'Neuroimaging Informatics Technology Initiative';
content = 'tesselated surface description';
elseif filetype_check_extension(filename, '.v')
type = 'vista';
manufacturer = 'University of British Columbia, Canada, http://www.cs.ubc.ca/nest/lci/vista/vista.html';
content = 'A format for computer vision research, contains meshes or volumes';
elseif filetype_check_extension(filename, '.tet')
type = 'tet';
manufacturer = 'a.o. INRIA, see http://shapes.aimatshape.net/';
content = 'tetraedral mesh';
elseif filetype_check_extension(filename, '.nc')
type = 'netmeg';
manufacturer = 'Center for Biomedical Research Excellence (COBRE), see http://cobre.mrn.org/megsim/tools/netMEG/netMEG.html';
content = 'MEG data';
elseif filetype_check_extension(filename, 'trk')
type = 'trackvis_trk';
manufacturer = 'Martinos Center for Biomedical Imaging, see http://www.trackvis.org';
content = 'fiber tracking data from diffusion MR imaging';
elseif filetype_check_extension(filename, '.xml') && filetype_check_header(filename, '<EEGMarkerList', 39)
type = 'localite_pos';
manufacturer = 'Localite';
content = 'EEG electrode positions';
elseif filetype_check_extension(filename, '.mbi')
type = 'manscan_mbi';
manufacturer = 'MANSCAN';
content = 'EEG header';
elseif filetype_check_extension(filename, '.mb2')
type = 'manscan_mb2';
manufacturer = 'MANSCAN';
content = 'EEG data';
elseif filetype_check_header(filename, 'ply')
type = 'ply';
manufacturer = 'Stanford Triangle Format';
content = 'three dimensional data from 3D scanners, see http://en.wikipedia.org/wiki/PLY_(file_format)';
elseif filetype_check_extension(filename, '.csv')
type = 'csv';
manufacturer = 'Generic';
content = 'Comma-separated values, see http://en.wikipedia.org/wiki/Comma-separated_values';
elseif filetype_check_extension(filename, '.ah5')
type = 'AnyWave';
manufacturer = 'AnyWave, http://meg.univ-amu.fr/wiki/AnyWave';
content = 'MEG/SEEG/EEG data';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% finished determining the filetype
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(type, 'unknown')
if ~exist(filename, 'file') && ~exist(filename, 'dir')
warning('file or directory "%s" does not exist, could not determine fileformat', filename);
else
warning('could not determine filetype of %s', filename);
end
end
if ~isempty(desired)
% return a boolean value instead of a descriptive string
type = strcmp(type, desired);
end
% remember the current input and output arguments, so that they can be
% reused on a subsequent call in case the same input argument is given
current_argout = {type};
if isempty(previous_argin) && ~strcmp(type, 'unknown')
previous_argin = current_argin;
previous_argout = current_argout;
previous_pwd = current_pwd;
elseif isempty(previous_argin) && (exist(filename,'file') || exist(filename,'dir')) && strcmp(type, 'unknown') % if the type is unknown, but the file or dir exists, save the current output
previous_argin = current_argin;
previous_argout = current_argout;
previous_pwd = current_pwd;
else
% don't remember in case unknown
previous_argin = [];
previous_argout = [];
previous_pwd = [];
end
return % filetype main()
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that helps in deciding whether a directory with files should
% be treated as a "dataset". This function returns a logical 1 (TRUE) if more
% than half of the element of a vector are nonzero number or are 1 or TRUE.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = most(x)
x = x(~isnan(x(:)));
y = sum(x==0)<ceil(length(x)/2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that always returns a true value
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function y = filetype_true(varargin)
y = 1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that checks for CED spike6 mat file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = filetype_check_ced_spike6mat(filename)
res = 1;
var = whos('-file', filename);
% Check whether all the variables in the file are structs (representing channels)
if ~all(strcmp('struct', unique({var(:).class})) == 1)
res = 0;
return;
end
var = load(filename, var(1).name);
var = struct2cell(var);
% Check whether the fields of the first struct have some particular names
fnames = {
'title'
'comment'
'interval'
'scale'
'offset'
'units'
'start'
'length'
'values'
'times'
};
res = (numel(intersect(fieldnames(var{1}), fnames)) >= 5);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that checks for a SPM eeg/meg mat file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = filetype_check_spmeeg_mat(filename)
% check for the accompanying *.dat file
res = exist([filename(1:(end-4)) '.dat'], 'file');
if ~res, return; end
% check the content of the *.mat file
var = whos('-file', filename);
res = res && numel(var)==1;
res = res && strcmp('D', getfield(var, {1}, 'name'));
res = res && strcmp('struct', getfield(var, {1}, 'class'));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that checks for a GTEC mat file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = filetype_check_gtec_mat(filename)
% check the content of the *.mat file
var = whos('-file', filename);
res = length(intersect({'log', 'names'}, {var.name}))==2;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that checks the presence of a specified file in a directory
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = filetype_check_dir(p, filename)
if ~isempty(p)
d = dir(p);
else
d = dir;
end
res = any(strcmp(filename,{d.name}));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that checks whether the directory is neuralynx_cds
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = filetype_check_neuralynx_cds(filename)
res=false;
files=dir(filename);
dirlist=files([files.isdir]);
% 1) check for a subdirectory with extension .lfp, .mua or .spike
haslfp = any(filetype_check_extension({dirlist.name}, 'lfp'));
hasmua = any(filetype_check_extension({dirlist.name}, 'mua'));
hasspike = any(filetype_check_extension({dirlist.name}, 'spike'));
% 2) check for each of the subdirs being a neuralynx_ds
if haslfp || hasmua || hasspike
sel=find(filetype_check_extension({dirlist.name}, 'lfp')+...
filetype_check_extension({dirlist.name}, 'mua')+...
filetype_check_extension({dirlist.name}, 'spike'));
neuralynxdirs=cell(1,length(sel));
for n=1:length(sel)
neuralynxdirs{n}=fullfile(filename, dirlist(sel(n)).name);
end
res=any(ft_filetype(neuralynxdirs, 'neuralynx_ds'));
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that checks whether the file contains only ascii characters
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function res = filetype_check_ascii(filename, len)
% See http://en.wikipedia.org/wiki/ASCII
if exist(filename, 'file')
fid = fopen(filename, 'rt');
bin = fread(fid, len, 'uint8=>uint8');
fclose(fid);
printable = bin>31 & bin<127; % the printable characters, represent letters, digits, punctuation marks, and a few miscellaneous symbols
special = bin==10 | bin==13 | bin==11; % line feed, form feed, tab
res = all(printable | special);
else
% always return true if the file does not (yet) exist, this is important
% for determining the format to which data should be written
res = 1;
end
|
github
|
ZijingMao/baselineeegtest-master
|
getdimord.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/getdimord.m
| 18,939 |
utf_8
|
7602345b5b12d24e2e0612acc7731b4d
|
function dimord = getdimord(data, field, varargin)
% GETDIMORD
%
% Use as
% dimord = getdimord(data, field)
%
% See also GETDIMSIZ
if ~isfield(data, field) && isfield(data, 'avg') && isfield(data.avg, field)
field = ['avg.' field];
elseif ~isfield(data, field) && isfield(data, 'trial') && isfield(data.trial, field)
field = ['trial.' field];
elseif ~isfield(data, field)
error('field "%s" not present in data', field);
end
if strncmp(field, 'avg.', 4)
prefix = '';
field = field(5:end); % strip the avg
data.(field) = data.avg.(field); % copy the avg into the main structure
data = rmfield(data, 'avg');
elseif strncmp(field, 'trial.', 6)
prefix = '(rpt)_';
field = field(7:end); % strip the trial
data.(field) = data.trial(1).(field); % copy the first trial into the main structure
data = rmfield(data, 'trial');
else
prefix = '';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ATTEMPT 1: the specific dimord is simply present
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfield(data, [field 'dimord'])
dimord = data.([field 'dimord']);
return
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% if not present, we need some additional information about the data strucure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% nan means that the value is not known and might remain unknown
% inf means that the value is not known but should be known
ntime = inf;
nfreq = inf;
nchan = inf;
nchancmb = inf;
nsubj = nan;
nrpt = nan;
nrpttap = nan;
npos = inf;
nori = nan; % this will be 3 in many cases
ntopochan = inf;
nspike = inf; % this is only for the first spike channel
nlag = nan;
% use an anonymous function
assign = @(var, val) assignin('caller', var, val);
% it is possible to pass additional ATTEMPTs such as nrpt, nrpttap, etc
for i=1:2:length(varargin)
assign(varargin{i}, varargin{i+1});
end
% try to determine the size of each possible dimension in the data
if isfield(data, 'label')
nchan = length(data.label);
end
if isfield(data, 'labelcmb')
nchancmb = size(data.labelcmb, 1);
end
if isfield(data, 'time')
if iscell(data.time) && ~isempty(data.time)
tmp = getdimsiz(data, 'time');
ntime = tmp(3); % raw data may contain variable length trials
else
ntime = length(data.time);
end
end
if isfield(data, 'freq')
nfreq = length(data.freq);
end
if isfield(data, 'trial') && ft_datatype(data, 'raw')
nrpt = length(data.trial);
end
if isfield(data, 'trialtime') && ft_datatype(data, 'spike')
nrpt = size(data.trialtime,1);
end
if isfield(data, 'cumtapcnt')
nrpt = size(data.cumtapcnt,1);
if numel(data.cumtapcnt)==length(data.cumtapcnt)
% it is a vector, hence it only represents repetitions
nrpttap = sum(data.cumtapcnt);
else
% it is a matrix, hence it is repetitions by frequencies
% this happens after mtmconvol with keeptrials
nrpttap = sum(data.cumtapcnt,2);
if any(nrpttap~=nrpttap(1))
warning('unexpected variation of the number of tapers over trials')
nrpttap = nan;
else
nrpttap = nrpttap(1);
end
end
end
if isfield(data, 'pos')
npos = size(data.pos,1);
elseif isfield(data, 'dim')
npos = prod(data.dim);
end
if isfield(data, 'csdlabel')
% this is used in PCC beamformers
if length(data.csdlabel)==npos
% each position has its own labels
len = cellfun(@numel, data.csdlabel);
len = len(len~=0);
if all(len==len(1))
% they all have the same length
nori = len(1);
end
else
% one list of labels for all positions
nori = length(data.csdlabel);
end
elseif isfinite(npos)
% assume that there are three dipole orientations per source
nori = 3;
end
if isfield(data, 'topolabel')
% this is used in ICA and PCA decompositions
ntopochan = length(data.topolabel);
end
if isfield(data, 'timestamp') && iscell(data.timestamp)
nspike = length(data.timestamp{1}); % spike data: only for the first channel
end
if ft_datatype(data, 'mvar') && isfield(data, 'coeffs')
nlag = size(data.coeffs,3);
end
% determine the size of the actual data
datsiz = getdimsiz(data, field);
tok = {'subj' 'rpt' 'rpttap' 'chan' 'chancmb' 'freq' 'time' 'pos' 'ori' 'topochan' 'lag'};
siz = [nsubj nrpt nrpttap nchan nchancmb nfreq ntime npos nori ntopochan nlag];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ATTEMPT 2: a general dimord is present and might apply
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfield(data, 'dimord')
dimtok = tokenize(data.dimord, '_');
if length(dimtok)>length(datsiz) && check_trailingdimsunitlength(data, dimtok((length(datsiz)+1):end))
% add the trailing singleton dimensions to datsiz, if needed
datsiz = [datsiz ones(1,max(0,length(dimtok)-length(datsiz)))];
end
if length(dimtok)==length(datsiz)
success = false(size(dimtok));
for i=1:length(dimtok)
sel = strcmp(tok, dimtok{i});
if any(sel) && datsiz(i)==siz(sel)
success(i) = true;
elseif strcmp(dimtok{i}, 'subj')
% the number of subjects cannot be determined, and will be indicated as nan
success(i) = true;
elseif strcmp(dimtok{i}, 'rpt')
% the number of trials is hard to determine, and might be indicated as nan
success(i) = true;
end
end % for
if all(success)
dimord = data.dimord;
return
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ATTEMPT 3: look at the size of some common fields that are known
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
switch field
% the logic for this code is to first check whether the size of a field
% has an exact match to a potential dimensionality, if not, check for a
% partial match (ignoring nans)
% note that the case for a cell dimension (typically pos) is handled at
% the end of this section
case {'individual'}
if isequalwithoutnans(datsiz, [nsubj nchan ntime])
dimord = 'subj_chan_time';
end
case {'avg' 'var' 'dof'}
if isequal(datsiz, [nrpt nchan ntime])
dimord = 'rpt_chan_time';
elseif isequal(datsiz, [nchan ntime])
dimord = 'chan_time';
elseif isequalwithoutnans(datsiz, [nrpt nchan ntime])
dimord = 'rpt_chan_time';
elseif isequalwithoutnans(datsiz, [nchan ntime])
dimord = 'chan_time';
end
case {'powspctrm' 'fourierspctrm'}
if isequal(datsiz, [nrpt nchan nfreq ntime])
dimord = 'rpt_chan_freq_time';
elseif isequal(datsiz, [nrpt nchan nfreq])
dimord = 'rpt_chan_freq';
elseif isequal(datsiz, [nchan nfreq ntime])
dimord = 'chan_freq_time';
elseif isequal(datsiz, [nchan nfreq])
dimord = 'chan_freq';
elseif isequalwithoutnans(datsiz, [nrpt nchan nfreq ntime])
dimord = 'rpt_chan_freq_time';
elseif isequalwithoutnans(datsiz, [nrpt nchan nfreq])
dimord = 'rpt_chan_freq';
elseif isequalwithoutnans(datsiz, [nchan nfreq ntime])
dimord = 'chan_freq_time';
elseif isequalwithoutnans(datsiz, [nchan nfreq])
dimord = 'chan_freq';
end
case {'crsspctrm' 'cohspctrm'}
if isequal(datsiz, [nrpt nchancmb nfreq ntime])
dimord = 'rpt_chancmb_freq_time';
elseif isequal(datsiz, [nrpt nchancmb nfreq])
dimord = 'rpt_chancmb_freq';
elseif isequal(datsiz, [nchancmb nfreq ntime])
dimord = 'chancmb_freq_time';
elseif isequal(datsiz, [nchancmb nfreq])
dimord = 'chancmb_freq';
elseif isequal(datsiz, [nrpt nchan nchan nfreq ntime])
dimord = 'rpt_chan_chan_freq_time';
elseif isequal(datsiz, [nrpt nchan nchan nfreq])
dimord = 'rpt_chan_chan_freq';
elseif isequal(datsiz, [nchan nchan nfreq ntime])
dimord = 'chan_chan_freq_time';
elseif isequal(datsiz, [nchan nchan nfreq])
dimord = 'chan_chan_freq';
elseif isequal(datsiz, [npos nori])
dimord = 'pos_ori';
elseif isequal(datsiz, [npos 1])
dimord = 'pos';
elseif isequalwithoutnans(datsiz, [nrpt nchancmb nfreq ntime])
dimord = 'rpt_chancmb_freq_time';
elseif isequalwithoutnans(datsiz, [nrpt nchancmb nfreq])
dimord = 'rpt_chancmb_freq';
elseif isequalwithoutnans(datsiz, [nchancmb nfreq ntime])
dimord = 'chancmb_freq_time';
elseif isequalwithoutnans(datsiz, [nchancmb nfreq])
dimord = 'chancmb_freq';
elseif isequalwithoutnans(datsiz, [nrpt nchan nchan nfreq ntime])
dimord = 'rpt_chan_chan_freq_time';
elseif isequalwithoutnans(datsiz, [nrpt nchan nchan nfreq])
dimord = 'rpt_chan_chan_freq';
elseif isequalwithoutnans(datsiz, [nchan nchan nfreq ntime])
dimord = 'chan_chan_freq_time';
elseif isequalwithoutnans(datsiz, [nchan nchan nfreq])
dimord = 'chan_chan_freq';
elseif isequalwithoutnans(datsiz, [npos nori])
dimord = 'pos_ori';
elseif isequalwithoutnans(datsiz, [npos 1])
dimord = 'pos';
end
case {'cov' 'coh' 'csd' 'noisecov' 'noisecsd'}
% these occur in timelock and in source structures
if isequal(datsiz, [nrpt nchan nchan])
dimord = 'rpt_chan_chan';
elseif isequal(datsiz, [nchan nchan])
dimord = 'chan_chan';
elseif isequal(datsiz, [npos nori nori])
dimord = 'pos_ori_ori';
elseif isequal(datsiz, [npos nrpt nori nori])
dimord = 'pos_rpt_ori_ori';
elseif isequalwithoutnans(datsiz, [nrpt nchan nchan])
dimord = 'rpt_chan_chan';
elseif isequalwithoutnans(datsiz, [nchan nchan])
dimord = 'chan_chan';
elseif isequalwithoutnans(datsiz, [npos nori nori])
dimord = 'pos_ori_ori';
elseif isequalwithoutnans(datsiz, [npos nrpt nori nori])
dimord = 'pos_rpt_ori_ori';
end
case {'pow'}
if isequal(datsiz, [npos ntime])
dimord = 'pos_time';
elseif isequal(datsiz, [npos nfreq])
dimord = 'pos_freq';
elseif isequal(datsiz, [npos nrpt])
dimord = 'pos_rpt';
elseif isequal(datsiz, [nrpt npos ntime])
dimord = 'rpt_pos_time';
elseif isequal(datsiz, [nrpt npos nfreq])
dimord = 'rpt_pos_freq';
elseif isequal(datsiz, [npos 1]) % in case there are no repetitions
dimord = 'pos';
elseif isequalwithoutnans(datsiz, [npos ntime])
dimord = 'pos_time';
elseif isequalwithoutnans(datsiz, [npos nfreq])
dimord = 'pos_freq';
elseif isequalwithoutnans(datsiz, [npos nrpt])
dimord = 'pos_rpt';
elseif isequalwithoutnans(datsiz, [nrpt npos ntime])
dimord = 'rpt_pos_time';
elseif isequalwithoutnans(datsiz, [nrpt npos nfreq])
dimord = 'rpt_pos_freq';
end
case {'mom'}
if isequal(datsiz, [npos nori nrpt])
dimord = 'pos_ori_rpt';
elseif isequal(datsiz, [npos nori ntime])
dimord = 'pos_ori_time';
elseif isequal(datsiz, [npos nori nfreq])
dimord = 'pos_ori_nfreq';
elseif isequal(datsiz, [npos ntime])
dimord = 'pos_time';
elseif isequal(datsiz, [npos nfreq])
dimord = 'pos_freq';
elseif isequal(datsiz, [npos 3])
dimord = 'pos_ori';
elseif isequal(datsiz, [npos 1])
dimord = 'pos';
elseif isequal(datsiz, [npos nrpt])
dimord = 'pos_rpt';
elseif isequalwithoutnans(datsiz, [npos nori nrpt])
dimord = 'pos_ori_rpt';
elseif isequalwithoutnans(datsiz, [npos nori ntime])
dimord = 'pos_ori_time';
elseif isequalwithoutnans(datsiz, [npos nori nfreq])
dimord = 'pos_ori_nfreq';
elseif isequalwithoutnans(datsiz, [npos ntime])
dimord = 'pos_time';
elseif isequalwithoutnans(datsiz, [npos nfreq])
dimord = 'pos_freq';
elseif isequalwithoutnans(datsiz, [npos 3])
dimord = 'pos_ori';
elseif isequalwithoutnans(datsiz, [npos 1])
dimord = 'pos';
elseif isequalwithoutnans(datsiz, [npos nrpt])
dimord = 'pos_rpt';
end
case {'filter'}
if isequalwithoutnans(datsiz, [npos nori nchan]) || (isequal(datsiz([1 2]), [npos nori]) && isinf(nchan))
dimord = 'pos_ori_chan';
end
case {'leadfield'}
if isequalwithoutnans(datsiz, [npos nchan nori]) || (isequal(datsiz([1 3]), [npos nori]) && isinf(nchan))
dimord = 'pos_chan_ori';
end
case {'ori' 'eta'}
if isequal(datsiz, [npos nori]) || isequal(datsiz, [npos 3])
dimord = 'pos_ori';
end
case {'csdlabel'}
if isequal(datsiz, [npos nori]) || isequal(datsiz, [npos 3])
dimord = 'pos_ori';
end
case {'trial'}
if ~iscell(data.(field)) && isequalwithoutnans(datsiz, [nrpt nchan ntime])
dimord = 'rpt_chan_time';
elseif isequalwithoutnans(datsiz, [nrpt nchan ntime])
dimord = '{rpt}_chan_time';
elseif isequalwithoutnans(datsiz, [nchan nspike]) || isequalwithoutnans(datsiz, [nchan 1 nspike])
dimord = '{chan}_spike';
end
case {'sampleinfo' 'trialinfo' 'trialtime'}
if isequalwithoutnans(datsiz, [nrpt nan])
dimord = 'rpt_other';
end
case {'cumtapcnt' 'cumsumcnt'}
if isequalwithoutnans(datsiz, [nrpt nan])
dimord = 'rpt_other';
end
case {'topo'}
if isequalwithoutnans(datsiz, [ntopochan nchan])
dimord = 'topochan_chan';
end
case {'unmixing'}
if isequalwithoutnans(datsiz, [nchan ntopochan])
dimord = 'chan_topochan';
end
case {'inside'}
if isequalwithoutnans(datsiz, [npos])
dimord = 'pos';
end
case {'timestamp' 'time'}
if ft_datatype(data, 'spike') && iscell(data.(field)) && datsiz(1)==nchan
dimord = '{chan}_spike';
elseif ft_datatype(data, 'raw') && iscell(data.(field)) && datsiz(1)==nrpt
dimord = '{rpt}_time';
elseif isvector(data.(field)) && isequal(datsiz, [1 ntime])
dimord = 'time';
end
case {'freq'}
if isvector(data.(field)) && isequal(datsiz, [1 nfreq])
dimord = 'freq';
end
otherwise
if isfield(data, 'dim') && isequal(datsiz, data.dim)
% FIXME is this the desired dimord for volume data? A dimord of vox or voxel is not recommended according to fixdimord.
dimord = 'pos';
end
end % switch field
% deal with possible first pos which is a cell
if exist('dimord', 'var') && strcmp(dimord(1:3), 'pos') && iscell(data.(field))
dimord = ['{pos}' dimord(4:end)];
end
if ~exist('dimord', 'var')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ATTEMPT 4: there is only one way that the dimensions can be interpreted
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
dimtok = cell(size(datsiz));
for i=1:length(datsiz)
sel = find(siz==datsiz(i));
if length(sel)==1
% there is exactly one corresponding dimension
dimtok{i} = tok{sel};
else
% there are zero or multiple corresponding dimensions
dimtok{i} = [];
end
end
if all(~cellfun(@isempty, dimtok))
if iscell(data.(field))
dimtok{1} = ['{' dimtok{1} '}'];
end
dimord = sprintf('%s_', dimtok{:});
dimord = dimord(1:end-1);
return
end
end % if dimord does not exist
if ~exist('dimord', 'var')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ATTEMPT 5: compare the size with the known size of each dimension
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sel = ~isnan(siz) & ~isinf(siz);
% nan means that the value is not known and might remain unknown
% inf means that the value is not known and but should be known
if length(unique(siz(sel)))==length(siz(sel))
% this should only be done if there is no chance of confusing dimensions
dimtok = cell(size(datsiz));
dimtok(datsiz==npos) = {'pos'};
dimtok(datsiz==nori) = {'ori'};
dimtok(datsiz==nrpttap) = {'rpttap'};
dimtok(datsiz==nrpt) = {'rpt'};
dimtok(datsiz==nsubj) = {'subj'};
dimtok(datsiz==nchancmb) = {'chancmb'};
dimtok(datsiz==nchan) = {'chan'};
dimtok(datsiz==nfreq) = {'freq'};
dimtok(datsiz==ntime) = {'time'};
if isempty(dimtok{end}) && datsiz(end)==1
% remove the unknown trailing singleton dimension
dimtok = dimtok(1:end-1);
elseif isequal(dimtok{1}, 'pos') && isempty(dimtok{2}) && datsiz(2)==1
% remove the unknown leading singleton dimension
dimtok(2) = [];
end
if all(~cellfun(@isempty, dimtok))
if iscell(data.(field))
dimtok{1} = ['{' dimtok{1} '}'];
end
dimord = sprintf('%s_', dimtok{:});
dimord = dimord(1:end-1);
return
end
end
end % if dimord does not exist
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% ATTEMPT 6: return "unknown" for all unknown dimensions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~exist('dimord', 'var')
% this should not happen
% if it does, it might help in diagnosis to have a very informative warning message
% since there have been problems with trials not being selected correctly due to the warning going unnoticed
% it is better to throw an error than a warning
warning('could not determine dimord of "%s" in the following data', field)
disp(data);
dimtok(cellfun(@isempty, dimtok)) = {'unknown'};
if all(~cellfun(@isempty, dimtok))
if iscell(data.(field))
dimtok{1} = ['{' dimtok{1} '}'];
end
dimord = sprintf('%s_', dimtok{:});
dimord = dimord(1:end-1);
end
end
% add '(rpt)' in case of source.trial
dimord = [prefix dimord];
end % function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ok = isequalwithoutnans(a, b)
% this is *only* used to compare matrix sizes, so we can ignore any singleton last dimension
numdiff = numel(b)-numel(a);
if numdiff > 0
% assume singleton dimensions missing in a
a = [a(:); ones(numdiff, 1)];
b = b(:);
elseif numdiff < 0
% assume singleton dimensions missing in b
b = [b(:); ones(abs(numdiff), 1)];
a = a(:);
end
c = ~isnan(a(:)) & ~isnan(b(:));
ok = isequal(a(c), b(c));
end % function isequalwithoutnans
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ok = check_trailingdimsunitlength(data, dimtok)
ok = false;
for k = 1:numel(dimtok)
switch dimtok{k}
case 'chan'
ok = numel(data.label)==1;
otherwise
if isfield(data, dimtok{k}); % check whether field exists
ok = numel(data.(dimtok{k}))==1;
end;
end
if ok,
break;
end
end
end % function check_trailingdimsunitlength
|
github
|
ZijingMao/baselineeegtest-master
|
read_mff_bin.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_mff_bin.m
| 4,095 |
utf_8
|
14e1df31f92faf2b6f02cfe4a32060c9
|
function [output] = read_mff_bin(filename, begblock, endblock, chanindx)
% READ_MFF_BIN
%
% Use as
% [hdr] = read_mff_bin(filename)
% or
% [dat] = read_mff_bin(filename, begblock, endblock);
fid = fopen(filename,'r');
if fid == -1
error('wrong filename') % could not find signal(n)
end
needhdr = (nargin==1);
needdat = (nargin==4);
if needhdr
hdr = read_mff_block(fid, [], [], 'skip');
prevhdr = hdr(end);
for i=2:hdr.opthdr.nblocks
hdr(i) = read_mff_block(fid, prevhdr, [], 'skip');
prevhdr = hdr(end);
end
% assign the output variable
output = hdr;
elseif needdat
prevhdr = [];
dat = {};
block = 0;
while true
block = block+1;
if block<begblock
[hdr] = read_mff_block(fid, prevhdr, chanindx, 'skip');
prevhdr = hdr;
continue % with the next block
end
if block==begblock
[hdr, dat] = read_mff_block(fid, prevhdr, chanindx, 'read');
prevhdr = hdr;
continue % with the next block
end
if block<=endblock
[hdr, dat(:,end+1)] = read_mff_block(fid, prevhdr, chanindx, 'read');
prevhdr = hdr;
continue % with the next block
end
break % out of the while loop
end % while
% assign the output variable
output = dat;
end % need header or data
fclose(fid);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [hdr, dat] = read_mff_block(fid, prevhdr, chanindx, action)
if nargin<3
prevhdr = [];
end
if nargin<4
action = 'none';
end
%-Endianness
endian = 'ieee-le';
% General information
hdr.version = fread(fid, 1, 'int32', endian);
if hdr.version==0
% the header did not change compared to the previous one
% no additional information is present in the file
% the file continues with the actual data
hdr = prevhdr;
hdr.version = 0;
else
hdr.headersize = fread(fid, 1, 'int32', endian);
hdr.datasize = fread(fid, 1, 'int32', endian); % the documentation specified that this includes the data, but that seems not to be the case
hdr.nsignals = fread(fid, 1, 'int32', endian);
% channel-specific information
hdr.offset = fread(fid, hdr.nsignals, 'int32', endian);
% signal depth and frequency for each channel
for i = 1:hdr.nsignals
hdr.depth(i) = fread(fid, 1, 'int8', endian);
hdr.fsample(i) = fread(fid, 1, 'bit24', endian); %ingnie: is bit24 the same as int24?
end
%-Optional header length
hdr.optlength = fread(fid, 1, 'int32', endian);
if hdr.optlength
hdr.opthdr.EGItype = fread(fid, 1, 'int32', endian);
hdr.opthdr.nblocks = fread(fid, 1, 'int64', endian);
hdr.opthdr.nsamples = fread(fid, 1, 'int64', endian);
hdr.opthdr.nsignals = fread(fid, 1, 'int32', endian);
else
hdr.opthdr = [];
end
% determine the number of samples for each channel
hdr.nsamples = diff(hdr.offset);
% the last one has to be determined by looking at the total data block length
hdr.nsamples(end+1) = hdr.datasize - hdr.offset(end);
% divide by the number of bytes in each channel
hdr.nsamples = hdr.nsamples(:) ./ (hdr.depth(:)./8);
end % reading the rest of the header
switch action
case 'read'
dat = cell(length(chanindx), 1);
currchan = 1;
for i = 1:hdr.nsignals
switch hdr.depth(i) % length in bit
case 16
slen = 2; % sample length, for fseek
datatype = 'int16';
case 32
slen = 4; % sample length, for fseek
datatype = 'single';
case 64
slen = 8; % sample length, for fseek
datatype = 'double';
end % case
tmp = fread(fid, [1 hdr.nsamples(i)], datatype);
if ~isempty(intersect(chanindx,i)) %only keep channels that are requested
dat{currchan} = tmp;
currchan = currchan + 1;
end
end % for
case 'skip'
dat = {};
fseek(fid, hdr.datasize, 'cof');
case 'none'
dat = {};
return;
end % switch action
|
github
|
ZijingMao/baselineeegtest-master
|
ft_datatype_sens.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/ft_datatype_sens.m
| 20,793 |
utf_8
|
1a5161e33bdd52cc9dc548f1382cb532
|
function [sens] = ft_datatype_sens(sens, varargin)
% FT_DATATYPE_SENS describes the FieldTrip structure that represents
% an EEG, ECoG, or MEG sensor array. This structure is commonly called
% "elec" for EEG and "grad" for MEG, or more general "sens" for either
% one.
%
% The structure for MEG gradiometers and/or magnetometers contains
% sens.label = Mx1 cell-array with channel labels
% sens.chanpos = Mx3 matrix with channel positions
% sens.chanori = Mx3 matrix with channel orientations, used for synthetic planar gradient computation
% sens.tra = MxN matrix to combine coils into channels
% sens.coilpos = Nx3 matrix with coil positions
% sens.coilori = Nx3 matrix with coil orientations
% sens.balance = structure containing info about the balancing, See FT_APPLY_MONTAGE
%
% and optionally
% sens.chanposorg = Mx3 matrix with original channel positions (in case
% sens.chanpos has been updated to contain NaNs, e.g.
% after ft_componentanalysis)
% sens.chanoriorg = Mx3 matrix with original channel orientations
% sens.labelorg = Mx1 cell-array with original channel labels
%
% The structure for EEG or ECoG channels contains
% sens.label = Mx1 cell-array with channel labels
% sens.chanpos = Mx3 matrix with channel positions
% sens.tra = MxN matrix to combine electrodes into channels
% sens.elecpos = Nx3 matrix with electrode positions
% In case sens.tra is not present in the EEG sensor array, the channels
% are assumed to be average referenced.
%
% The following fields apply to MEG and EEG
% sens.chantype = Mx1 cell-array with the type of the channel, see FT_CHANTYPE
% sens.chanunit = Mx1 cell-array with the units of the channel signal, e.g. 'V', 'fT' or 'T/cm', see FT_CHANUNIT
%
% The following fields are optional
% sens.type = string with the MEG or EEG acquisition system, see FT_SENSTYPE
% sens.fid = structure with fiducial information
%
% Historical fields:
% - balance, chanori, chanpos, chantype, chanunit, coilori, coilpos,
% coordsys elecpos label, labelorg, tra, type, unit, see bug2513
%
% Revision history:
%
% (upcoming) The chantype and chanunit have become required fields. It is possible
% to convert the amplitude and distance units (e.g. from T to fT and from m to mm)
% and it is possible to express planar and axial gradiometer channels either in
% units of amplitude or in units of amplitude/distance (i.e. proper gradient).
% All numeric values are represented in double precision.
%
% (2011v2/latest) The chantype and chanunit have been added for MEG.
%
% (2011v1) To facilitate determining the position of channels (e.g. for plotting)
% in case of balanced MEG or bipolar EEG, an explicit distinction has been made
% between chanpos+chanori and coilpos+coilori (for MEG) and chanpos and elecpos
% (for EEG). The pnt and ori fields are removed
%
% (2010) Added support for bipolar or otherwise more complex linear combinations
% of EEG electrodes using sens.tra, similar to MEG.
%
% (2009) Noice reduction has been added for MEG systems in the balance field.
%
% (2006) The optional fields sens.type and sens.unit were added.
%
% (2003) The initial version was defined, which looked like this for EEG
% sens.pnt = Mx3 matrix with electrode positions
% sens.label = Mx1 cell-array with channel labels
% and like this for MEG
% sens.pnt = Nx3 matrix with coil positions
% sens.ori = Nx3 matrix with coil orientations
% sens.tra = MxN matrix to combine coils into channels
% sens.label = Mx1 cell-array with channel labels
%
% See also FT_READ_SENS, FT_SENSTYPE, FT_CHANTYPE, FT_APPLY_MONTAGE, CTF2GRAD, FIF2GRAD,
% BTI2GRAD, YOKOGAWA2GRAD, ITAB2GRAD
% Copyright (C) 2011-2013, Robert Oostenveld & Jan-Mathijs Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_datatype_sens.m 9529 2014-05-14 15:46:46Z roboos $
% undocumented options for the upcoming (2013?) format
% amplitude = string, can be 'T' or 'fT'
% distance = string, can be 'm', 'cm' or 'mm'
% scaling = string, can be 'amplitude' or 'amplitude/distance'
% these are for remembering the type on subsequent calls with the same input arguments
persistent previous_argin previous_argout
current_argin = [{sens} varargin];
if isequal(current_argin, previous_argin)
% don't do the whole cheking again, but return the previous output from cache
sens = previous_argout{1};
return
end
% get the optional input arguments, which should be specified as key-value pairs
version = ft_getopt(varargin, 'version', 'latest');
amplitude = ft_getopt(varargin, 'amplitude'); % should be 'V' 'uV' 'T' 'mT' 'uT' 'nT' 'pT' 'fT'
distance = ft_getopt(varargin, 'distance'); % should be 'm' 'dm' 'cm' 'mm'
scaling = ft_getopt(varargin, 'scaling'); % should be 'amplitude' or 'amplitude/distance', the default depends on the senstype
if ~isempty(amplitude) && ~any(strcmp(amplitude, {'V' 'uV' 'T' 'mT' 'uT' 'nT' 'pT' 'fT'}))
error('unsupported unit of amplitude "%s"', amplitude);
end
if ~isempty(distance) && ~any(strcmp(distance, {'m' 'dm' 'cm' 'mm'}))
error('unsupported unit of distance "%s"', distance);
end
if strcmp(version, 'latest')
version = '2011v2';
end
if isempty(sens)
return;
end
% this is needed further down
nchan = length(sens.label);
% there are many cases which deal with either eeg or meg
ismeg = ft_senstype(sens, 'meg');
switch version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case 'upcoming' % this is under development and expected to become the standard in 2013
% update it to the previous standard version
sens = ft_datatype_sens(sens, 'version', '2011v2');
% ensure that all numbers are represented in double precision
sens = ft_struct2double(sens);
% in version 2011v2 this was optional, now it is required
if ~isfield(sens, 'chantype') || all(strcmp(sens.chantype, 'unknown'))
sens.chantype = ft_chantype(sens);
end
% in version 2011v2 this was optional, now it is required
if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown'))
sens.chanunit = ft_chanunit(sens);
end
if ~isempty(distance)
% update the units of distance, this also updates the tra matrix
sens = ft_convert_units(sens, distance);
else
% determine the default, this may be needed to set the scaling
distance = sens.unit;
end
if ~isempty(amplitude) && isfield(sens, 'tra')
% update the tra matrix for the units of amplitude, this ensures that
% the leadfield values remain consistent with the units
for i=1:nchan
if ~isempty(regexp(sens.chanunit{i}, 'm$', 'once'))
% this channel is expressed as amplitude per distance
sens.tra(i,:) = sens.tra(i,:) * scalingfactor(sens.chanunit{i}, [amplitude '/' distance]);
sens.chanunit{i} = [amplitude '/' distance];
elseif ~isempty(regexp(sens.chanunit{i}, '[T|V]$', 'once'))
% this channel is expressed as amplitude
sens.tra(i,:) = sens.tra(i,:) * scalingfactor(sens.chanunit{i}, amplitude);
sens.chanunit{i} = amplitude;
else
error('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i);
end
end
else
% determine the default amplityde, this may be needed to set the scaling
if any(~cellfun(@isempty, regexp(sens.chanunit, '^T')))
% one of the channel units starts with T
amplitude = 'T';
elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^fT')))
% one of the channel units starts with fT
amplitude = 'fT';
elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^V')))
% one of the channel units starts with V
amplitude = 'V';
elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^uV')))
% one of the channel units starts with uV
amplitude = 'uV';
else
% this unknown amplitude will cause a problem if the scaling needs to be changed between amplitude and amplitude/distance
amplitude = 'unknown';
end
end
% perform some sanity checks
if ismeg
sel_m = ~cellfun(@isempty, regexp(sens.chanunit, '/m$'));
sel_dm = ~cellfun(@isempty, regexp(sens.chanunit, '/dm$'));
sel_cm = ~cellfun(@isempty, regexp(sens.chanunit, '/cm$'));
sel_mm = ~cellfun(@isempty, regexp(sens.chanunit, '/mm$'));
if strcmp(sens.unit, 'm') && (any(sel_dm) || any(sel_cm) || any(sel_mm))
error('inconsistent units in input gradiometer');
elseif strcmp(sens.unit, 'dm') && (any(sel_m) || any(sel_cm) || any(sel_mm))
error('inconsistent units in input gradiometer');
elseif strcmp(sens.unit, 'cm') && (any(sel_m) || any(sel_dm) || any(sel_mm))
error('inconsistent units in input gradiometer');
elseif strcmp(sens.unit, 'mm') && (any(sel_m) || any(sel_dm) || any(sel_cm))
error('inconsistent units in input gradiometer');
end
% the default should be amplitude/distance for neuromag and aplitude for all others
if isempty(scaling)
if ft_senstype(sens, 'neuromag')
scaling = 'amplitude/distance';
elseif ft_senstype(sens, 'yokogawa440')
warning('asuming that the default scaling should be amplitude rather than amplitude/distance');
scaling = 'amplitude';
else
scaling = 'amplitude';
end
end
% update the gradiometer scaling
if strcmp(scaling, 'amplitude')
for i=1:nchan
if strcmp(sens.chanunit{i}, [amplitude '/' distance])
% this channel is expressed as amplitude per distance
coil = find(abs(sens.tra(i,:))~=0);
if length(coil)~=2
error('unexpected number of coils contributing to channel %d', i);
end
baseline = norm(sens.coilpos(coil(1),:) - sens.coilpos(coil(2),:));
sens.tra(i,:) = sens.tra(i,:)*baseline; % scale with the baseline distance
sens.chanunit{i} = amplitude;
elseif strcmp(sens.chanunit{i}, amplitude)
% no conversion needed
else
error('unexpected channel unit "%s" in channel %d', i, sens.chanunit{i});
end % if
end % for
elseif strcmp(scaling, 'amplitude/distance')
for i=1:nchan
if strcmp(sens.chanunit{i}, amplitude)
% this channel is expressed as amplitude
coil = find(abs(sens.tra(i,:))~=0);
if length(coil)==1 || strcmp(sens.chantype{i}, 'megmag')
% this is a magnetometer channel, no conversion needed
continue
elseif length(coil)~=2
error('unexpected number of coils (%d) contributing to channel %s (%d)', length(coil), sens.label{i}, i);
end
baseline = norm(sens.coilpos(coil(1),:) - sens.coilpos(coil(2),:));
sens.tra(i,:) = sens.tra(i,:)/baseline; % scale with the baseline distance
sens.chanunit{i} = [amplitude '/' distance];
elseif strcmp(sens.chanunit{i}, [amplitude '/' distance])
% no conversion needed
else
error('unexpected channel unit "%s" in channel %d', i, sens.chanunit{i});
end % if
end % for
end % if strcmp scaling
else
sel_m = ~cellfun(@isempty, regexp(sens.chanunit, '/m$'));
sel_dm = ~cellfun(@isempty, regexp(sens.chanunit, '/dm$'));
sel_cm = ~cellfun(@isempty, regexp(sens.chanunit, '/cm$'));
sel_mm = ~cellfun(@isempty, regexp(sens.chanunit, '/mm$'));
if any(sel_m | sel_dm | sel_cm | sel_mm)
error('scaling of amplitude/distance has not been considered yet for EEG');
end
end % if iseeg or ismeg
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
case '2011v2'
if ~isempty(amplitude) || ~isempty(distance) || ~isempty(scaling)
warning('amplitude, distance and scaling are not supported for version "%s"', version);
end
% This speeds up subsequent calls to ft_senstype and channelposition.
% However, if it is not more precise than MEG or EEG, don't keep it in
% the output (see further down).
if ~isfield(sens, 'type')
sens.type = ft_senstype(sens);
end
if isfield(sens, 'pnt')
if ismeg
% sensor description is a MEG sensor-array, containing oriented coils
sens.coilpos = sens.pnt; sens = rmfield(sens, 'pnt');
sens.coilori = sens.ori; sens = rmfield(sens, 'ori');
else
% sensor description is something else, EEG/ECoG etc
sens.elecpos = sens.pnt; sens = rmfield(sens, 'pnt');
end
end
if ~isfield(sens, 'chanpos')
if ismeg
% sensor description is a MEG sensor-array, containing oriented coils
[chanpos, chanori, lab] = channelposition(sens);
% the channel order can be different in the two representations
[selsens, selpos] = match_str(sens.label, lab);
sens.chanpos = nan(length(sens.label), 3);
sens.chanori = nan(length(sens.label), 3);
% insert the determined position/orientation on the appropriate rows
sens.chanpos(selsens,:) = chanpos(selpos,:);
sens.chanori(selsens,:) = chanori(selpos,:);
if length(selsens)~=length(sens.label)
warning('cannot determine the position and orientation for all channels');
end
else
% sensor description is something else, EEG/ECoG etc
% note that chanori will be all NaNs
[chanpos, chanori, lab] = channelposition(sens);
% the channel order can be different in the two representations
[selsens, selpos] = match_str(sens.label, lab);
sens.chanpos = nan(length(sens.label), 3);
% insert the determined position/orientation on the appropriate rows
sens.chanpos(selsens,:) = chanpos(selpos,:);
if length(selsens)~=length(sens.label)
warning('cannot determine the position and orientation for all channels');
end
end
end
if ~isfield(sens, 'chantype') || all(strcmp(sens.chantype, 'unknown'))
if ismeg
sens.chantype = ft_chantype(sens);
else
% for EEG it is not required
end
end
if ~isfield(sens, 'unit')
% this should be done prior to calling ft_chanunit, since ft_chanunit uses this for planar neuromag channels
sens = ft_convert_units(sens);
end
if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown'))
if ismeg
sens.chanunit = ft_chanunit(sens);
else
% for EEG it is not required
end
end
if any(strcmp(sens.type, {'meg', 'eeg', 'magnetometer', 'electrode', 'unknown'}))
% this is not sufficiently informative, so better remove it
% see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=1806
sens = rmfield(sens, 'type');
end
if size(sens.chanpos,1)~=length(sens.label) || ...
isfield(sens, 'tra') && size(sens.tra,1)~=length(sens.label) || ...
isfield(sens, 'tra') && isfield(sens, 'elecpos') && size(sens.tra,2)~=size(sens.elecpos,1) || ...
isfield(sens, 'tra') && isfield(sens, 'coilpos') && size(sens.tra,2)~=size(sens.coilpos,1) || ...
isfield(sens, 'tra') && isfield(sens, 'coilori') && size(sens.tra,2)~=size(sens.coilori,1) || ...
isfield(sens, 'chanpos') && size(sens.chanpos,1)~=length(sens.label) || ...
isfield(sens, 'chanori') && size(sens.chanori,1)~=length(sens.label)
error('inconsistent number of channels in sensor description');
end
if ismeg
% ensure that the magnetometer/gradiometer balancing is specified
if ~isfield(sens, 'balance') || ~isfield(sens.balance, 'current')
sens.balance.current = 'none';
end
% try to add the chantype and chanunit to the CTF G1BR montage
if isfield(sens, 'balance') && isfield(sens.balance, 'G1BR') && ~isfield(sens.balance.G1BR, 'chantype')
sens.balance.G1BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G1BR.labelorg));
sens.balance.G1BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G1BR.labelorg));
sens.balance.G1BR.chantypenew = repmat({'unknown'}, size(sens.balance.G1BR.labelnew));
sens.balance.G1BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G1BR.labelnew));
% the synthetic gradient montage does not fundamentally change the chantype or chanunit
[sel1, sel2] = match_str(sens.balance.G1BR.labelorg, sens.label);
sens.balance.G1BR.chantypeorg(sel1) = sens.chantype(sel2);
sens.balance.G1BR.chanunitorg(sel1) = sens.chanunit(sel2);
[sel1, sel2] = match_str(sens.balance.G1BR.labelnew, sens.label);
sens.balance.G1BR.chantypenew(sel1) = sens.chantype(sel2);
sens.balance.G1BR.chanunitnew(sel1) = sens.chanunit(sel2);
end
% idem for G2BR
if isfield(sens, 'balance') && isfield(sens.balance, 'G2BR') && ~isfield(sens.balance.G2BR, 'chantype')
sens.balance.G2BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G2BR.labelorg));
sens.balance.G2BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G2BR.labelorg));
sens.balance.G2BR.chantypenew = repmat({'unknown'}, size(sens.balance.G2BR.labelnew));
sens.balance.G2BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G2BR.labelnew));
% the synthetic gradient montage does not fundamentally change the chantype or chanunit
[sel1, sel2] = match_str(sens.balance.G2BR.labelorg, sens.label);
sens.balance.G2BR.chantypeorg(sel1) = sens.chantype(sel2);
sens.balance.G2BR.chanunitorg(sel1) = sens.chanunit(sel2);
[sel1, sel2] = match_str(sens.balance.G2BR.labelnew, sens.label);
sens.balance.G2BR.chantypenew(sel1) = sens.chantype(sel2);
sens.balance.G2BR.chanunitnew(sel1) = sens.chanunit(sel2);
end
% idem for G3BR
if isfield(sens, 'balance') && isfield(sens.balance, 'G3BR') && ~isfield(sens.balance.G3BR, 'chantype')
sens.balance.G3BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G3BR.labelorg));
sens.balance.G3BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G3BR.labelorg));
sens.balance.G3BR.chantypenew = repmat({'unknown'}, size(sens.balance.G3BR.labelnew));
sens.balance.G3BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G3BR.labelnew));
% the synthetic gradient montage does not fundamentally change the chantype or chanunit
[sel1, sel2] = match_str(sens.balance.G3BR.labelorg, sens.label);
sens.balance.G3BR.chantypeorg(sel1) = sens.chantype(sel2);
sens.balance.G3BR.chanunitorg(sel1) = sens.chanunit(sel2);
[sel1, sel2] = match_str(sens.balance.G3BR.labelnew, sens.label);
sens.balance.G3BR.chantypenew(sel1) = sens.chantype(sel2);
sens.balance.G3BR.chanunitnew(sel1) = sens.chanunit(sel2);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
otherwise
error('converting to version %s is not supported', version);
end % switch
% this makes the display with the "disp" command look better
sens = sortfieldnames(sens);
% remember the current input and output arguments, so that they can be
% reused on a subsequent call in case the same input argument is given
current_argout = {sens};
previous_argin = current_argin;
previous_argout = current_argout;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function b = sortfieldnames(a)
fn = sort(fieldnames(a));
for i=1:numel(fn)
b.(fn{i}) = a.(fn{i});
end
|
github
|
ZijingMao/baselineeegtest-master
|
avw_img_read.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/avw_img_read.m
| 29,199 |
utf_8
|
be1e5b74cfdcf9acc49582896e9fadec
|
function [ avw, machine ] = avw_img_read(fileprefix,IMGorient,machine,verbose)
% avw_img_read - read Analyze format data image (*.img)
%
% [ avw, machine ] = avw_img_read(fileprefix,[orient],[machine],[verbose])
%
% fileprefix - a string, the filename without the .img extension
%
% orient - read a specified orientation, integer values:
%
% '', use header history orient field
% 0, transverse unflipped (LAS*)
% 1, coronal unflipped (LA*S)
% 2, sagittal unflipped (L*AS)
% 3, transverse flipped (LPS*)
% 4, coronal flipped (LA*I)
% 5, sagittal flipped (L*AI)
%
% where * follows the slice dimension and letters indicate +XYZ
% orientations (L left, R right, A anterior, P posterior,
% I inferior, & S superior).
%
% Some files may contain data in the 3-5 orientations, but this
% is unlikely. For more information about orientation, see the
% documentation at the end of this .m file. See also the
% AVW_FLIP function for orthogonal reorientation.
%
% machine - a string, see machineformat in fread for details.
% The default here is 'ieee-le' but the routine
% will automatically switch between little and big
% endian to read any such Analyze header. It
% reports the appropriate machine format and can
% return the machine value.
%
% verbose - the default is to output processing information to the command
% window. If verbose = 0, this will not happen.
%
% Returned values:
%
% avw.hdr - a struct with image data parameters.
% avw.img - a 3D matrix of image data (double precision).
%
% A returned 3D matrix will correspond with the
% default ANALYZE coordinate system, which
% is Left-handed:
%
% X-Y plane is Transverse
% X-Z plane is Coronal
% Y-Z plane is Sagittal
%
% X axis runs from patient right (low X) to patient Left (high X)
% Y axis runs from posterior (low Y) to Anterior (high Y)
% Z axis runs from inferior (low Z) to Superior (high Z)
%
% The function can read a 4D Analyze volume, but only if it is in the
% axial unflipped orientation.
%
% See also: avw_hdr_read (called by this function),
% avw_view, avw_write, avw_img_write, avw_flip
%
% $Revision: 7123 $ $Date: 2009/01/14 09:24:45 $
% Licence: GNU GPL, no express or implied warranties
% History: 05/2002, [email protected]
% The Analyze format is copyright
% (c) Copyright, 1986-1995
% Biomedical Imaging Resource, Mayo Foundation
% 01/2003, [email protected]
% - adapted for matlab v5
% - revised all orientation information and handling
% after seeking further advice from AnalyzeDirect.com
% 03/2003, [email protected]
% - adapted for -ve pixdim values (non standard Analyze)
% 07/2004, [email protected], added ability to
% read volumes with dimensionality greather than 3.
% a >3D volume cannot be flipped. and error is thrown if a volume of
% greater than 3D (ie, avw.hdr.dime.dim(1) > 3) requests a data flip
% (ie, avw.hdr.hist.orient ~= 0 ). i pulled the transfer of read-in
% data (tmp) to avw.img out of any looping mechanism. looping is not
% necessary as the data is already in its correct orientation. using
% 'reshape' rather than looping should be faster but, more importantly,
% it allows the reading in of N-D volumes. See lines 270-280.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~exist('IMGorient','var'), IMGorient = ''; end
if ~exist('machine','var'), machine = 'ieee-le'; end
if ~exist('verbose','var'), verbose = 1; end
if isempty(IMGorient), IMGorient = ''; end
if isempty(machine), machine = 'ieee-le'; end
if isempty(verbose), verbose = 1; end
if ~exist('fileprefix','var'),
msg = sprintf('...no input fileprefix - see help avw_img_read\n\n');
error(msg);
end
if findstr('.hdr',fileprefix),
fileprefix = strrep(fileprefix,'.hdr','');
end
if findstr('.img',fileprefix),
fileprefix = strrep(fileprefix,'.img','');
end
% MAIN
% Read the file header
[ avw, machine ] = avw_hdr_read(fileprefix,machine,verbose);
avw = read_image(avw,IMGorient,machine,verbose);
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ avw ] = read_image(avw,IMGorient,machine,verbose)
fid = fopen(sprintf('%s.img',avw.fileprefix),'r',machine);
if fid < 0,
msg = sprintf('...cannot open file %s.img\n\n',avw.fileprefix);
error(msg);
end
if verbose,
ver = '[$Revision: 7123 $]';
fprintf('\nAVW_IMG_READ [v%s]\n',ver(12:16)); tic;
end
% short int bitpix; /* Number of bits per pixel; 1, 8, 16, 32, or 64. */
% short int datatype /* Datatype for this image set */
% /*Acceptable values for datatype are*/
% #define DT_NONE 0
% #define DT_UNKNOWN 0 /*Unknown data type*/
% #define DT_BINARY 1 /*Binary ( 1 bit per voxel)*/
% #define DT_UNSIGNED_CHAR 2 /*Unsigned character ( 8 bits per voxel)*/
% #define DT_SIGNED_SHORT 4 /*Signed short (16 bits per voxel)*/
% #define DT_SIGNED_INT 8 /*Signed integer (32 bits per voxel)*/
% #define DT_FLOAT 16 /*Floating point (32 bits per voxel)*/
% #define DT_COMPLEX 32 /*Complex (64 bits per voxel; 2 floating point numbers)/*
% #define DT_DOUBLE 64 /*Double precision (64 bits per voxel)*/
% #define DT_RGB 128 /*A Red-Green-Blue datatype*/
% #define DT_ALL 255 /*Undocumented*/
switch double(avw.hdr.dime.bitpix),
case 1, precision = 'bit1';
case 8, precision = 'uchar';
case 16, precision = 'int16';
case 32,
if isequal(avw.hdr.dime.datatype, 8), precision = 'int32';
else precision = 'single';
end
case 64, precision = 'double';
otherwise,
precision = 'uchar';
if verbose, fprintf('...precision undefined in header, using ''uchar''\n'); end
end
% read the whole .img file into matlab (faster)
if verbose,
fprintf('...reading %s Analyze %s image format.\n',machine,precision);
end
fseek(fid,0,'bof');
% adjust for matlab version
ver = version;
ver = str2num(ver(1));
if ver < 6,
tmp = fread(fid,inf,sprintf('%s',precision));
else,
tmp = fread(fid,inf,sprintf('%s=>double',precision));
end
fclose(fid);
% Update the global min and max values
avw.hdr.dime.glmax = max(double(tmp));
avw.hdr.dime.glmin = min(double(tmp));
%---------------------------------------------------------------
% Now partition the img data into xyz
% --- first figure out the size of the image
% short int dim[ ]; /* Array of the image dimensions */
%
% dim[0] Number of dimensions in database; usually 4.
% dim[1] Image X dimension; number of pixels in an image row.
% dim[2] Image Y dimension; number of pixel rows in slice.
% dim[3] Volume Z dimension; number of slices in a volume.
% dim[4] Time points; number of volumes in database.
PixelDim = double(avw.hdr.dime.dim(2));
RowDim = double(avw.hdr.dime.dim(3));
SliceDim = double(avw.hdr.dime.dim(4));
TimeDim = double(avw.hdr.dime.dim(5));
PixelSz = double(avw.hdr.dime.pixdim(2));
RowSz = double(avw.hdr.dime.pixdim(3));
SliceSz = double(avw.hdr.dime.pixdim(4));
TimeSz = double(avw.hdr.dime.pixdim(5));
% ---- NON STANDARD ANALYZE...
% Some Analyze files have been found to set -ve pixdim values, eg
% the MNI template avg152T1_brain in the FSL etc/standard folder,
% perhaps to indicate flipped orientation? If so, this code below
% will NOT handle the flip correctly!
if PixelSz < 0,
warning('X pixdim < 0 !!! resetting to abs(avw.hdr.dime.pixdim(2))');
PixelSz = abs(PixelSz);
avw.hdr.dime.pixdim(2) = single(PixelSz);
end
if RowSz < 0,
warning('Y pixdim < 0 !!! resetting to abs(avw.hdr.dime.pixdim(3))');
RowSz = abs(RowSz);
avw.hdr.dime.pixdim(3) = single(RowSz);
end
if SliceSz < 0,
warning('Z pixdim < 0 !!! resetting to abs(avw.hdr.dime.pixdim(4))');
SliceSz = abs(SliceSz);
avw.hdr.dime.pixdim(4) = single(SliceSz);
end
% ---- END OF NON STANDARD ANALYZE
% --- check the orientation specification and arrange img accordingly
if ~isempty(IMGorient),
if ischar(IMGorient),
avw.hdr.hist.orient = uint8(str2num(IMGorient));
else
avw.hdr.hist.orient = uint8(IMGorient);
end
end,
if isempty(avw.hdr.hist.orient),
msg = [ '...unspecified avw.hdr.hist.orient, using default 0\n',...
' (check image and try explicit IMGorient option).\n'];
fprintf(msg);
avw.hdr.hist.orient = uint8(0);
end
% --- check if the orientation is to be flipped for a volume with more
% --- than 3 dimensions. this logic is currently unsupported so throw
% --- an error. volumes of any dimensionality may be read in *only* as
% --- unflipped, ie, avw.hdr.hist.orient == 0
if ( TimeDim > 1 ) && (avw.hdr.hist.orient ~= 0 ),
msg = [ 'ERROR: This volume has more than 3 dimensions *and* ', ...
'requires flipping the data. Flipping is not supported ', ...
'for volumes with dimensionality greater than 3. Set ', ...
'avw.hdr.hist.orient = 0 and flip your volume after ', ...
'calling this function' ];
msg = sprintf( '%s (%s).', msg, mfilename );
error( msg );
end
switch double(avw.hdr.hist.orient),
case 0, % transverse unflipped
% orient = 0: The primary orientation of the data on disk is in the
% transverse plane relative to the object scanned. Most commonly, the fastest
% moving index through the voxels that are part of this transverse image would
% span the right-left extent of the structure imaged, with the next fastest
% moving index spanning the posterior-anterior extent of the structure. This
% 'orient' flag would indicate to Analyze that this data should be placed in
% the X-Y plane of the 3D Analyze Coordinate System, with the Z dimension
% being the slice direction.
% For the 'transverse unflipped' type, the voxels are stored with
% Pixels in 'x' axis (varies fastest) - from patient right to left
% Rows in 'y' axis - from patient posterior to anterior
% Slices in 'z' axis - from patient inferior to superior
if verbose, fprintf('...reading axial unflipped orientation\n'); end
% -- This code will handle nD files
dims = double( avw.hdr.dime.dim(2:end) );
% replace dimensions of 0 with 1 to be used in reshape
idx = find( dims == 0 );
dims( idx ) = 1;
avw.img = reshape( tmp, dims );
% -- The code above replaces this
% avw.img = zeros(PixelDim,RowDim,SliceDim);
%
% n = 1;
% x = 1:PixelDim;
% for z = 1:SliceDim,
% for y = 1:RowDim,
% % load Y row of X values into Z slice avw.img
% avw.img(x,y,z) = tmp(n:n+(PixelDim-1));
% n = n + PixelDim;
% end
% end
% no need to rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim
case 1, % coronal unflipped
% orient = 1: The primary orientation of the data on disk is in the coronal
% plane relative to the object scanned. Most commonly, the fastest moving
% index through the voxels that are part of this coronal image would span the
% right-left extent of the structure imaged, with the next fastest moving
% index spanning the inferior-superior extent of the structure. This 'orient'
% flag would indicate to Analyze that this data should be placed in the X-Z
% plane of the 3D Analyze Coordinate System, with the Y dimension being the
% slice direction.
% For the 'coronal unflipped' type, the voxels are stored with
% Pixels in 'x' axis (varies fastest) - from patient right to left
% Rows in 'z' axis - from patient inferior to superior
% Slices in 'y' axis - from patient posterior to anterior
if verbose, fprintf('...reading coronal unflipped orientation\n'); end
avw.img = zeros(PixelDim,SliceDim,RowDim);
n = 1;
x = 1:PixelDim;
for y = 1:SliceDim,
for z = 1:RowDim,
% load Z row of X values into Y slice avw.img
avw.img(x,y,z) = tmp(n:n+(PixelDim-1));
n = n + PixelDim;
end
end
% rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim
avw.hdr.dime.dim(2:4) = int16([PixelDim,SliceDim,RowDim]);
avw.hdr.dime.pixdim(2:4) = single([PixelSz,SliceSz,RowSz]);
case 2, % sagittal unflipped
% orient = 2: The primary orientation of the data on disk is in the sagittal
% plane relative to the object scanned. Most commonly, the fastest moving
% index through the voxels that are part of this sagittal image would span the
% posterior-anterior extent of the structure imaged, with the next fastest
% moving index spanning the inferior-superior extent of the structure. This
% 'orient' flag would indicate to Analyze that this data should be placed in
% the Y-Z plane of the 3D Analyze Coordinate System, with the X dimension
% being the slice direction.
% For the 'sagittal unflipped' type, the voxels are stored with
% Pixels in 'y' axis (varies fastest) - from patient posterior to anterior
% Rows in 'z' axis - from patient inferior to superior
% Slices in 'x' axis - from patient right to left
if verbose, fprintf('...reading sagittal unflipped orientation\n'); end
avw.img = zeros(SliceDim,PixelDim,RowDim);
n = 1;
y = 1:PixelDim; % posterior to anterior (fastest)
for x = 1:SliceDim, % right to left (slowest)
for z = 1:RowDim, % inferior to superior
% load Z row of Y values into X slice avw.img
avw.img(x,y,z) = tmp(n:n+(PixelDim-1));
n = n + PixelDim;
end
end
% rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim
avw.hdr.dime.dim(2:4) = int16([SliceDim,PixelDim,RowDim]);
avw.hdr.dime.pixdim(2:4) = single([SliceSz,PixelSz,RowSz]);
%--------------------------------------------------------------------------------
% Orient values 3-5 have the second index reversed in order, essentially
% 'flipping' the images relative to what would most likely become the vertical
% axis of the displayed image.
%--------------------------------------------------------------------------------
case 3, % transverse/axial flipped
% orient = 3: The primary orientation of the data on disk is in the
% transverse plane relative to the object scanned. Most commonly, the fastest
% moving index through the voxels that are part of this transverse image would
% span the right-left extent of the structure imaged, with the next fastest
% moving index spanning the *anterior-posterior* extent of the structure. This
% 'orient' flag would indicate to Analyze that this data should be placed in
% the X-Y plane of the 3D Analyze Coordinate System, with the Z dimension
% being the slice direction.
% For the 'transverse flipped' type, the voxels are stored with
% Pixels in 'x' axis (varies fastest) - from patient right to Left
% Rows in 'y' axis - from patient anterior to Posterior *
% Slices in 'z' axis - from patient inferior to Superior
if verbose, fprintf('...reading axial flipped (+Y from Anterior to Posterior)\n'); end
avw.img = zeros(PixelDim,RowDim,SliceDim);
n = 1;
x = 1:PixelDim;
for z = 1:SliceDim,
for y = RowDim:-1:1, % flip in Y, read A2P file into P2A 3D matrix
% load a flipped Y row of X values into Z slice avw.img
avw.img(x,y,z) = tmp(n:n+(PixelDim-1));
n = n + PixelDim;
end
end
% no need to rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim
case 4, % coronal flipped
% orient = 4: The primary orientation of the data on disk is in the coronal
% plane relative to the object scanned. Most commonly, the fastest moving
% index through the voxels that are part of this coronal image would span the
% right-left extent of the structure imaged, with the next fastest moving
% index spanning the *superior-inferior* extent of the structure. This 'orient'
% flag would indicate to Analyze that this data should be placed in the X-Z
% plane of the 3D Analyze Coordinate System, with the Y dimension being the
% slice direction.
% For the 'coronal flipped' type, the voxels are stored with
% Pixels in 'x' axis (varies fastest) - from patient right to Left
% Rows in 'z' axis - from patient superior to Inferior*
% Slices in 'y' axis - from patient posterior to Anterior
if verbose, fprintf('...reading coronal flipped (+Z from Superior to Inferior)\n'); end
avw.img = zeros(PixelDim,SliceDim,RowDim);
n = 1;
x = 1:PixelDim;
for y = 1:SliceDim,
for z = RowDim:-1:1, % flip in Z, read S2I file into I2S 3D matrix
% load a flipped Z row of X values into Y slice avw.img
avw.img(x,y,z) = tmp(n:n+(PixelDim-1));
n = n + PixelDim;
end
end
% rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim
avw.hdr.dime.dim(2:4) = int16([PixelDim,SliceDim,RowDim]);
avw.hdr.dime.pixdim(2:4) = single([PixelSz,SliceSz,RowSz]);
case 5, % sagittal flipped
% orient = 5: The primary orientation of the data on disk is in the sagittal
% plane relative to the object scanned. Most commonly, the fastest moving
% index through the voxels that are part of this sagittal image would span the
% posterior-anterior extent of the structure imaged, with the next fastest
% moving index spanning the *superior-inferior* extent of the structure. This
% 'orient' flag would indicate to Analyze that this data should be placed in
% the Y-Z plane of the 3D Analyze Coordinate System, with the X dimension
% being the slice direction.
% For the 'sagittal flipped' type, the voxels are stored with
% Pixels in 'y' axis (varies fastest) - from patient posterior to Anterior
% Rows in 'z' axis - from patient superior to Inferior*
% Slices in 'x' axis - from patient right to Left
if verbose, fprintf('...reading sagittal flipped (+Z from Superior to Inferior)\n'); end
avw.img = zeros(SliceDim,PixelDim,RowDim);
n = 1;
y = 1:PixelDim;
for x = 1:SliceDim,
for z = RowDim:-1:1, % flip in Z, read S2I file into I2S 3D matrix
% load a flipped Z row of Y values into X slice avw.img
avw.img(x,y,z) = tmp(n:n+(PixelDim-1));
n = n + PixelDim;
end
end
% rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim
avw.hdr.dime.dim(2:4) = int16([SliceDim,PixelDim,RowDim]);
avw.hdr.dime.pixdim(2:4) = single([SliceSz,PixelSz,RowSz]);
otherwise
error('unknown value in avw.hdr.hist.orient, try explicit IMGorient option.');
end
if verbose, t=toc; fprintf('...done (%5.2f sec).\n\n',t); end
return
% This function attempts to read the orientation of the
% Analyze file according to the hdr.hist.orient field of the
% header. Unfortunately, this field is optional and not
% all programs will set it correctly, so there is no guarantee,
% that the data loaded will be correctly oriented. If necessary,
% experiment with the 'orient' option to read the .img
% data into the 3D matrix of avw.img as preferred.
%
% (Conventions gathered from e-mail with [email protected])
%
% 0 transverse unflipped
% X direction first, progressing from patient right to left,
% Y direction second, progressing from patient posterior to anterior,
% Z direction third, progressing from patient inferior to superior.
% 1 coronal unflipped
% X direction first, progressing from patient right to left,
% Z direction second, progressing from patient inferior to superior,
% Y direction third, progressing from patient posterior to anterior.
% 2 sagittal unflipped
% Y direction first, progressing from patient posterior to anterior,
% Z direction second, progressing from patient inferior to superior,
% X direction third, progressing from patient right to left.
% 3 transverse flipped
% X direction first, progressing from patient right to left,
% Y direction second, progressing from patient anterior to posterior,
% Z direction third, progressing from patient inferior to superior.
% 4 coronal flipped
% X direction first, progressing from patient right to left,
% Z direction second, progressing from patient superior to inferior,
% Y direction third, progressing from patient posterior to anterior.
% 5 sagittal flipped
% Y direction first, progressing from patient posterior to anterior,
% Z direction second, progressing from patient superior to inferior,
% X direction third, progressing from patient right to left.
%----------------------------------------------------------------------------
% From ANALYZE documentation...
%
% The ANALYZE coordinate system has an origin in the lower left
% corner. That is, with the subject lying supine, the coordinate
% origin is on the right side of the body (x), at the back (y),
% and at the feet (z). This means that:
%
% +X increases from right (R) to left (L)
% +Y increases from the back (posterior,P) to the front (anterior, A)
% +Z increases from the feet (inferior,I) to the head (superior, S)
%
% The LAS orientation is the radiological convention, where patient
% left is on the image right. The alternative neurological
% convention is RAS (also Talairach convention).
%
% A major advantage of the Analzye origin convention is that the
% coordinate origin of each orthogonal orientation (transverse,
% coronal, and sagittal) lies in the lower left corner of the
% slice as it is displayed.
%
% Orthogonal slices are numbered from one to the number of slices
% in that orientation. For example, a volume (x, y, z) dimensioned
% 128, 256, 48 has:
%
% 128 sagittal slices numbered 1 through 128 (X)
% 256 coronal slices numbered 1 through 256 (Y)
% 48 transverse slices numbered 1 through 48 (Z)
%
% Pixel coordinates are made with reference to the slice numbers from
% which the pixels come. Thus, the first pixel in the volume is
% referenced p(1,1,1) and not at p(0,0,0).
%
% Transverse slices are in the XY plane (also known as axial slices).
% Sagittal slices are in the ZY plane.
% Coronal slices are in the ZX plane.
%
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
% E-mail from [email protected]
%
% The 'orient' field in the data_history structure specifies the primary
% orientation of the data as it is stored in the file on disk. This usually
% corresponds to the orientation in the plane of acquisition, given that this
% would correspond to the order in which the data is written to disk by the
% scanner or other software application. As you know, this field will contain
% the values:
%
% orient = 0 transverse unflipped
% 1 coronal unflipped
% 2 sagittal unflipped
% 3 transverse flipped
% 4 coronal flipped
% 5 sagittal flipped
%
% It would be vary rare that you would ever encounter any old Analyze 7.5
% files that contain values of 'orient' which indicate that the data has been
% 'flipped'. The 'flipped flag' values were really only used internal to
% Analyze to precondition data for fast display in the Movie module, where the
% images were actually flipped vertically in order to accommodate the raster
% paint order on older graphics devices. The only cases you will encounter
% will have values of 0, 1, or 2.
%
% As mentioned, the 'orient' flag only specifies the primary orientation of
% data as stored in the disk file itself. It has nothing to do with the
% representation of the data in the 3D Analyze coordinate system, which always
% has a fixed representation to the data. The meaning of the 'orient' values
% should be interpreted as follows:
%
% orient = 0: The primary orientation of the data on disk is in the
% transverse plane relative to the object scanned. Most commonly, the fastest
% moving index through the voxels that are part of this transverse image would
% span the right-left extent of the structure imaged, with the next fastest
% moving index spanning the posterior-anterior extent of the structure. This
% 'orient' flag would indicate to Analyze that this data should be placed in
% the X-Y plane of the 3D Analyze Coordinate System, with the Z dimension
% being the slice direction.
%
% orient = 1: The primary orientation of the data on disk is in the coronal
% plane relative to the object scanned. Most commonly, the fastest moving
% index through the voxels that are part of this coronal image would span the
% right-left extent of the structure imaged, with the next fastest moving
% index spanning the inferior-superior extent of the structure. This 'orient'
% flag would indicate to Analyze that this data should be placed in the X-Z
% plane of the 3D Analyze Coordinate System, with the Y dimension being the
% slice direction.
%
% orient = 2: The primary orientation of the data on disk is in the sagittal
% plane relative to the object scanned. Most commonly, the fastest moving
% index through the voxels that are part of this sagittal image would span the
% posterior-anterior extent of the structure imaged, with the next fastest
% moving index spanning the inferior-superior extent of the structure. This
% 'orient' flag would indicate to Analyze that this data should be placed in
% the Y-Z plane of the 3D Analyze Coordinate System, with the X dimension
% being the slice direction.
%
% Orient values 3-5 have the second index reversed in order, essentially
% 'flipping' the images relative to what would most likely become the vertical
% axis of the displayed image.
%
% Hopefully you understand the difference between the indication this 'orient'
% flag has relative to data stored on disk and the full 3D Analyze Coordinate
% System for data that is managed as a volume image. As mentioned previously,
% the orientation of patient anatomy in the 3D Analyze Coordinate System has a
% fixed orientation relative to each of the orthogonal axes. This orientation
% is completely described in the information that is attached, but the basics
% are:
%
% Left-handed coordinate system
%
% X-Y plane is Transverse
% X-Z plane is Coronal
% Y-Z plane is Sagittal
%
% X axis runs from patient right (low X) to patient left (high X)
% Y axis runs from posterior (low Y) to anterior (high Y)
% Z axis runs from inferior (low Z) to superior (high Z)
%
%----------------------------------------------------------------------------
%----------------------------------------------------------------------------
% SPM2 NOTES from spm2 webpage: One thing to watch out for is the image
% orientation. The proper Analyze format uses a left-handed co-ordinate
% system, whereas Talairach uses a right-handed one. In SPM99, images were
% flipped at the spatial normalisation stage (from one co-ordinate system
% to the other). In SPM2b, a different approach is used, so that either a
% left- or right-handed co-ordinate system is used throughout. The SPM2b
% program is told about the handedness that the images are stored with by
% the spm_flip_analyze_images.m function and the defaults.analyze.flip
% parameter that is specified in the spm_defaults.m file. These files are
% intended to be customised for each site. If you previously used SPM99
% and your images were flipped during spatial normalisation, then set
% defaults.analyze.flip=1. If no flipping took place, then set
% defaults.analyze.flip=0. Check that when using the Display facility
% (possibly after specifying some rigid-body rotations) that:
%
% The top-left image is coronal with the top (superior) of the head displayed
% at the top and the left shown on the left. This is as if the subject is viewed
% from behind.
%
% The bottom-left image is axial with the front (anterior) of the head at the
% top and the left shown on the left. This is as if the subject is viewed from above.
%
% The top-right image is sagittal with the front (anterior) of the head at the
% left and the top of the head shown at the top. This is as if the subject is
% viewed from the left.
%----------------------------------------------------------------------------
|
github
|
ZijingMao/baselineeegtest-master
|
read_yokogawa_event.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_yokogawa_event.m
| 7,112 |
utf_8
|
a70ad744018275d54a5de06fbcc9d1ff
|
function [event] = read_yokogawa_event(filename, varargin)
% READ_YOKOGAWA_EVENT reads event information from continuous,
% epoched or averaged MEG data that has been generated by the Yokogawa
% MEG system and software and allows those events to be used in
% combination with FieldTrip.
%
% Use as
% [event] = read_yokogawa_event(filename)
%
% See also READ_YOKOGAWA_HEADER, READ_YOKOGAWA_DATA
% Copyright (C) 2005, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: read_yokogawa_event.m 7123 2012-12-06 21:21:38Z roboos $
event = [];
handles = definehandles;
% get the options, the default is set below
trigindx = ft_getopt(varargin, 'trigindx');
threshold = ft_getopt(varargin, 'threshold');
detectflank = ft_getopt(varargin, 'detectflank');
% ensure that the required toolbox is on the path
if ft_hastoolbox('yokogawa_meg_reader');
% read the dataset header
hdr = read_yokogawa_header_new(filename);
ch_info = hdr.orig.channel_info.channel;
type = [ch_info.type];
% determine the trigger channels (if not specified by the user)
if isempty(trigindx)
trigindx = find(type==handles.TriggerChannel);
end
% Use the MEG Reader documentation if more detailed support is
% required.
if hdr.orig.acq_type==handles.AcqTypeEvokedRaw
% read the trigger id from all trials
event = getYkgwHdrEvent(filename);
% use the standard FieldTrip header for trial events
% make an event for each trial as defined in the header
for i=1:hdr.nTrials
event(end+1).type = 'trial';
event(end ).sample = (i-1)*hdr.nSamples + 1;
event(end ).offset = -hdr.nSamplesPre;
event(end ).duration = hdr.nSamples;
if ~isempty(value)
event(end ).value = event(i).code;
end
end
% Use the MEG Reader documentation if more detailed support is required.
elseif hdr.orig.acq_type==handles.AcqTypeEvokedAve
% make an event for the average
event(1).type = 'average';
event(1).sample = 1;
event(1).offset = -hdr.nSamplesPre;
event(1).duration = hdr.nSamples;
elseif hdr.orig.acq_type==handles.AcqTypeContinuousRaw
% the data structure does not contain events, but flank detection on the trigger channel might reveal them
% this is done below for all formats
end
elseif ft_hastoolbox('yokogawa');
% read the dataset header
hdr = read_yokogawa_header(filename);
% determine the trigger channels (if not specified by the user)
if isempty(trigindx)
trigindx = find(hdr.orig.channel_info(:,2)==handles.TriggerChannel);
end
if hdr.orig.acq_type==handles.AcqTypeEvokedRaw
% read the trigger id from all trials
fid = fopen(filename, 'r');
value = GetMeg160TriggerEventM(fid);
fclose(fid);
% use the standard FieldTrip header for trial events
% make an event for each trial as defined in the header
for i=1:hdr.nTrials
event(end+1).type = 'trial';
event(end ).sample = (i-1)*hdr.nSamples + 1;
event(end ).offset = -hdr.nSamplesPre;
event(end ).duration = hdr.nSamples;
if ~isempty(value)
event(end ).value = value(i);
end
end
elseif hdr.orig.acq_type==handles.AcqTypeEvokedAve
% make an event for the average
event(1).type = 'average';
event(1).sample = 1;
event(1).offset = -hdr.nSamplesPre;
event(1).duration = hdr.nSamples;
elseif hdr.orig.acq_type==handles.AcqTypeContinuousRaw
% the data structure does not contain events, but flank detection on the trigger channel might reveal them
% this is done below for all formats
end
else
error('cannot determine, whether Yokogawa toolbox is present');
end
% read the trigger channels and detect the flanks
if ~isempty(trigindx)
trigger = read_trigger(filename, 'header', hdr, 'denoise', false, 'chanindx', trigindx, 'detectflank', detectflank, 'threshold', threshold);
% combine the triggers and the other events
event = appendevent(event, trigger);
end
if isempty(event)
warning('no triggers were detected, please specify the "trigindx" option');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this defines some usefull constants
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles = definehandles;
handles.output = [];
handles.sqd_load_flag = false;
handles.mri_load_flag = false;
handles.NullChannel = 0;
handles.MagnetoMeter = 1;
handles.AxialGradioMeter = 2;
handles.PlannerGradioMeter = 3;
handles.RefferenceChannelMark = hex2dec('0100');
handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter );
handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter );
handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter );
handles.TriggerChannel = -1;
handles.EegChannel = -2;
handles.EcgChannel = -3;
handles.EtcChannel = -4;
handles.NonMegChannelNameLength = 32;
handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length
handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter
handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length
handles.AcqTypeContinuousRaw = 1;
handles.AcqTypeEvokedAve = 2;
handles.AcqTypeEvokedRaw = 3;
handles.sqd = [];
handles.sqd.selected_start = [];
handles.sqd.selected_end = [];
handles.sqd.axialgradiometer_ch_no = [];
handles.sqd.axialgradiometer_ch_info = [];
handles.sqd.axialgradiometer_data = [];
handles.sqd.plannergradiometer_ch_no = [];
handles.sqd.plannergradiometer_ch_info = [];
handles.sqd.plannergradiometer_data = [];
handles.sqd.eegchannel_ch_no = [];
handles.sqd.eegchannel_data = [];
handles.sqd.nullchannel_ch_no = [];
handles.sqd.nullchannel_data = [];
handles.sqd.selected_time = [];
handles.sqd.sample_rate = [];
handles.sqd.sample_count = [];
handles.sqd.pretrigger_length = [];
handles.sqd.matching_info = [];
handles.sqd.source_info = [];
handles.sqd.mri_info = [];
handles.mri = [];
|
github
|
ZijingMao/baselineeegtest-master
|
read_4d_hdr.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_4d_hdr.m
| 26,578 |
utf_8
|
0c1de85be0ce9fbe0a604100894eb861
|
function [header] = read_4d_hdr(datafile, configfile)
% hdr=READ_4D_HDR(datafile, configfile)
% Collects the required Fieldtrip header data from the data file 'filename'
% and the associated 'config' file for that data.
%
% Adapted from the MSI>>Matlab code written by Eugene Kronberg
% Copyright (C) 2008-2009, Centre for Cognitive Neuroimaging, Glasgow, Gavin Paterson & J.M.Schoffelen
% Copyright (C) 2010-2011, Donders Institute for Brain, Cognition and Behavior, J.M.Schoffelen
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: read_4d_hdr.m 7593 2013-03-05 16:09:24Z jansch $
%read header
if nargin ~= 2
[path, file, ext] = fileparts(datafile);
configfile = fullfile(path, 'config');
end
if ~isempty(datafile),
%always big endian
fid = fopen(datafile, 'r', 'b');
if fid == -1
error('Cannot open file %s', datafile);
end
fseek(fid, 0, 'eof');
header_end = ftell(fid);
%last 8 bytes of the pdf is header offset
fseek(fid, -8, 'eof');
header_offset = fread(fid,1,'uint64');
%first byte of the header
fseek(fid, header_offset, 'bof');
% read header data
align_file_pointer(fid)
header.header_data.FileType = fread(fid, 1, 'uint16=>uint16');
file_type = char(fread(fid, 5, 'uchar'))';
header.header_data.file_type = file_type(file_type>0);
fseek(fid, 1, 'cof');
format = fread(fid, 1, 'int16=>int16');
switch format
case 1
header.header_data.Format = 'SHORT';
case 2
header.header_data.Format = 'LONG';
case 3
header.header_data.Format = 'FLOAT';
case 4
header.header_data.Format ='DOUBLE';
end
header.header_data.acq_mode = fread(fid, 1, 'uint16=>uint16');
header.header_data.TotalEpochs = fread(fid, 1, 'uint32=>double');
header.header_data.input_epochs = fread(fid, 1, 'uint32=>uint32');
header.header_data.TotalEvents = fread(fid, 1, 'uint32=>uint32');
header.header_data.total_fixed_events = fread(fid, 1, 'uint32=>uint32');
header.header_data.SamplePeriod = fread(fid, 1, 'float32=>float64');
header.header_data.SampleFrequency = 1/header.header_data.SamplePeriod;
xaxis_label = char(fread(fid, 16, 'uchar'))';
header.header_data.xaxis_label = xaxis_label(xaxis_label>0);
header.header_data.total_processes = fread(fid, 1, 'uint32=>uint32');
header.header_data.TotalChannels = fread(fid, 1, 'uint16=>double');
fseek(fid, 2, 'cof');
header.header_data.checksum = fread(fid, 1, 'int32=>int32');
header.header_data.total_ed_classes = fread(fid, 1, 'uint32=>uint32');
header.header_data.total_associated_files = fread(fid, 1, 'uint16=>uint16');
header.header_data.last_file_index = fread(fid, 1, 'uint16=>uint16');
header.header_data.timestamp = fread(fid, 1, 'uint32=>uint32');
header.header_data.reserved = fread(fid, 20, 'uchar')';
fseek(fid, 4, 'cof');
%read epoch_data
for epoch = 1:header.header_data.TotalEpochs;
align_file_pointer(fid)
header.epoch_data(epoch).pts_in_epoch = fread(fid, 1, 'uint32=>uint32');
header.epoch_data(epoch).epoch_duration = fread(fid, 1, 'float32=>float32');
header.epoch_data(epoch).expected_iti = fread(fid, 1, 'float32=>float32');
header.epoch_data(epoch).actual_iti = fread(fid, 1, 'float32=>float32');
header.epoch_data(epoch).total_var_events = fread(fid, 1, 'uint32=>uint32');
header.epoch_data(epoch).checksum = fread(fid, 1, 'int32=>int32');
header.epoch_data(epoch).epoch_timestamp = fread(fid, 1, 'int32=>int32');
header.epoch_data(epoch).reserved = fread(fid, 28, 'uchar')';
header.header_data.SlicesPerEpoch = double(header.epoch_data(1).pts_in_epoch);
%read event data (var_events)
for event = 1:header.epoch_data(epoch).total_var_events
align_file_pointer(fid)
event_name = char(fread(fid, 16, 'uchar'))';
header.epoch_data(epoch).var_event{event}.event_name = event_name(event_name>0);
header.epoch_data(epoch).var_event{event}.start_lat = fread(fid, 1, 'float32=>float32');
header.epoch_data(epoch).var_event{event}.end_lat = fread(fid, 1, 'float32=>float32');
header.epoch_data(epoch).var_event{event}.step_size = fread(fid, 1, 'float32=>float32');
header.epoch_data(epoch).var_event{event}.fixed_event = fread(fid, 1, 'uint16=>uint16');
fseek(fid, 2, 'cof');
header.epoch_data(epoch).var_event{event}.checksum = fread(fid, 1, 'int32=>int32');
header.epoch_data(epoch).var_event{event}.reserved = fread(fid, 32, 'uchar')';
fseek(fid, 4, 'cof');
end
end
%read channel ref data
for channel = 1:header.header_data.TotalChannels
align_file_pointer(fid)
chan_label = (fread(fid, 16, 'uint8=>char'))';
header.channel_data(channel).chan_label = chan_label(chan_label>0);
header.channel_data(channel).chan_no = fread(fid, 1, 'uint16=>uint16');
header.channel_data(channel).attributes = fread(fid, 1, 'uint16=>uint16');
header.channel_data(channel).scale = fread(fid, 1, 'float32=>float32');
yaxis_label = char(fread(fid, 16, 'uint8=>char'))';
header.channel_data(channel).yaxis_label = yaxis_label(yaxis_label>0);
header.channel_data(channel).valid_min_max = fread(fid, 1, 'uint16=>uint16');
fseek(fid, 6, 'cof');
header.channel_data(channel).ymin = fread(fid, 1, 'float64');
header.channel_data(channel).ymax = fread(fid, 1, 'float64');
header.channel_data(channel).index = fread(fid, 1, 'uint32=>uint32');
header.channel_data(channel).checksum = fread(fid, 1, 'int32=>int32');
header.channel_data(channel).whatisit = char(fread(fid, 4, 'uint8=>char'))';
header.channel_data(channel).reserved = fread(fid, 28, 'uint8')';
end
%read event data
for event = 1:header.header_data.total_fixed_events
align_file_pointer(fid)
event_name = char(fread(fid, 16, 'uchar'))';
header.event_data(event).event_name = event_name(event_name>0);
header.event_data(event).start_lat = fread(fid, 1, 'float32=>float32');
header.event_data(event).end_lat = fread(fid, 1, 'float32=>float32');
header.event_data(event).step_size = fread(fid, 1, 'float32=>float32');
header.event_data(event).fixed_event = fread(fid, 1, 'uint16=>uint16');
fseek(fid, 2, 'cof');
header.event_data(event).checksum = fread(fid, 1, 'int32=>int32');
header.event_data(event).reserved = fread(fid, 32, 'uchar')';
fseek(fid, 4, 'cof');
end
header.header_data.FirstLatency = double(header.event_data(1).start_lat);
%experimental: read process information
for np = 1:header.header_data.total_processes
align_file_pointer(fid)
nbytes = fread(fid, 1, 'uint32=>uint32');
fp = ftell(fid);
header.process(np).hdr.nbytes = nbytes;
type = char(fread(fid, 20, 'uchar'))';
header.process(np).hdr.type = type(type>0);
header.process(np).hdr.checksum = fread(fid, 1, 'int32=>int32');
user = char(fread(fid, 32, 'uchar'))';
header.process(np).user = user(user>0);
header.process(np).timestamp = fread(fid, 1, 'uint32=>uint32');
fname = char(fread(fid, 32, 'uchar'))';
header.process(np).filename = fname(fname>0);
fseek(fid, 28*8, 'cof'); %dont know
header.process(np).totalsteps = fread(fid, 1, 'uint32=>uint32');
header.process(np).checksum = fread(fid, 1, 'int32=>int32');
header.process(np).reserved = fread(fid, 32, 'uchar')';
for ns = 1:header.process(np).totalsteps
align_file_pointer(fid)
nbytes2 = fread(fid, 1, 'uint32=>uint32');
header.process(np).step(ns).hdr.nbytes = nbytes2;
type = char(fread(fid, 20, 'uchar'))';
header.process(np).step(ns).hdr.type = type(type>0); %dont know how to interpret the first two
header.process(np).step(ns).hdr.checksum = fread(fid, 1, 'int32=>int32');
userblocksize = fread(fid, 1, 'int32=>int32'); %we are at 32 bytes here
header.process(np).step(ns).userblocksize = userblocksize;
fseek(fid, nbytes2 - 32, 'cof');
if strcmp(header.process(np).step(ns).hdr.type, 'PDF_Weight_Table'),
warning('reading in weight table: no warranty that this is correct. it seems to work for the Glasgow 248-magnetometer system. if you have some code yourself, and/or would like to test it on your own data, please contact Jan-Mathijs');
tmpfp = ftell(fid);
tmp = fread(fid, 1, 'uint8');
Nchan = fread(fid, 1, 'uint32');
Nref = fread(fid, 1, 'uint32');
for k = 1:Nref
name = fread(fid, 17, 'uchar'); %strange number, but seems to be true
header.process(np).step(ns).RefChan{k,1} = char(name(name>0))';
end
fseek(fid, 152, 'cof');
for k = 1:Nchan
name = fread(fid, 17, 'uchar');
header.process(np).step(ns).Chan{k,1} = char(name(name>0))';
end
%fseek(fid, 20, 'cof');
%fseek(fid, 4216, 'cof');
header.process(np).step(ns).stuff1 = fread(fid, 4236, 'uint8');
name = fread(fid, 16, 'uchar');
header.process(np).step(ns).Creator = char(name(name>0))';
%some stuff I don't understand yet
%fseek(fid, 136, 'cof');
header.process(np).step(ns).stuff2 = fread(fid, 136, 'uint8');
%now something strange is going to happen: the weights are probably little-endian encoded.
%here we go: check whether this applies to the whole PDF weight table
fp = ftell(fid);
fclose(fid);
fid = fopen(datafile, 'r', 'l');
fseek(fid, fp, 'bof');
for k = 1:Nchan
header.process(np).step(ns).Weights(k,:) = fread(fid, 23, 'float32=>float32')';
fseek(fid, 36, 'cof');
end
else
if userblocksize < 1e6,
%for one reason or another userblocksize can assume strangely high values
fseek(fid, userblocksize, 'cof');
end
end
end
end
fclose(fid);
end
%end read header
%read config file
fid = fopen(configfile, 'r', 'b');
if fid == -1
error('Cannot open config file');
end
header.config_data.version = fread(fid, 1, 'uint16=>uint16');
site_name = char(fread(fid, 32, 'uchar'))';
header.config_data.site_name = site_name(site_name>0);
dap_hostname = char(fread(fid, 16, 'uchar'))';
header.config_data.dap_hostname = dap_hostname(dap_hostname>0);
header.config_data.sys_type = fread(fid, 1, 'uint16=>uint16');
header.config_data.sys_options = fread(fid, 1, 'uint32=>uint32');
header.config_data.supply_freq = fread(fid, 1, 'uint16=>uint16');
header.config_data.total_chans = fread(fid, 1, 'uint16=>uint16');
header.config_data.system_fixed_gain = fread(fid, 1, 'float32=>float32');
header.config_data.volts_per_bit = fread(fid, 1, 'float32=>float32');
header.config_data.total_sensors = fread(fid, 1, 'uint16=>uint16');
header.config_data.total_user_blocks = fread(fid, 1, 'uint16=>uint16');
header.config_data.next_derived_channel_number = fread(fid, 1, 'uint16=>uint16');
fseek(fid, 2, 'cof');
header.config_data.checksum = fread(fid, 1, 'int32=>int32');
header.config_data.reserved = fread(fid, 32, 'uchar=>uchar')';
header.config.Xfm = fread(fid, [4 4], 'double');
%user blocks
for ub = 1:header.config_data.total_user_blocks
align_file_pointer(fid)
header.user_block_data{ub}.hdr.nbytes = fread(fid, 1, 'uint32=>uint32');
type = char(fread(fid, 20, 'uchar'))';
header.user_block_data{ub}.hdr.type = type(type>0);
header.user_block_data{ub}.hdr.checksum = fread(fid, 1, 'int32=>int32');
user = char(fread(fid, 32, 'uchar'))';
header.user_block_data{ub}.user = user(user>0);
header.user_block_data{ub}.timestamp = fread(fid, 1, 'uint32=>uint32');
header.user_block_data{ub}.user_space_size = fread(fid, 1, 'uint32=>uint32');
header.user_block_data{ub}.reserved = fread(fid, 32, 'uchar=>uchar')';
fseek(fid, 4, 'cof');
user_space_size = double(header.user_block_data{ub}.user_space_size);
if strcmp(type(type>0), 'B_weights_used'),
%warning('reading in weight table: no warranty that this is correct. it seems to work for the Glasgow 248-magnetometer system. if you have some code yourself, and/or would like to test it on your own data, please contact Jan-Mathijs');
tmpfp = ftell(fid);
%read user_block_data weights
%there is information in the 4th and 8th byte, these might be related to the settings?
version = fread(fid, 1, 'uint32');
header.user_block_data{ub}.version = version;
if version==1,
Nbytes = fread(fid,1,'uint32');
Nchan = fread(fid,1,'uint32');
Position = fread(fid, 32, 'uchar');
header.user_block_data{ub}.position = char(Position(Position>0))';
fseek(fid,tmpfp+user_space_size - Nbytes*Nchan, 'bof');
Ndigital = floor((Nbytes - 4*2) / 4);
Nanalog = 3; %lucky guess?
% how to know number of analog weights vs digital weights???
for ch = 1:Nchan
% for Konstanz -- comment for others?
header.user_block_data{ub}.aweights(ch,:) = fread(fid, [1 Nanalog], 'int16')';
fseek(fid,2,'cof'); % alignment
header.user_block_data{ub}.dweights(ch,:) = fread(fid, [1 Ndigital], 'single=>double')';
end
fseek(fid, tmpfp, 'bof');
%there is no information with respect to the channels here.
%the best guess would be to assume the order identical to the order in header.config.channel_data
%for the digital weights it would be the order of the references in that list
%for the analog weights I would not know
elseif version==2,
unknown2 = fread(fid, 1, 'uint32');
Nchan = fread(fid, 1, 'uint32');
Position = fread(fid, 32, 'uchar');
header.user_block_data{ub}.position = char(Position(Position>0))';
fseek(fid, tmpfp+124, 'bof');
Nanalog = fread(fid, 1, 'uint32');
Ndigital = fread(fid, 1, 'uint32');
fseek(fid, tmpfp+204, 'bof');
for k = 1:Nchan
Name = fread(fid, 16, 'uchar');
header.user_block_data{ub}.channames{k,1} = char(Name(Name>0))';
end
for k = 1:Nanalog
Name = fread(fid, 16, 'uchar');
header.user_block_data{ub}.arefnames{k,1} = char(Name(Name>0))';
end
for k = 1:Ndigital
Name = fread(fid, 16, 'uchar');
header.user_block_data{ub}.drefnames{k,1} = char(Name(Name>0))';
end
header.user_block_data{ub}.dweights = fread(fid, [Ndigital Nchan], 'single=>double')';
header.user_block_data{ub}.aweights = fread(fid, [Nanalog Nchan], 'int16')';
fseek(fid, tmpfp, 'bof');
end
elseif strcmp(type(type>0), 'B_E_table_used'),
%warning('reading in weight table: no warranty that this is correct');
%tmpfp = ftell(fid);
%fseek(fid, 4, 'cof'); %there's info here dont know how to interpret
%Nx = fread(fid, 1, 'uint32');
%Nchan = fread(fid, 1, 'uint32');
%type = fread(fid, 32, 'uchar'); %don't know whether correct
%header.user_block_data{ub}.type = char(type(type>0))';
%fseek(fid, 16, 'cof');
%for k = 1:Nchan
% name = fread(fid, 16, 'uchar');
% header.user_block_data{ub}.name{k,1} = char(name(name>0))';
%end
elseif strcmp(type(type>0), 'B_COH_Points'),
tmpfp = ftell(fid);
Ncoil = fread(fid, 1, 'uint32');
N = fread(fid, 1, 'uint32');
coils = fread(fid, [7 Ncoil], 'double');
header.user_block_data{ub}.pnt = coils(1:3,:)';
header.user_block_data{ub}.ori = coils(4:6,:)';
header.user_block_data{ub}.Ncoil = Ncoil;
header.user_block_data{ub}.N = N;
tmp = fread(fid, (904-288)/8, 'double');
header.user_block_data{ub}.tmp = tmp; %FIXME try to find out what these bytes mean
fseek(fid, tmpfp, 'bof');
elseif strcmp(type(type>0), 'b_ccp_xfm_block'),
tmpfp = ftell(fid);
tmp1 = fread(fid, 1, 'uint32');
%tmp = fread(fid, [4 4], 'double');
%tmp = fread(fid, [4 4], 'double');
%the next part seems to be in little endian format (at least when I tried)
tmp = fread(fid, 128, 'uint8');
tmp = uint8(reshape(tmp, [8 16])');
xfm = zeros(4,4);
for k = 1:size(tmp,1)
xfm(k) = typecast(tmp(k,:), 'double');
if abs(xfm(k))<1e-10 || abs(xfm(k))>1e10, xfm(k) = typecast(fliplr(tmp(k,:)), 'double');end
end
fseek(fid, tmpfp, 'bof'); %FIXME try to find out why this looks so strange
elseif strcmp(type(type>0), 'b_eeg_elec_locs'),
%this block contains the digitized coil and electrode positions
tmpfp = ftell(fid);
Npoints = user_space_size./40;
for k = 1:Npoints
tmp = fread(fid, 16, 'uchar');
%tmplabel = char(tmp(tmp>47 & tmp<128)'); %stick to plain ASCII
% store up until the first space
tmplabel = char(tmp(1:max(1,(find(tmp==0,1,'first')-1)))'); %stick to plain ASCII
%if strmatch('Coil', tmplabel),
% label{k} = tmplabel(1:5);
%elseif ismember(tmplabel(1), {'L' 'R' 'C' 'N' 'I'}),
% label{k} = tmplabel(1);
%else
% label{k} = '';
%end
label{k} = tmplabel;
tmp = fread(fid, 3, 'double');
pnt(k,:) = tmp(:)';
end
% post-processing of the labels
% it seems the following can happen
% - a sequence of L R N C I, i.e. the coordinate system defining landmarks
for k = 1:numel(label)
firstletter(k) = label{k}(1);
end
sel = strfind(firstletter, 'LRNCI');
if ~isempty(sel)
label{sel} = label{sel}(1);
label{sel+1} = label{sel+1}(1);
label{sel+2} = label{sel+2}(1);
label{sel+3} = label{sel+3}(1);
label{sel+4} = label{sel+4}(1);
end
% - a sequence of coil1...coil5 i.e. the localization coils
for k = 1:numel(label)
if strncmpi(label{k},'coil',4)
label{k} = label{k}(1:5);
end
end
% - something else: EEG electrodes?
header.user_block_data{ub}.label = label(:);
header.user_block_data{ub}.pnt = pnt;
fseek(fid, tmpfp, 'bof');
end
fseek(fid, user_space_size, 'cof');
end
%channels
for ch = 1:header.config_data.total_chans
align_file_pointer(fid)
name = char(fread(fid, 16, 'uchar'))';
header.config.channel_data(ch).name = name(name>0);
%FIXME this is a very dirty fix to get the reading in of continuous headlocalization
%correct. At the moment, the numbering of the hmt related channels seems to start with 1000
%which I don't understand, but seems rather nonsensical.
chan_no = fread(fid, 1, 'uint16=>uint16');
if chan_no > header.config_data.total_chans,
%FIXME fix the number in header.channel_data as well
sel = find([header.channel_data.chan_no]== chan_no);
if ~isempty(sel),
chan_no = ch;
header.channel_data(sel).chan_no = chan_no;
header.channel_data(sel).chan_label = header.config.channel_data(ch).name;
else
%does not matter
end
end
header.config.channel_data(ch).chan_no = chan_no;
header.config.channel_data(ch).type = fread(fid, 1, 'uint16=>uint16');
header.config.channel_data(ch).sensor_no = fread(fid, 1, 'int16=>int16');
fseek(fid, 2, 'cof');
header.config.channel_data(ch).gain = fread(fid, 1, 'float32=>float32');
header.config.channel_data(ch).units_per_bit = fread(fid, 1, 'float32=>float32');
yaxis_label = char(fread(fid, 16, 'uchar'))';
header.config.channel_data(ch).yaxis_label = yaxis_label(yaxis_label>0);
header.config.channel_data(ch).aar_val = fread(fid, 1, 'double');
header.config.channel_data(ch).checksum = fread(fid, 1, 'int32=>int32');
header.config.channel_data(ch).reserved = fread(fid, 32, 'uchar=>uchar')';
fseek(fid, 4, 'cof');
align_file_pointer(fid)
header.config.channel_data(ch).device_data.hdr.size = fread(fid, 1, 'uint32=>uint32');
header.config.channel_data(ch).device_data.hdr.checksum = fread(fid, 1, 'int32=>int32');
header.config.channel_data(ch).device_data.hdr.reserved = fread(fid, 32, 'uchar=>uchar')';
switch header.config.channel_data(ch).type
case {1, 3}%meg/ref
header.config.channel_data(ch).device_data.inductance = fread(fid, 1, 'float32=>float32');
fseek(fid, 4, 'cof');
header.config.channel_data(ch).device_data.Xfm = fread(fid, [4 4], 'double');
header.config.channel_data(ch).device_data.xform_flag = fread(fid, 1, 'uint16=>uint16');
header.config.channel_data(ch).device_data.total_loops = fread(fid, 1, 'uint16=>uint16');
header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')';
fseek(fid, 4, 'cof');
for loop = 1:header.config.channel_data(ch).device_data.total_loops
align_file_pointer(fid)
header.config.channel_data(ch).device_data.loop_data(loop).position = fread(fid, 3, 'double');
header.config.channel_data(ch).device_data.loop_data(loop).direction = fread(fid, 3, 'double');
header.config.channel_data(ch).device_data.loop_data(loop).radius = fread(fid, 1, 'double');
header.config.channel_data(ch).device_data.loop_data(loop).wire_radius = fread(fid, 1, 'double');
header.config.channel_data(ch).device_data.loop_data(loop).turns = fread(fid, 1, 'uint16=>uint16');
fseek(fid, 2, 'cof');
header.config.channel_data(ch).device_data.loop_data(loop).checksum = fread(fid, 1, 'int32=>int32');
header.config.channel_data(ch).device_data.loop_data(loop).reserved = fread(fid, 32, 'uchar=>uchar')';
end
case 2%eeg
header.config.channel_data(ch).device_data.impedance = fread(fid, 1, 'float32=>float32');
fseek(fid, 4, 'cof');
header.config.channel_data(ch).device_data.Xfm = fread(fid, [4 4], 'double');
header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')';
case 4%external
header.config.channel_data(ch).device_data.user_space_size = fread(fid, 1, 'uint32=>uint32');
header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')';
fseek(fid, 4, 'cof');
case 5%TRIGGER
header.config.channel_data(ch).device_data.user_space_size = fread(fid, 1, 'uint32=>uint32');
header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')';
fseek(fid, 4, 'cof');
case 6%utility
header.config.channel_data(ch).device_data.user_space_size = fread(fid, 1, 'uint32=>uint32');
header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')';
fseek(fid, 4, 'cof');
case 7%derived
header.config.channel_data(ch).device_data.user_space_size = fread(fid, 1, 'uint32=>uint32');
header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')';
fseek(fid, 4, 'cof');
case 8%shorted
header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')';
otherwise
error('Unknown device type: %d\n', header.config.channel_data(ch).type);
end
end
fclose(fid);
%end read config file
header.header_data.FileDescriptor = 0; %no obvious field to take this from
header.header_data.Events = 1;%no obvious field to take this from
header.header_data.EventCodes = 0;%no obvious field to take this from
if isfield(header, 'channel_data'),
header.ChannelGain = double([header.config.channel_data([header.channel_data.chan_no]).gain]');
header.ChannelUnitsPerBit = double([header.config.channel_data([header.channel_data.chan_no]).units_per_bit]');
header.Channel = {header.config.channel_data([header.channel_data.chan_no]).name}';
header.ChannelType = double([header.config.channel_data([header.channel_data.chan_no]).type]');
%header.Channel = {header.channel_data.chan_label}';
%header.Channel = {header.channel_data([header.channel_data.index]+1).chan_label}';
header.Format = header.header_data.Format;
% take the EEG labels from the channel_data, and the rest of the labels
% from the config.channel_data. Some systems have overloaded MEG channel
% labels, which clash with the labels in the grad-structure. This will
% lead to problems in forward/inverse modelling. Use the following
% convention: keep the ones from the config.
% Some systems have overloaded EEG channel
% labels, rather than Exxx have a human interpretable form. Use these,
% to prevent a clash with the elec-structure, if present. This is a
% bit clunky (because EEG is treated different from MEG), but inherent is
% inherent in how the header information is organised.
header.Channel(header.ChannelType==2) = {header.channel_data(header.ChannelType==2).chan_label}';
end
function align_file_pointer(fid)
current_position = ftell(fid);
if mod(current_position, 8) ~= 0
offset = 8 - mod(current_position,8);
fseek(fid, offset, 'cof');
end
|
github
|
ZijingMao/baselineeegtest-master
|
decode_nifti1.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/decode_nifti1.m
| 3,043 |
utf_8
|
e74c0ee902019b3883dbaf1cb0ebda26
|
function H = decode_nifti1(blob)
% DECODE_NIFTI1 is a helper function for real-time processing of MRI data
%
% Use as
% H = decode_nifti1(blob)
%
% Decodes a NIFTI-1 header given as raw 348 bytes (uint8) into a Matlab structure
% that matches the C struct defined in nifti1.h, with the only difference that the
% variable length arrays "dim" and "pixdim" are cut off to the right size, e.g., the
% "dim" entry will only contain the relevant elements:
% dim[0..7]={3,64,64,18,x,x,x,x} in C would become dim=[64,64,18] in Matlab.
%
% WARNING: This function currently ignores endianness !!!
%
% See also DECODE_RES4, DECODE_NIFTI1, SAP2MATLAB
% (C) 2010 S.Klanke
if class(blob)~='uint8'
error 'Bad type for blob'
end
if length(blob)~=348
error 'Blob must be exactly 348 bytes long'
end
% see nift1.h for information on structure
H = [];
magic = char(blob(345:347));
if blob(348)~=0 | magic~='ni1' & magic~='n+1'
error 'Not a NIFTI-1 header!';
end
H.sizeof_hdr = typecast(blob(1:4),'int32');
H.data_type = cstr2matlab(blob(5:14));
H.db_name = cstr2matlab(blob(15:32));
H.extents = typecast(blob(33:36),'int32');
H.session_error = typecast(blob(37:38),'int16');
H.regular = blob(39);
H.dim_info = blob(40);
dim = typecast(blob(41:56),'int16');
H.dim = dim(2:dim(1)+1);
H.intent_p1 = typecast(blob(57:60),'single');
H.intent_p2 = typecast(blob(61:64),'single');
H.intent_p3 = typecast(blob(65:68),'single');
H.intent_code = typecast(blob(69:70),'int16');
H.datatype = typecast(blob(71:72),'int16');
H.bitpix = typecast(blob(73:74),'int16');
H.slice_start = typecast(blob(75:76),'int16');
pixdim = typecast(blob(77:108),'single');
H.qfac = pixdim(1);
H.pixdim = pixdim(2:dim(1)+1);
H.vox_offset = typecast(blob(109:112),'single');
H.scl_scope = typecast(blob(113:116),'single');
H.scl_inter = typecast(blob(117:120),'single');
H.slice_end = typecast(blob(121:122),'int16');
H.slice_code = blob(123);
H.xyzt_units = blob(124);
H.cal_max = typecast(blob(125:128),'single');
H.cal_min = typecast(blob(129:132),'single');
H.slice_duration = typecast(blob(133:136),'single');
H.toffset = typecast(blob(137:140),'single');
H.glmax = typecast(blob(141:144),'int32');
H.glmin = typecast(blob(145:148),'int32');
H.descrip = cstr2matlab(blob(149:228));
H.aux_file = cstr2matlab(blob(229:252));
H.qform_code = typecast(blob(253:254),'int16');
H.sform_code = typecast(blob(255:256),'int16');
quats = typecast(blob(257:280),'single');
H.quatern_b = quats(1);
H.quatern_c = quats(2);
H.quatern_d = quats(3);
H.quatern_x = quats(4);
H.quatern_y = quats(5);
H.quatern_z = quats(6);
trafo = typecast(blob(281:328),'single');
H.srow_x = trafo(1:4);
H.srow_y = trafo(5:8);
H.srow_z = trafo(9:12);
%H.S = [H.srow_x; H.srow_y; H.srow_z; 0 0 0 1];
H.intent_name = cstr2matlab(blob(329:344));
H.magic = magic;
function ms = cstr2matlab(cs)
if cs(1)==0
ms = '';
else
ind = find(cs==0);
if isempty(ind)
ms = char(cs)';
else
ms = char(cs(1:ind(1)-1))';
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
read_edf.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/read_edf.m
| 16,383 |
utf_8
|
76f3f3461aa550382e8ebedfe44d6326
|
function [dat] = read_edf(filename, hdr, begsample, endsample, chanindx)
% READ_EDF reads specified samples from an EDF continous datafile
% It neglects all trial boundaries as if the data was acquired in
% non-continous mode.
%
% Use as
% [hdr] = read_edf(filename);
% where
% filename name of the datafile, including the .edf extension
% This returns a header structure with the following elements
% hdr.Fs sampling frequency
% hdr.nChans number of channels
% hdr.nSamples number of samples per trial
% hdr.nSamplesPre number of pre-trigger samples in each trial
% hdr.nTrials number of trials
% hdr.label cell-array with labels of each channel
% hdr.orig detailled EDF header information
%
% Use as
% [hdr] = read_edf(filename, [], chanindx);
% where
% filename name of the datafile, including the .edf extension
% chanindx index of channels to read (optional, default is all)
% This returns a header structure with the following elements
% hdr.Fs sampling frequency
% hdr.nChans number of channels
% hdr.nSamples number of samples per trial
% hdr.nSamplesPre number of pre-trigger samples in each trial
% hdr.nTrials number of trials
% hdr.label cell-array with labels of each channel
% hdr.orig detailled EDF header information
%
% Or use as
% [dat] = read_edf(filename, hdr, begsample, endsample, chanindx);
% where
% filename name of the datafile, including the .edf extension
% hdr header structure, see above
% begsample index of the first sample to read
% endsample index of the last sample to read
% chanindx index of channels to read (optional, default is all)
% This returns a Nchans X Nsamples data matrix
%
% Or use as
% [evt] = read_edf(filename, hdr);
% where
% filename name of the datafile, including the .edf extension
% hdr header structure, see above
% This returns an Nsamples data vector of just the annotation channel
% Copyright (C) 2006, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: read_edf.m 10432 2015-05-31 11:10:16Z roboos $
switch nargin
case 1
chanindx=[];
case 2
chanindx=[];
case 3
chanindx=begsample;
case 4
end;
needhdr = (nargin==1)||(nargin==3);
needevt = (nargin==2);
needdat = (nargin==5);
if needhdr
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the header, this code is from EEGLAB's openbdf
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FILENAME = filename;
% defines Seperator for Subdirectories
SLASH='/';
BSLASH=char(92);
cname=computer;
if cname(1:2)=='PC' SLASH=BSLASH; end;
fid=fopen(FILENAME,'r','ieee-le');
if fid<0
fprintf(2,['Error LOADEDF: File ' FILENAME ' not found\n']);
return;
end;
EDF.FILE.FID=fid;
EDF.FILE.OPEN = 1;
EDF.FileName = FILENAME;
PPos=min([max(find(FILENAME=='.')) length(FILENAME)+1]);
SPos=max([0 find((FILENAME=='/') | (FILENAME==BSLASH))]);
EDF.FILE.Ext = FILENAME(PPos+1:length(FILENAME));
EDF.FILE.Name = FILENAME(SPos+1:PPos-1);
if SPos==0
EDF.FILE.Path = pwd;
else
EDF.FILE.Path = FILENAME(1:SPos-1);
end;
EDF.FileName = [EDF.FILE.Path SLASH EDF.FILE.Name '.' EDF.FILE.Ext];
H1=char(fread(EDF.FILE.FID,256,'char')'); %
EDF.VERSION=H1(1:8); % 8 Byte Versionsnummer
%if 0 fprintf(2,'LOADEDF: WARNING Version EDF Format %i',ver); end;
EDF.PID = deblank(H1(9:88)); % 80 Byte local patient identification
EDF.RID = deblank(H1(89:168)); % 80 Byte local recording identification
%EDF.H.StartDate = H1(169:176); % 8 Byte
%EDF.H.StartTime = H1(177:184); % 8 Byte
EDF.T0=[str2num(H1(168+[7 8])) str2num(H1(168+[4 5])) str2num(H1(168+[1 2])) str2num(H1(168+[9 10])) str2num(H1(168+[12 13])) str2num(H1(168+[15 16])) ];
% Y2K compatibility until year 2090
if EDF.VERSION(1)=='0'
if EDF.T0(1) < 91
EDF.T0(1)=2000+EDF.T0(1);
else
EDF.T0(1)=1900+EDF.T0(1);
end;
else ;
% in a future version, this is hopefully not needed
end;
EDF.HeadLen = str2num(H1(185:192)); % 8 Byte Length of Header
% reserved = H1(193:236); % 44 Byte
EDF.NRec = str2num(H1(237:244)); % 8 Byte # of data records
EDF.Dur = str2num(H1(245:252)); % 8 Byte # duration of data record in sec
EDF.NS = str2num(H1(253:256)); % 8 Byte # of signals
EDF.Label = char(fread(EDF.FILE.FID,[16,EDF.NS],'char')');
EDF.Transducer = char(fread(EDF.FILE.FID,[80,EDF.NS],'char')');
EDF.PhysDim = char(fread(EDF.FILE.FID,[8,EDF.NS],'char')');
EDF.PhysMin= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'));
EDF.PhysMax= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'));
EDF.DigMin = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'));
EDF.DigMax = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'));
% check validity of DigMin and DigMax
if (length(EDF.DigMin) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Digital Minimum\n');
EDF.DigMin = -(2^15)*ones(EDF.NS,1);
end
if (length(EDF.DigMax) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Digital Maximum\n');
EDF.DigMax = (2^15-1)*ones(EDF.NS,1);
end
if (any(EDF.DigMin >= EDF.DigMax))
fprintf(2,'Warning OPENEDF: Digital Minimum larger than Maximum\n');
end
% check validity of PhysMin and PhysMax
if (length(EDF.PhysMin) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Physical Minimum\n');
EDF.PhysMin = EDF.DigMin;
end
if (length(EDF.PhysMax) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Physical Maximum\n');
EDF.PhysMax = EDF.DigMax;
end
if (any(EDF.PhysMin >= EDF.PhysMax))
fprintf(2,'Warning OPENEDF: Physical Minimum larger than Maximum\n');
EDF.PhysMin = EDF.DigMin;
EDF.PhysMax = EDF.DigMax;
end
EDF.PreFilt= char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); %
tmp = fread(EDF.FILE.FID,[8,EDF.NS],'char')'; % samples per data record
EDF.SPR = str2num(char(tmp)); % samples per data record
fseek(EDF.FILE.FID,32*EDF.NS,0);
EDF.Cal = (EDF.PhysMax-EDF.PhysMin)./(EDF.DigMax-EDF.DigMin);
EDF.Off = EDF.PhysMin - EDF.Cal .* EDF.DigMin;
tmp = find(EDF.Cal < 0);
EDF.Cal(tmp) = ones(size(tmp));
EDF.Off(tmp) = zeros(size(tmp));
EDF.Calib=[EDF.Off';(diag(EDF.Cal))];
%EDF.Calib=sparse(diag([1; EDF.Cal]));
%EDF.Calib(1,2:EDF.NS+1)=EDF.Off';
EDF.SampleRate = EDF.SPR / EDF.Dur;
EDF.FILE.POS = ftell(EDF.FILE.FID);
if EDF.NRec == -1 % unknown record size, determine correct NRec
fseek(EDF.FILE.FID, 0, 'eof');
endpos = ftell(EDF.FILE.FID);
EDF.NRec = floor((endpos - EDF.FILE.POS) / (sum(EDF.SPR) * 2));
fseek(EDF.FILE.FID, EDF.FILE.POS, 'bof');
H1(237:244)=sprintf('%-8i',EDF.NRec); % write number of records
end;
EDF.Chan_Select=(EDF.SPR==max(EDF.SPR));
for k=1:EDF.NS
if EDF.Chan_Select(k)
EDF.ChanTyp(k)='N';
else
EDF.ChanTyp(k)=' ';
end;
if findstr(upper(EDF.Label(k,:)),'ECG')
EDF.ChanTyp(k)='C';
elseif findstr(upper(EDF.Label(k,:)),'EKG')
EDF.ChanTyp(k)='C';
elseif findstr(upper(EDF.Label(k,:)),'EEG')
EDF.ChanTyp(k)='E';
elseif findstr(upper(EDF.Label(k,:)),'EOG')
EDF.ChanTyp(k)='O';
elseif findstr(upper(EDF.Label(k,:)),'EMG')
EDF.ChanTyp(k)='M';
end;
end;
if isempty(chanindx)
chanindx=[1:EDF.NS];
end;
EDF.AS.spb = sum(EDF.SPR); % Samples per Block
bi=[0;cumsum(EDF.SPR)];
idx=[];idx2=[];
for k=1:EDF.NS,
idx2=[idx2, (k-1)*max(EDF.SPR)+(1:EDF.SPR(k))];
end;
maxspr=max(EDF.SPR);
idx3=zeros(EDF.NS*maxspr,1);
for k=1:EDF.NS, idx3(maxspr*(k-1)+(1:maxspr))=bi(k)+ceil((1:maxspr)'/maxspr*EDF.SPR(k));end;
%EDF.AS.bi=bi;
EDF.AS.IDX2=idx2;
%EDF.AS.IDX3=idx3;
% close the file
fclose(EDF.FILE.FID);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert the header to Fieldtrip-style
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if all(EDF.SampleRate(chanindx)==EDF.SampleRate(chanindx(1)))
chansel=chanindx;
hdr.Fs = EDF.SampleRate(chanindx(1));
hdr.nChans = length(chansel);
hdr.label = cellstr(EDF.Label);
hdr.label = hdr.label(chansel);
% it is continuous data, therefore append all records in one trial
hdr.nSamples = EDF.NRec * EDF.Dur * EDF.SampleRate(chansel(1));
hdr.nSamplesPre = 0;
hdr.nTrials = 1;
hdr.orig = EDF;
% this will be used on subsequent reading of data
if length(chansel) ~= EDF.NS
hdr.orig.chansel = chansel;
else
hdr.orig.chansel = 1:hdr.nChans;
end;
hdr.orig.annotation = find(strcmp(cellstr(hdr.orig.Label), 'EDF Annotations'));
elseif all(EDF.SampleRate(1:end-1)==EDF.SampleRate(1))
% only the last channel has a deviant sampling frequency
% this is the case for EGI recorded datasets that have been converted
% to EDF+, in which case the annotation channel is the last
chansel = find(EDF.SampleRate==EDF.SampleRate(1));
% continue with the subset of channels that has a consistent sampling frequency
hdr.Fs = EDF.SampleRate(chansel(1));
hdr.nChans = length(chansel);
warning('Skipping "%s" as continuous data channel because of inconsistent sampling frequency (%g Hz)', deblank(EDF.Label(end,:)), EDF.SampleRate(end));
hdr.label = cellstr(EDF.Label);
hdr.label = hdr.label(chansel);
% it is continuous data, therefore append all records in one trial
hdr.nSamples = EDF.NRec * EDF.Dur * EDF.SampleRate(chansel(1));
hdr.nSamplesPre = 0;
hdr.nTrials = 1;
hdr.orig = EDF;
% this will be used on subsequent reading of data
hdr.orig.chansel = chansel;
hdr.orig.annotation = find(strcmp(cellstr(hdr.orig.Label), 'EDF Annotations'));
else
% select the sampling rate that results in the most channels
[a, b, c] = unique(EDF.SampleRate);
for i=1:length(a)
chancount(i) = sum(c==i);
end
[dum, indx] = max(chancount);
chansel = find(EDF.SampleRate == a(indx));
% continue with the subset of channels that has a consistent sampling frequency
hdr.Fs = EDF.SampleRate(chansel(1));
hdr.nChans = length(chansel);
hdr.label = cellstr(EDF.Label);
hdr.label = hdr.label(chansel);
% it is continuous data, therefore append all records in one trial
hdr.nSamples = EDF.NRec * EDF.Dur * EDF.SampleRate(chansel(1));
hdr.nSamplesPre = 0;
hdr.nTrials = 1;
hdr.orig = EDF;
% this will be used on subsequent reading of data
hdr.orig.chansel = chansel;
hdr.orig.annotation = find(strcmp(cellstr(hdr.orig.Label), 'EDF Annotations'));
warning('channels with different sampling rate not supported, using a subselection of %d channels at %f Hz', length(hdr.label), hdr.Fs);
end
% return the header
dat = hdr;
elseif needdat || needevt
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% retrieve the original header
EDF = hdr.orig;
% determine whether a subset of channels should be used
% which is the case if channels have a variable sampling frequency
variableFs = isfield(EDF, 'chansel');
if variableFs && needevt
% read the annotation channel, not the data channels
EDF.chansel = EDF.annotation;
begsample = 1;
endsample = EDF.SampleRate(end)*EDF.NRec*EDF.Dur;
end
if variableFs
epochlength = EDF.Dur * EDF.SampleRate(EDF.chansel(1)); % in samples for the selected channel
blocksize = sum(EDF.Dur * EDF.SampleRate); % in samples for all channels
chanoffset = EDF.Dur * EDF.SampleRate;
chanoffset = cumsum([0; chanoffset(1:end-1)]);
% use a subset of channels
nchans = length(EDF.chansel);
chanindx=[1:nchans]; %JD
else
epochlength = EDF.Dur * EDF.SampleRate(1); % in samples for a single channel
blocksize = sum(EDF.Dur * EDF.SampleRate); % in samples for all channels
% use all channels
nchans = EDF.NS;
end
% determine the trial containing the begin and end sample
begepoch = floor((begsample-1)/epochlength) + 1;
endepoch = floor((endsample-1)/epochlength) + 1;
nepochs = endepoch - begepoch + 1;
% allocate memory to hold the data
dat = zeros(length(chanindx),nepochs*epochlength);
% read and concatenate all required data epochs
for i=begepoch:endepoch
if variableFs
% only a subset of channels with consistent sampling frequency is read
offset = EDF.HeadLen + (i-1)*blocksize*2; % in bytes
% read the complete data block
buf = readLowLevel(filename, offset, blocksize); % see below in subfunction
for j=1:length(chanindx)
% cut out the part that corresponds with a single channel
dat(j,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf((1:epochlength) + chanoffset(EDF.chansel(chanindx(j))));
end
elseif length(chanindx)==1
% this is more efficient if only one channel has to be read, e.g. the status channel
offset = EDF.HeadLen + (i-1)*blocksize*2; % in bytes
offset = offset + (chanindx-1)*epochlength*2;
% read the data for a single channel
buf = readLowLevel(filename, offset, epochlength); % see below in subfunction
dat(:,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf;
else
% read the data from all channels, subsequently select the desired channels
offset = EDF.HeadLen + (i-1)*blocksize*2; % in bytes
% read the complete data block
buf = readLowLevel(filename, offset, blocksize); % see below in subfunction
buf = reshape(buf, epochlength, nchans);
dat(:,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf(:,chanindx)';
end
end
% select the desired samples
begsample = begsample - (begepoch-1)*epochlength; % correct for the number of bytes that were skipped
endsample = endsample - (begepoch-1)*epochlength; % correct for the number of bytes that were skipped
dat = dat(:, begsample:endsample);
% Calibrate the data
if variableFs
calib = diag(EDF.Cal(EDF.chansel(chanindx)));
else
calib = diag(EDF.Cal(chanindx));
end
if length(chanindx)>1
% using a sparse matrix speeds up the multiplication
dat = sparse(calib) * dat;
else
% in case of one channel the sparse multiplication would result in a sparse array
dat = calib * dat;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for reading the 16 bit values
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function buf = readLowLevel(filename, offset, numwords)
if offset < 2*1024^2
% use the external mex file, only works for <2GB
buf = read_16bit(filename, offset, numwords);
else
% use plain matlab, thanks to Philip van der Broek
fp = fopen(filename,'r','ieee-le');
status = fseek(fp, offset, 'bof');
if status
error(['failed seeking ' filename]);
end
[buf,num] = fread(fp,numwords,'bit16=>double');
fclose(fp);
if (num<numwords)
error(['failed reading ' filename]);
return
end
end
|
github
|
ZijingMao/baselineeegtest-master
|
yokogawa2grad.m
|
.m
|
baselineeegtest-master/External Software/EEGLAB/eeglab13_4_4b/plugins/Fileio150704/private/yokogawa2grad.m
| 7,205 |
utf_8
|
c61a324e8fd20060380618a1f0760a72
|
function grad = yokogawa2grad(hdr)
% YOKOGAWA2GRAD converts the position and weights of all coils that
% compromise a gradiometer system into a structure that can be used
% by FieldTrip. This implementation uses the old "yokogawa" toolbox.
%
% See also CTF2GRAD, BTI2GRAD, FIF2GRAD, MNE2GRAD, ITAB2GRAD,
% FT_READ_SENS, FT_READ_HEADER
% Copyright (C) 2005-2008, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: yokogawa2grad.m 7123 2012-12-06 21:21:38Z roboos $
if ~ft_hastoolbox('yokogawa')
error('cannot determine whether Yokogawa toolbox is present');
end
if isfield(hdr, 'label')
label = hdr.label; % keep for later use
end
if isfield(hdr, 'orig')
hdr = hdr.orig; % use the original header, not the FieldTrip header
end
% The "channel_info" contains
% 1 channel number, zero offset
% 2 channel type, type of gradiometer
% 3 position x (in m)
% 4 position y (in m)
% 5 position z (in m)
% 6 orientation of first coil (theta in deg)
% 7 orientation of first coil (phi in deg)
% 8 orientation from the 1st to 2nd coil for gradiometer (theta in deg)
% 9 orientation from the 1st to 2nd coil for gradiometer (phi in deg)
% 10 coil size (in m)
% 11 baseline (in m)
handles = definehandles;
isgrad = (hdr.channel_info(:,2)==handles.AxialGradioMeter | ...
hdr.channel_info(:,2)==handles.PlannerGradioMeter | ...
hdr.channel_info(:,2)==handles.MagnetoMeter | ...
hdr.channel_info(:,2)==handles.RefferenceAxialGradioMeter);
% reference channels are excluded because the positions are not specified
% hdr.channel_info(:,2)==handles.RefferencePlannerGradioMeter
% hdr.channel_info(:,2)==handles.RefferenceMagnetoMeter
isgrad_handles = hdr.channel_info(isgrad,2);
ismag = (isgrad_handles(:)==handles.MagnetoMeter | isgrad_handles(:)==handles.RefferenceMagnetoMeter);
grad.coilpos = hdr.channel_info(isgrad,3:5)*100; % cm
grad.unit = 'cm';
% Get orientation of the 1st coil
ori_1st = hdr.channel_info(find(isgrad),[6 7]);
% polar to x,y,z coordinates
ori_1st = ...
[sin(ori_1st(:,1)/180*pi).*cos(ori_1st(:,2)/180*pi) ...
sin(ori_1st(:,1)/180*pi).*sin(ori_1st(:,2)/180*pi) ...
cos(ori_1st(:,1)/180*pi)];
grad.coilori = ori_1st;
% Get orientation from the 1st to 2nd coil for gradiometer
ori_1st_to_2nd = hdr.channel_info(find(isgrad),[8 9]);
% polar to x,y,z coordinates
ori_1st_to_2nd = ...
[sin(ori_1st_to_2nd(:,1)/180*pi).*cos(ori_1st_to_2nd(:,2)/180*pi) ...
sin(ori_1st_to_2nd(:,1)/180*pi).*sin(ori_1st_to_2nd(:,2)/180*pi) ...
cos(ori_1st_to_2nd(:,1)/180*pi)];
% Get baseline
baseline = hdr.channel_info(isgrad,size(hdr.channel_info,2));
% Define the location and orientation of 2nd coil
info = hdr.channel_info(isgrad,2);
for i=1:sum(isgrad)
if (info(i) == handles.AxialGradioMeter || info(i) == handles.RefferenceAxialGradioMeter )
grad.coilpos(i+sum(isgrad),:) = [grad.coilpos(i,:)+ori_1st(i,:)*baseline(i)*100];
grad.coilori(i+sum(isgrad),:) = -ori_1st(i,:);
elseif (info(i) == handles.PlannerGradioMeter || info(i) == handles.RefferencePlannerGradioMeter)
grad.coilpos(i+sum(isgrad),:) = [grad.coilpos(i,:)+ori_1st_to_2nd(i,:)*baseline(i)*100];
grad.coilori(i+sum(isgrad),:) = -ori_1st(i,:);
else
grad.coilpos(i+sum(isgrad),:) = [0 0 0];
grad.coilori(i+sum(isgrad),:) = [0 0 0];
end
end
% Define the pair of 1st and 2nd coils for each gradiometer
grad.tra = repmat(diag(ones(1,size(grad.coilpos,1)/2),0),1,2);
% for mangetometers change tra as there is no second coil
if any(ismag)
sz_pnt = size(grad.coilpos,1)/2;
% create logical variable
not_2nd_coil = ([diag(zeros(sz_pnt),0)' ismag']~=0);
grad.tra(ismag,not_2nd_coil) = 0;
end
% the gradiometer labels should be consistent with the channel labels in
% read_yokogawa_header, the predefined list of channel names in ft_senslabel
% and with ft_channelselection
% ONLY consistent with read_yokogawa_header as NO FIXED relation between
% channel index and type of channel exists for Yokogawa systems. Therefore
% all have individual label sequences: No useful support in ft_senslabel possible
if ~isempty(label)
grad.label = label(isgrad);
else
% this is only backup, if something goes wrong above.
label = cell(size(isgrad));
for i=1:length(label)
label{i} = sprintf('AG%03d', i);
end
grad.label = label(isgrad);
end
grad.unit = 'cm';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this defines some usefull constants
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles = definehandles
handles.output = [];
handles.sqd_load_flag = false;
handles.mri_load_flag = false;
handles.NullChannel = 0;
handles.MagnetoMeter = 1;
handles.AxialGradioMeter = 2;
handles.PlannerGradioMeter = 3;
handles.RefferenceChannelMark = hex2dec('0100');
handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter );
handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter );
handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter );
handles.TriggerChannel = -1;
handles.EegChannel = -2;
handles.EcgChannel = -3;
handles.EtcChannel = -4;
handles.NonMegChannelNameLength = 32;
handles.DefaultMagnetometerSize = (4.0/1000.0); % ????4.0mm???????`
handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % ???a15.5mm???~??
handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % ????12.0mm???????`
handles.AcqTypeContinuousRaw = 1;
handles.AcqTypeEvokedAve = 2;
handles.AcqTypeEvokedRaw = 3;
handles.sqd = [];
handles.sqd.selected_start = [];
handles.sqd.selected_end = [];
handles.sqd.axialgradiometer_ch_no = [];
handles.sqd.axialgradiometer_ch_info = [];
handles.sqd.axialgradiometer_data = [];
handles.sqd.plannergradiometer_ch_no = [];
handles.sqd.plannergradiometer_ch_info = [];
handles.sqd.plannergradiometer_data = [];
handles.sqd.nullchannel_ch_no = [];
handles.sqd.nullchannel_data = [];
handles.sqd.selected_time = [];
handles.sqd.sample_rate = [];
handles.sqd.sample_count = [];
handles.sqd.pretrigger_length = [];
handles.sqd.matching_info = [];
handles.sqd.source_info = [];
handles.sqd.mri_info = [];
handles.mri = [];
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.