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
philippboehmsturm/antx-master
printstruct.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/utilities/printstruct.m
4,418
utf_8
565d732cbf17defe563a87964b4f1ecb
function str = printstruct(name, val) % PRINTSTRUCT converts a Matlab structure to text which can be % interpreted by Matlab, resulting in the original structure. % 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: printstruct.m 951 2010-04-21 18:24:01Z roboos $ str = []; if isstruct(val) if numel(val)>1 % this function cannot print struct arrays with multiple elements str = sprintf('%s = ''FIXME'';', name); return else % print it as a named structure fn = fieldnames(val); for i=1:length(fn) fv = getfield(val, fn{i}); switch class(fv) case 'char' % line = sprintf('%s = ''%s'';\n', fn{i}, fv); % line = [name '.' line]; line = printstr([name '.' fn{i}], fv); str = [str line]; case {'single' 'double'} line = printmat([name '.' fn{i}], fv); str = [str line]; case {'int8' 'int16' 'int32' 'int64' 'uint8' 'uint16' 'uint32' 'uint64'} line = printmat([name '.' fn{i}], fv); str = [str line]; case 'cell' line = printcell([name '.' fn{i}], fv); str = [str line]; case 'struct' line = printstruct([name '.' fn{i}], fv); str = [str line]; otherwise error('unsupported'); end end end elseif ~isstruct(val) % print it as a named variable switch class(val) case 'char' str = printstr(name, val); case 'double' str = printmat(name, val); case {'int8' 'int16' 'int32' 'int64' 'uint8' 'uint16' 'uint32' 'uint64'} str = printmat(name, val); case 'cell' str = printcell(name, val); otherwise error('unsupported'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = printcell(name, val) str = []; siz = size(val); if isempty(val) str = sprintf('%s = {};\n', name); return; end for i=1:prod(siz) typ{i} = class(val{i}); end for i=2:prod(siz) if ~strcmp(typ{i}, typ{1}) warning('different elements in cell array'); return end end if all(size(val)==1) str = sprintf('%s = { %s };\n', name, printval(val{1})); else str = sprintf('%s = {\n', name); for i=1:siz(1) dum = ''; for j=1:siz(2) dum = [dum ' ' printval(val{i,j})]; end str = sprintf('%s%s\n', str, dum); end str = sprintf('%s};\n', str); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = printmat(name, val) str = []; siz = size(val); if any(size(val)==0) str = sprintf('%s = [];\n', name); elseif all(size(val)==1) str = sprintf('%s = %s;\n', name, printval(val)); elseif size(val,1)==1 dum = sprintf('%g ', str, val(:)); str = sprintf('%s = [%s];\n', name, dum); else str = sprintf('%s = [\n', name); for i=1:siz(1) dum = sprintf('%g ', val(i,:)); str = sprintf('%s %s\n', str, dum); end str = sprintf('%s];\n', str); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = printstr(name, val) str = []; siz = size(val); if siz(1)~=1 str = sprintf('%s = \n', name); for i=1:siz(1) str = [str sprintf(' %s\n', printval(val(i,:)))]; end else str = sprintf('%s = %s;\n', name, printval(val)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = printval(val) str = []; switch class(val) case 'char' str = sprintf('''%s''', val); case 'double' str = sprintf('%g', val); case {'int8' 'int16' 'int32' 'int64' 'uint8' 'uint16' 'uint32' 'uint64'} str = sprintf('%d', val); case 'struct' str = '''FIXME'''; end
github
philippboehmsturm/antx-master
ft_transform_geometry.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/utilities/ft_transform_geometry.m
3,850
utf_8
0810eea6fb2c18145ce615b7f950718a
function [output] = ft_transform_geometry(transform, input) % FT_TRANSFORM_GEOMETRY applies a homogeneous coordinate transformation to % a structure with geometric information. These objects include: % - volume conductor geometry, consisting of a mesh, a set of meshes, a % single sphere, or multiple spheres. % - gradiometer of electrode structure containing sensor positions and % coil orientations (for MEG). % - headshape description containing positions in 3D space. % - sourcemodel description containing positions and optional orientations % in 3D space. % % The units in which the transformation matrix is expressed are assumed to % be the same units as the units in which the geometric object is % expressed. Depending on the input object, the homogeneous transformation % matrix should be limited to a rigid-body translation plus rotation % (MEG-gradiometer array), or to a rigid-body translation plus rotation % plus a global rescaling (volume conductor geometry). % % Use as % output = ft_transform_geometry(transform, input) % Copyright (C) 2011, 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_transform_geometry.m$ checkrotation = ~strcmp(ft_voltype(input), 'unknown') || ft_senstype(input, 'meg'); checkscaling = ~strcmp(ft_voltype(input), 'unknown'); % determine the rotation matrix rotation = eye(4); rotation(1:3,1:3) = transform(1:3,1:3); if any(abs(transform(4,:)-[0 0 0 1])>100*eps) error('invalid transformation matrix'); end if checkrotation % allow for some numerical imprecision if abs(det(rotation)-1)>100*eps error('only a rigid body transformation without rescaling is allowed'); end end if checkscaling % FIXME build in a check for uniform rescaling probably do svd or so % FIXME insert check for nonuniform scaling, should give an error end tfields = {'pos' 'pnt' 'o'}; % apply rotation plus translation rfields = {'ori' 'nrm'}; % only apply rotation mfields = {'transform'}; % plain matrix multiplication recfields = {'fid' 'bnd'}; % recurse into these fields % the field 'r' is not included here, because it applies to a volume % conductor model, and scaling is not allowed, so r will not change. fnames = fieldnames(input); for k = 1:numel(fnames) if any(strcmp(fnames{k}, tfields)) input.(fnames{k}) = apply(transform, input.(fnames{k})); elseif any(strcmp(fnames{k}, rfields)) input.(fnames{k}) = apply(rotation, input.(fnames{k})); elseif any(strcmp(fnames{k}, mfields)) input.(fnames{k}) = transform*input.(fnames{k}); elseif any(strcmp(fnames{k}, recfields)) for j = 1:numel(input.(fnames{k})) input.(fnames{k})(j) = ft_transform_geometry(transform, input.(fnames{k})(j)); end else % do nothing end end output = input; return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that applies the homogeneous transformation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [new] = apply(transform, old) old(:,4) = 1; new = old * transform'; new = new(:,1:3);
github
philippboehmsturm/antx-master
warning_once.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/utilities/private/warning_once.m
3,060
utf_8
f046009e4f6ffe5745af9c5e527614e8
function [ws warned] = warning_once(varargin) % % Use as % warning_once(string) % or % warning_once(string, timeout) % or % warning_once(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. The default timeout value is 60 seconds. % % Can be used instead of the MATLAB built-in function WARNING, thus as % s = warning_once(...) % or % warning_once(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. % In other words, warning_once accepts as an input the same structure it % returns as an output. This returns or restores the states of warnings to % their previous values. % % Can also be used as % [s w] = warning_once(...) % where w is a boolean that indicates whether a warning as been % thrown or not. persistent stopwatch previous if nargin < 1 error('You need to specify at least a warning message'); end warned = false; if isstruct(varargin{1}) warning(varargin{1}); return; end if nargin==3 msgid = varargin{1}; msgstr = varargin{2}; timeout = varargin{3}; elseif nargin==2 msgstr= ''; % this becomes irrelevant msgid = varargin{1}; % this becomes the real msgstr timeout = varargin{2}; elseif nargin==1 msgstr= ''; % this becomes irrelevant msgid = varargin{1}; % this becomes the real msgstr timeout = 60; % default timeout in seconds end if isempty(timeout) error('Timeout ill-specified'); end if isempty(stopwatch) stopwatch = tic; end if isempty(previous) previous = struct; end now = toc(stopwatch); % measure time since first function call fname = fixname([msgid '_' msgstr]); % make a nice string that is allowed as structure fieldname, copy the subfunction from ft_hastoolbox fname = decomma(fname); if length(fname) > 63 % MATLAB max name fname = fname(1:63); end if isfield(previous, fname) && now>previous.(fname).timeout % it has timed out, give the warning again ws = warning(msgid, msgstr); previous.(fname).timeout = now+timeout; previous.(fname).ws = ws; warned = true; elseif ~isfield(previous, fname) % the warning has not been issued before ws = warning(msgid, msgstr); previous.(fname).timeout = now+timeout; previous.(fname).ws = ws; warned = true; else % the warning has been issued before, but has not timed out yet ws = previous.(fname).ws; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out = fixname(toolbox) out = lower(toolbox); out(out=='-') = '_'; % fix dashes out(out==' ') = '_'; % fix spaces out(out=='/') = '_'; % fix forward slashes out(out=='\') = '_'; % fix backward slashes while(out(1) == '_'), out = out(2:end); end; % remove preceding underscore while(out(end) == '_'), out = out(1:end-1); end; % remove subsequent underscore end function nameout = decomma(name) nameout = name; indx = findstr(name,','); nameout(indx)=[]; end
github
philippboehmsturm/antx-master
nanmean.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/utilities/private/nanmean.m
2,121
utf_8
7e0ebd9ca56f2cd79f89031bbccebb9a
% nanmean() - Average, not considering NaN values % % Usage: same as mean() % Author: Arnaud Delorme, CNL / Salk Institute, 16 Oct 2002 %123456789012345678901234567890123456789012345678901234567890123456789012 % 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 % 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: nanmean.m 2885 2011-02-16 09:41:58Z roboos $ function out = nanmean(in, dim) if nargin < 1 help nanmean; return; end; if nargin < 2 if size(in,1) ~= 1 dim = 1; elseif size(in,2) ~= 1 dim = 2; else dim = 3; end; end; tmpin = in; tmpin(find(isnan(in(:)))) = 0; out = sum(tmpin, dim) ./ sum(~isnan(in),dim);
github
philippboehmsturm/antx-master
ft_plot_slice.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/plotting/ft_plot_slice.m
6,993
utf_8
226f857d7fa8bca676385baa261dd08e
function [h, T2] = ft_plot_slice(dat, varargin) % FT_PLOT_SLICE cuts a 2-D slice from a 3-D volume and interpolates % if necessary % % Use as % ft_plot_slice(dat, ...) % % Additional options should be specified in key-value pairs and can be % 'transform' a 4x4 homogeneous transformation matrix specifying the mapping from % voxel space to the coordinate system in which the data are plotted. % 'location' a 1x3 vector specifying a point on the plane which will be plotted % the coordinates are expressed in the coordinate system in which the % data will be plotted. location defines the origin of the plane % 'orientation' a 1x3 vector specifying the direction orthogonal through the plane % which will be plotted. % 'datmask' a 3D-matrix with the same size as the matrix dat, serving as opacitymap % 'interpmethod' a string specifying the method for the interpolation, default = 'nearest' % see INTERPN % 'colormap' % 'style' 'flat' or '3D' % % 'interplim' % Copyrights (C) 2010, 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_plot_slice.m 2968 2011-02-26 13:46:32Z jansch $ persistent previous_dim X Y Z; transform = keyval('transform', varargin); loc = keyval('location', varargin); ori = keyval('orientation', varargin); if isempty(ori), ori = [0 0 1]; end; resolution = keyval('resolution', varargin); if isempty(resolution), resolution = 1; end; mask = keyval('datmask', varargin); interpmethod = keyval('interpmethod', varargin); if isempty(interpmethod), interpmethod = 'nearest'; end cmap = keyval('colormap', varargin); if ~strcmp(class(dat), 'double'), dat = cast(dat, 'double'); end % norm normalise the ori vector ori = ori./sqrt(sum(ori.^2)); % dimensionality of the input data dim = size(dat); if isempty(previous_dim), previous_dim = [0 0 0]; end % set the location if empty if isempty(loc) && (isempty(transform) || all(all(transform-eye(4)==0)==1)) loc = dim./2; elseif isempty(loc) loc = [0 0 0]; end % set the transformation matrix if empty if isempty(transform) transform = eye(4); end % check whether mask is ok domask = ~isempty(mask); if domask, if ~all(dim==size(mask)), error('the mask data should have the same dimensionality as the functional data'); end end % determine whether interpolation is needed dointerp = false; if ~dointerp && sum(sum(transform-eye(4)))~=0, dointerp = true; end if ~dointerp && ~all(round(loc)==loc), dointerp = true; end if ~dointerp && sum(ori)~=1, dointerp = true; end if ~dointerp && ~(resolution==round(resolution)), dointerp = true; end % determine the caller function and toggle dointerp to true, if % ft_plot_slice has been called from ft_plot_montage % this is necessary for the correct allocation of the persistent variables st = dbstack; if ~dointerp && strcmp(st(2).name, 'ft_plot_montage'), dointerp = true; end if dointerp %--------cut a slice using interpn % get voxel indices if all(dim==previous_dim) % for speeding up the plotting on subsequent calls % use persistent variables X Y Z else [X, Y, Z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3)); end % define 'x' and 'y' axis in projection plane. % this is more or less arbitrary [x, y] = projplane(ori); m = max(dim)./1; xplane = -m:resolution:m; yplane = -m:resolution:m; zplane = 0; [X2,Y2,Z2] = ndgrid(xplane, yplane, zplane); %2D cartesian grid of projection plane in plane voxels siz = size(squeeze(X2)); pos = [X2(:) Y2(:) Z2(:)]; clear X2 Y2 Z2; % get the transformation matrix from plotting space to voxel space T1 = inv(transform); % get the transformation matrix from to get the projection plane at the right location and orientation into plotting space. T2 = [x(:) y(:) ori(:) loc(:); 0 0 0 1]; % get the transformation matrix from projection plane to voxel space M = T1*T2; pos = warp_apply(M, pos); % gives the positions of the required plane in voxel space Xi = reshape(pos(:,1), siz); Yi = reshape(pos(:,2), siz); Zi = reshape(pos(:,3), siz); V = interpn(X,Y,Z,dat,Xi,Yi,Zi,interpmethod); [V,Xi,Yi,Zi] = tight(V,Xi,Yi,Zi); siz = size(Xi); if domask, Vmask = tight(interpn(X,Y,Z,mask,Xi,Yi,Zi,interpmethod)); end else %-------cut a slice without interpolation [x, y] = projplane(ori); T2 = [x(:) y(:) ori(:) loc(:); 0 0 0 1]; if all(ori==[1 0 0]), xplane = loc(1); yplane = 1:dim(2); zplane = 1:dim(3); end if all(ori==[0 1 0]), xplane = 1:dim(1); yplane = loc(2); zplane = 1:dim(3); end if all(ori==[0 0 1]), xplane = 1:dim(1); yplane = 1:dim(2); zplane = loc(3); end [Xi,Yi,Zi] = ndgrid(xplane, yplane, zplane); siz = size(squeeze(Xi)); Xi = reshape(Xi, siz); Yi = reshape(Yi, siz); Zi = reshape(Zi, siz); V = reshape(dat(xplane, yplane, zplane), siz); if domask, Vmask = mask(xplane, yplane, zplane); end end % get positions of the plane in plotting space posh = warp_apply(transform, [Xi(:) Yi(:) Zi(:)], 'homogeneous', 1e-8); Xh = reshape(posh(:,1), siz); Yh = reshape(posh(:,2), siz); Zh = reshape(posh(:,3), siz); if isempty(cmap), %treat as gray value: scale and convert to rgb dmin = min(dat(:)); dmax = max(dat(:)); V = (V-dmin)./(dmax-dmin); V(isnan(V)) = 0; clear dmin dmax; % convert anatomy into RGB values V = cat(3, V, V, V); end h = surface(Xh, Yh, Zh, V); set(h, 'linestyle', 'none'); if domask, set(h, 'FaceAlpha', 'flat'); set(h, 'AlphaDataMapping', 'scaled'); set(h, 'AlphaData', Vmask); end if ~isempty(cmap) colormap(cmap); end % store for future reference previous_dim = dim; function [x, y] = projplane(z) [u,s,v] = svd([eye(3) z(:)]); x = u(:,2)'; y = u(:,3)'; function [V,Xi,Yi,Zi] = tight(V,Xi,Yi,Zi) % cut off the nans at the edges x = sum(~isfinite(V),1)<size(V,1); y = sum(~isfinite(V),2)<size(V,2); V = V(y,x); if nargin>1, Xi = Xi(y,x); end if nargin>2, Yi = Yi(y,x); end if nargin>3, Zi = Zi(y,x); end
github
philippboehmsturm/antx-master
ft_select_range.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/plotting/ft_select_range.m
8,056
utf_8
9c9b96f6d9fa1e6df6e589bb084c51e8
function ft_select_range(handle, eventdata, varargin) % FT_SELECT_RANGE is a helper function that can be used as callback function % in a figure. It allows the user to select a horizontal or a vertical % range, or one or multiple boxes. % % Example % x = randn(10,1); % y = randn(10,1); % figure; plot(x, y, '.'); % % set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}); % set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonUpFcn'}); % set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonMotionFcn'}); % % set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'multiple', false, 'xrange', false, 'yrange', false, 'callback', @disp, 'event', 'WindowButtonDownFcn'}); % set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'multiple', false, 'xrange', false, 'yrange', false, 'callback', @disp, 'event', 'WindowButtonUpFcn'}); % set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'multiple', false, 'xrange', false, 'yrange', false, 'callback', @disp, 'event', 'WindowButtonMotionFcn'}); % Copyright (C) 2009, 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_select_range.m 3389 2011-04-26 13:58:48Z vlalit $ % get the optional arguments event = keyval('event', varargin); callback = keyval('callback', varargin); multiple = keyval('multiple', varargin); if isempty(multiple), multiple = false; end xrange = keyval('xrange', varargin); if isempty(xrange), xrange = true; end yrange = keyval('yrange', varargin); if isempty(yrange), yrange = true; end clear = keyval('clear', varargin); if isempty(clear), clear = false; end contextmenu = keyval('contextmenu', varargin); % this will be displayed following a right mouse click % convert 'yes/no' string to boolean value multiple = istrue(multiple); xrange = istrue(xrange); yrange = istrue(yrange); p = handle; while ~isequal(p, 0) handle = p; p = get(handle, 'parent'); end if ishandle(handle) userData = getappdata(handle, 'select_range_m'); else userData = []; end if isempty(userData) userData.range = []; % this is a Nx4 matrix with the selection range userData.box = []; % this is a Nx1 vector with the line handle end p = get(gca, 'CurrentPoint'); p = p(1,1:2); abc = axis; xLim = abc(1:2); yLim = abc(3:4); % limit cursor coordinates if p(1)<xLim(1), p(1)=xLim(1); end; if p(1)>xLim(2), p(1)=xLim(2); end; if p(2)<yLim(1), p(2)=yLim(1); end; if p(2)>yLim(2), p(2)=yLim(2); end; % determine whether the user is currently making a selection selecting = numel(userData.range)>0 && any(isnan(userData.range(end,:))); pointonly = ~xrange && ~yrange; if pointonly && multiple warning('multiple selections are not possible for a point'); multiple = false; end switch lower(event) case lower('WindowButtonDownFcn') if inSelection(p, userData.range) % the user has clicked in one of the existing selections evalCallback(callback, userData.range); if clear delete(userData.box(ishandle(userData.box))); userData.range = []; userData.box = []; set(handle, 'Pointer', 'crosshair'); end else if ~multiple % start with a new selection delete(userData.box(ishandle(userData.box))); userData.range = []; userData.box = []; end % add a new selection range userData.range(end+1,1:4) = nan; userData.range(end,1) = p(1); userData.range(end,3) = p(2); % add a new selection box xData = [nan nan nan nan nan]; yData = [nan nan nan nan nan]; userData.box(end+1) = line(xData, yData); end case lower('WindowButtonUpFcn') if selecting % select the other corner of the box userData.range(end,2) = p(1); userData.range(end,4) = p(2); end if multiple && ~isempty(userData.range) && ~diff(userData.range(end,1:2)) && ~diff(userData.range(end,3:4)) % start with a new selection delete(userData.box(ishandle(userData.box))); userData.range = []; userData.box = []; end if ~isempty(userData.range) % ensure that the selection is sane if diff(userData.range(end,1:2))<0 userData.range(end,1:2) = userData.range(end,[2 1]); end if diff(userData.range(end,3:4))<0 userData.range(end,3:4) = userData.range(end,[4 3]); end if pointonly % only select a single point userData.range(end,2) = userData.range(end,1); userData.range(end,4) = userData.range(end,3); elseif ~xrange % only select along the y-axis userData.range(end,1:2) = [-inf inf]; elseif ~yrange % only select along the x-axis userData.range(end,3:4) = [-inf inf]; end end if pointonly && ~multiple evalCallback(callback, userData.range); if clear delete(userData.box(ishandle(userData.box))); userData.range = []; userData.box = []; set(handle, 'Pointer', 'crosshair'); end end case lower('WindowButtonMotionFcn') if selecting && ~pointonly % update the selection box if xrange x1 = userData.range(end,1); x2 = p(1); else x1 = xLim(1); x2 = xLim(2); end if yrange y1 = userData.range(end,3); y2 = p(2); else y1 = yLim(1); y2 = yLim(2); end xData = [x1 x2 x2 x1 x1]; yData = [y1 y1 y2 y2 y1]; set(userData.box(end), 'xData', xData); set(userData.box(end), 'yData', yData); set(userData.box(end), 'Color', [0 0 0]); set(userData.box(end), 'EraseMode', 'xor'); set(userData.box(end), 'LineStyle', '--'); set(userData.box(end), 'LineWidth', 1.5); set(userData.box(end), 'Visible', 'on'); else % update the cursor if inSelection(p, userData.range) set(handle, 'Pointer', 'hand'); else set(handle, 'Pointer', 'crosshair'); end end otherwise error('unexpected event "%s"', event); end % switch event % put the modified selections back into the figure if ishandle(handle) setappdata(handle, 'select_range_m', userData); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function retval = inSelection(p, range) if isempty(range) retval = false; else retval = (p(1)>=range(:,1) & p(1)<=range(:,2) & p(2)>=range(:,3) & p(2)<=range(:,4)); retval = any(retval); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function evalCallback(callback, val) if ~isempty(callback) if isa(callback, 'cell') % the callback specifies a function and additional arguments funhandle = callback{1}; funargs = callback(2:end); feval(funhandle, val, funargs{:}); else % the callback only specifies a function funhandle = callback; feval(funhandle, val); end end
github
philippboehmsturm/antx-master
ft_select_channel.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/plotting/ft_select_channel.m
5,797
utf_8
4c90523b87dbe7921b8e5e96364644e2
function ft_select_channel(handle, eventdata, varargin) % FT_SELECT_CHANNEL is a helper function that can be used as callback function % in a figure. It allows the user to select a channel. The channel labels % are returned. % % Use as % label = ft_select_channel(h, eventdata, ...) % The first two arguments are automatically passed by Matlab to any % callback function. % % Additional options should be specified in key-value pairs and can be % 'callback' = function handle to be executed after channels have been selected % % You can pass additional arguments to the callback function in a cell-array % like {@function_handle,arg1,arg2} % % Example % % create a figure % lay = ft_prepare_layout([]) % ft_plot_lay(lay) % % % add the required guidata % info = guidata(gcf) % info.x = lay.pos(:,1); % info.y = lay.pos(:,2); % info.label = lay.label % guidata(gcf, info) % % % add this function as the callback to make a single selection % set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'callback', @disp}) % % % or to make multiple selections % set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}) % set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}) % set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}) % % Subsequently you can click in the figure and you'll see that the disp % function is executed as callback and that it displays the selected % channels. % Copyright (C) 2009, 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_select_channel.m 3866 2011-07-18 15:31:48Z craric $ % get optional input arguments multiple = keyval('multiple', varargin); if isempty(multiple), multiple = false; end callback = keyval('callback', varargin); % convert 'yes/no' string to boolean value multiple = istrue(multiple); if multiple % the selection is done using select_range, which will subsequently call select_channel_multiple set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'multiple', true, 'callback', {@select_channel_multiple, callback}, 'event', 'WindowButtonDownFcn'}); set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'multiple', true, 'callback', {@select_channel_multiple, callback}, 'event', 'WindowButtonUpFcn'}); set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'multiple', true, 'callback', {@select_channel_multiple, callback}, 'event', 'WindowButtonMotionFcn'}); else % the selection is done using select_channel_single pos = get(gca, 'CurrentPoint'); pos = pos(1,1:2); select_channel_single(pos, callback) end % if multiple %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to assist in the selection of a single channel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_channel_single(pos, callback) info = guidata(gcf); x = info.x; y = info.y; label = info.label; % compute a tolerance measure distance = sqrt(abs(sum([x y]'.*[x y]',1))); distance = triu(distance, 1); distance = distance(:); distance = distance(distance>0); distance = median(distance); tolerance = 0.3*distance; % compute the distance between the clicked point and all channels dx = x - pos(1); dy = y - pos(2); dd = sqrt(dx.^2 + dy.^2); [d, i] = min(dd); if d<tolerance label = label{i}; fprintf('channel "%s" selected\n', label); else label = {}; fprintf('no channel selected\n'); end % execute the original callback with the selected channel as input argument if ~isempty(callback) if isa(callback, 'cell') % the callback specifies a function and additional arguments funhandle = callback{1}; funargs = callback(2:end); feval(funhandle, label, funargs{:}); else % the callback only specifies a function funhandle = callback; feval(funhandle, label); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to assist in the selection of multiple channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_channel_multiple(range, callback) info = guidata(gcf); x = info.x(:); y = info.y(:); label = info.label(:); % determine which channels ly in the selected range select = false(size(label)); for i=1:size(range,1) select = select | (x>=range(i, 1) & x<=range(i, 2) & y>=range(i, 3) & y<=range(i, 4)); end label = label(select); % execute the original callback with the selected channels as input argument if any(select) if ~isempty(callback) if isa(callback, 'cell') % the callback specifies a function and additional arguments funhandle = callback{1}; funargs = callback(2:end); feval(funhandle, label, funargs{:}); else % the callback only specifies a function funhandle = callback; feval(funhandle, label); end end end
github
philippboehmsturm/antx-master
ft_apply_montage.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/plotting/private/ft_apply_montage.m
9,812
utf_8
c30fdecc34ab9678cc26828eea0538c1
function [sens] = ft_apply_montage(sens, montage, varargin) % FT_APPLY_MONTAGE changes the montage of an electrode or gradiometer array. A % montage can be used for EEG rereferencing, MEG synthetic gradients, MEG % planar gradients or unmixing using ICA. This function applies the montage % to the sensor array. The sensor array can subsequently be used for % forward computation and source reconstruction of the data. % % Use as % [sens] = ft_apply_montage(sens, montage, ...) % [data] = ft_apply_montage(data, montage, ...) % [montage] = ft_apply_montage(montage1, montage2, ...) % where the input is a FieldTrip sensor definition as obtained from FT_READ_SENS % or a FieldTrip raw data structure as obtained from FT_PREPROCESSING. % % A montage is specified as a structure with the fields % montage.tra = MxN matrix % montage.labelnew = Mx1 cell-array % montage.labelorg = Nx1 cell-array % % Additional options should be specified in key-value pairs and can be % 'keepunused' string, 'yes' or 'no' (default = 'no') % 'inverse' string, 'yes' or 'no' (default = 'no') % % If the first input is a montage, then the second input montage will be % applied to the first. In effect the resulting montage will first do % montage1, then montage2. % % See also FT_READ_SENS, FT_TRANSFORM_SENS % Copyright (C) 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: ft_apply_montage.m 3392 2011-04-27 10:26:53Z jansch $ % get optional input arguments keepunused = keyval('keepunused', varargin); if isempty(keepunused), keepunused = 'no'; end inverse = keyval('inverse', varargin); if isempty(inverse), inverse = 'no'; end feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'text'; end bname = keyval('balancename', varargin); if isempty(bname), bname = ''; end % check the consistency of the input sensor array or data if isfield(sens, 'labelorg') && isfield(sens, 'labelnew') % the input data structure is also a montage, i.e. apply the montages sequentially sens.label = sens.labelnew; end % check the consistency of the montage if size(montage.tra,1)~=length(montage.labelnew) error('the number of channels in the montage is inconsistent'); elseif size(montage.tra,2)~=length(montage.labelorg) error('the number of channels in the montage is inconsistent'); end if strcmp(inverse, 'yes') % apply the inverse montage, i.e. undo a previously applied montage tmp.labelnew = montage.labelorg; % swap around tmp.labelorg = montage.labelnew; % swap around tmp.tra = full(montage.tra); if rank(tmp.tra) < length(tmp.tra) warning('the linear projection for the montage is not full-rank, the resulting data will have reduced dimensionality'); tmp.tra = pinv(tmp.tra); else tmp.tra = inv(tmp.tra); end montage = tmp; end % use default transfer from sensors to channels if not specified if isfield(sens, 'pnt') && ~isfield(sens, 'tra') nchan = size(sens.pnt,1); sens.tra = sparse(eye(nchan)); end % select and keep the columns that are non-empty, i.e. remove the empty columns selcol = find(~all(montage.tra==0, 1)); montage.tra = montage.tra(:,selcol); montage.labelorg = montage.labelorg(selcol); clear selcol % select and remove the columns corresponding to channels that are not present in the original data remove = setdiff(montage.labelorg, intersect(montage.labelorg, sens.label)); selcol = match_str(montage.labelorg, remove); % we cannot just remove the colums, all rows that depend on it should also be removed selrow = false(length(montage.labelnew),1); for i=1:length(selcol) selrow = selrow & (montage.tra(:,selcol(i))~=0); end % convert from indices to logical vector selcol = indx2logical(selcol, length(montage.labelorg)); % remove rows and columns montage.labelorg = montage.labelorg(~selcol); montage.labelnew = montage.labelnew(~selrow); montage.tra = montage.tra(~selrow, ~selcol); clear remove selcol selrow i % add columns for the channels that are present in the data but not involved in the montage, and stick to the original order in the data [add, ix] = setdiff(sens.label, montage.labelorg); add = sens.label(sort(ix)); m = size(montage.tra,1); n = size(montage.tra,2); k = length(add); if strcmp(keepunused, 'yes') % add the channels that are not rereferenced to the input and output montage.tra((m+(1:k)),(n+(1:k))) = eye(k); montage.labelorg = cat(1, montage.labelorg(:), add(:)); montage.labelnew = cat(1, montage.labelnew(:), add(:)); else % add the channels that are not rereferenced to the input montage only montage.tra(:,(n+(1:k))) = zeros(m,k); montage.labelorg = cat(1, montage.labelorg(:), add(:)); end clear add m n k % determine whether all channels are unique m = size(montage.tra,1); n = size(montage.tra,2); if length(unique(montage.labelnew))~=m error('not all output channels of the montage are unique'); end if length(unique(montage.labelorg))~=n error('not all input channels of the montage are unique'); end % determine whether all channels that have to be rereferenced are available if length(intersect(sens.label, montage.labelorg))~=length(montage.labelorg) error('not all channels that are required in the montage are available in the data'); end % reorder the columns of the montage matrix [selsens, selmont] = match_str(sens.label, montage.labelorg); montage.tra = double(sparse(montage.tra(:,selmont))); montage.labelorg = montage.labelorg(selmont); if isfield(sens, 'labelorg') && isfield(sens, 'labelnew') % apply the montage on top of the other montage sens = rmfield(sens, 'label'); if isa(sens.tra, 'single') sens.tra = full(montage.tra) * sens.tra; else sens.tra = montage.tra * sens.tra; end sens.labelnew = montage.labelnew; elseif isfield(sens, 'tra') % apply the montage to the sensor array if isa(sens.tra, 'single') sens.tra = full(montage.tra) * sens.tra; else sens.tra = montage.tra * sens.tra; end sens.label = montage.labelnew; % keep track of the order of the balancing and which one is the current % one if strcmp(inverse, 'yes') if isfield(sens, 'balance')% && isfield(sens.balance, 'previous') if isfield(sens.balance, 'previous') && numel(sens.balance.previous)>=1 sens.balance.current = sens.balance.previous{1}; sens.balance.previous = sens.balance.previous(2:end); elseif isfield(sens.balance, 'previous') sens.balance.current = 'none'; sens.balance = rmfield(sens.balance, 'previous'); else sens.balance.current = 'none'; end end elseif ~strcmp(inverse, 'yes') && ~isempty(bname) if isfield(sens, 'balance') && isfield(sens.balance, 'current') if ~isfield(sens.balance, 'previous') sens.balance.previous = {}; end sens.balance.previous = [{sens.balance.current} sens.balance.previous]; sens.balance.current = bname; sens.balance.(bname) = montage; end end elseif isfield(sens, 'trial') % apply the montage to the raw data that was preprocessed using fieldtrip data = sens; clear sens Ntrials = numel(data.trial); ft_progress('init', feedback, 'processing trials'); for i=1:Ntrials ft_progress(i/Ntrials, 'processing trial %d from %d\n', i, Ntrials); if isa(data.trial{i}, 'single') % sparse matrices and single precision do not match data.trial{i} = full(montage.tra) * data.trial{i}; else data.trial{i} = montage.tra * data.trial{i}; end end ft_progress('close'); data.label = montage.labelnew; % rename the output variable sens = data; clear data elseif isfield(sens, 'fourierspctrm') % apply the montage to the spectrally decomposed data freq = sens; clear sens if strcmp(freq.dimord, 'rpttap_chan_freq') siz = size(freq.fourierspctrm); nrpt = siz(1); nchan = siz(2); nfreq = siz(3); output = zeros(nrpt, size(montage.tra,1), nfreq); for foilop=1:nfreq output(:,:,foilop) = freq.fourierspctrm(:,:,foilop) * montage.tra'; end elseif strcmp(freq.dimord, 'rpttap_chan_freq_time') siz = size(freq.fourierspctrm); nrpt = siz(1); nchan = siz(2); nfreq = siz(3); ntime = siz(4); output = zeros(nrpt, size(montage.tra,1), nfreq, ntime); for foilop=1:nfreq for toilop = 1:ntime output(:,:,foilop,toilop) = freq.fourierspctrm(:,:,foilop,toilop) * montage.tra'; end end else error('unsupported dimord in frequency data (%s)', freq.dimord); end % replace the Fourier spectrum freq.fourierspctrm = output; freq.label = montage.labelnew; % rename the output variable sens = freq; clear freq else error('unrecognized input'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = indx2logical(x, n) y = false(1,n); y(x) = true;
github
philippboehmsturm/antx-master
select3dtool.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/plotting/private/select3dtool.m
2,713
utf_8
fdf7d572638e6ebd059c63f233d26704
function select3dtool(arg) %SELECT3DTOOL A simple tool for interactively obtaining 3-D coordinates % % SELECT3DTOOL(FIG) Specify figure handle % % Example: % surf(peaks); % select3dtool; % % click on surface if nargin<1 arg = gcf; end if ~ishandle(arg) feval(arg); return; end %% initialize gui %% fig = arg; figure(fig); uistate = uiclearmode(fig); [tool, htext] = createUI; hmarker1 = line('marker','o','markersize',10,'markerfacecolor','k','erasemode','xor','visible','off'); hmarker2 = line('marker','o','markersize',10,'markerfacecolor','r','erasemode','xor','visible','off'); state.uistate = uistate; state.text = htext; state.tool = tool; state.fig = fig; state.marker1 = hmarker1; state.marker2 = hmarker2; setappdata(fig,'select3dtool',state); setappdata(state.tool,'select3dhost',fig); set(fig,'windowbuttondownfcn','select3dtool(''click'')'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function off state = getappdata(gcbf,'select3dtool'); if ~isempty(state) delete(state.tool); end fig = getappdata(gcbf,'select3dhost'); if ~isempty(fig) & ishandle(fig) state = getappdata(fig,'select3dtool'); uirestore(state.uistate); delete(state.marker1); delete(state.marker2); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function click [p v vi] = select3d; state = getappdata(gcbf,'select3dtool'); if ~ishandle(state.text) state.text = createUI; end if ~ishandle(state.marker1) state.marker1 = []; end if ~ishandle(state.marker2) state.marker2 = []; end setappdata(state.fig,'select3dtool',state); if isempty(v) v = [nan nan nan]; vi = nan; set(state.marker2,'visible','off'); else set(state.marker2,'visible','on','xdata',v(1),'ydata',v(2),'zdata',v(3)); end if isempty(p) p = [nan nan nan]; set(state.marker1,'visible','off'); else set(state.marker1,'visible','on','xdata',p(1),'ydata',p(2),'zdata',p(3)); end % Update tool and markers set(state.text,'string',createString(p(1),p(2),p(3),v(1),v(2),v(3),vi)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fig, h] = createUI pos = [200 200 200 200]; % Create selection tool % fig = figure('handlevisibility','off','menubar','none','resize','off',... 'numbertitle','off','name','Select 3-D Tool','position',pos,'deletefcn','select3dtool(''off'')'); h = uicontrol('style','text','parent',fig,'string',createString(0,0,0,0,0,0,0),... 'units','norm','position',[0 0 1 1],'horizontalalignment','left'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [str] = createString(px,py,pz,vx,vy,vz,vi) str = sprintf(' Position:\n X %f\n Y: %f\n Z: %f \n\n Vertex:\n X: %f\n Y: %f\n Z: %f \n\n Vertex Index:\n %d',px,py,pz,vx,vy,vz,vi);
github
philippboehmsturm/antx-master
inside_contour.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/plotting/private/inside_contour.m
1,106
utf_8
37d10e5d9a05c79551aac24c328e34aa
function bool = inside_contour(pos, contour); npos = size(pos,1); ncnt = size(contour,1); x = pos(:,1); y = pos(:,2); minx = min(x); miny = min(y); maxx = max(x); maxy = max(y); bool = true(npos,1); bool(x<minx) = false; bool(y<miny) = false; bool(x>maxx) = false; bool(y>maxy) = false; % the summed angle over the contour is zero if the point is outside, and 2*pi if the point is inside the contour % leave some room for inaccurate f critval = 0.1; % the remaining points have to be investigated with more attention sel = find(bool); for i=1:length(sel) contourx = contour(:,1) - pos(sel(i),1); contoury = contour(:,2) - pos(sel(i),2); angle = atan2(contoury, contourx); % angle = unwrap(angle); angle = my_unwrap(angle); total = sum(diff(angle)); bool(sel(i)) = (abs(total)>critval); end function x = my_unwrap(x) % this is a faster implementation of the MATLAB unwrap function % with hopefully the same functionality d = diff(x); indx = find(abs(d)>pi); for i=indx(:)' if d(i)>0 x((i+1):end) = x((i+1):end) - 2*pi; else x((i+1):end) = x((i+1):end) + 2*pi; end end
github
philippboehmsturm/antx-master
ft_specest_mtmconvol.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/specest/ft_specest_mtmconvol.m
17,419
utf_8
c6cfb36cc212009ed5bc834211e299aa
function [spectrum,ntaper,freqoi,timeoi] = ft_specest_mtmconvol(dat, time, varargin) % SPECEST_MTMCONVOL performs wavelet convolution in the time domain % by multiplication in the frequency domain % % Use as % [spectrum,freqoi,timeoi] = specest_mtmconvol(dat,time,...) % where % dat = matrix of chan*sample % time = vector, containing time in seconds for each sample % spectrum = matrix of ntaper*chan*freqoi*timeoi of fourier coefficients % ntaper = vector containing the number of tapers per freqoi % freqoi = vector of frequencies in spectrum % timeoi = vector of timebins in spectrum % % Optional arguments should be specified in key-value pairs and can include: % taper = 'dpss', 'hanning' or many others, see WINDOW (default = 'dpss') % pad = number, indicating time-length of data to be padded out to in seconds % timeoi = vector, containing time points of interest (in seconds) % timwin = vector, containing length of time windows (in seconds) % freqoi = vector, containing frequencies (in Hz) % tapsmofrq = number, the amount of spectral smoothing through multi-tapering. Note: 4 Hz smoothing means plus-minus 4 Hz, i.e. a 8 Hz smoothing box % dimord = 'tap_chan_freq_time' (default) or 'chan_time_freqtap' for % memory efficiency % verbose = output progress to console (0 or 1, default 1) % % See also SPECEST_MTMFFT, SPECEST_CONVOL, SPECEST_HILBERT, SPECEST_WAVELET % Copyright (C) 2010, Donders Institute for Brain, Cognition and Behaviour % % $Log$ % get the optional input arguments keyvalcheck(varargin, 'optional', {'taper','pad','timeoi','timwin','freqoi','tapsmofrq','dimord','feedback','verbose','polyremoval'}); taper = keyval('taper', varargin); if isempty(taper), taper = 'dpss'; end pad = keyval('pad', varargin); timeoi = keyval('timeoi', varargin); if isempty(timeoi), timeoi = 'all'; end timwin = keyval('timwin', varargin); freqoi = keyval('freqoi', varargin); if isempty(freqoi), freqoi = 'all'; end tapsmofrq = keyval('tapsmofrq', varargin); dimord = keyval('dimord', varargin); if isempty(dimord), dimord = 'tap_chan_freq_time'; end fbopt = keyval('feedback', varargin); verbose = keyval('verbose', varargin); if isempty(verbose), verbose = 1; end polyorder = keyval('polyremoval', varargin); if isempty(polyorder), polyorder = 1; end if isempty(fbopt), fbopt.i = 1; fbopt.n = 1; end % throw errors for required input if isempty(tapsmofrq) && strcmp(taper, 'dpss') error('you need to specify tapsmofrq when using dpss tapers') end if isempty(timwin) error('you need to specify timwin') elseif (length(timwin) ~= length(freqoi) && ~strcmp(freqoi,'all')) error('timwin should be of equal length as freqoi') end % Set n's [nchan,ndatsample] = size(dat); % Remove polynomial fit from the data -> default is demeaning if polyorder >= 0 dat = ft_preproc_polyremoval(dat, polyorder, 1, ndatsample); end % Determine fsample and set total time-length of data fsample = 1/(time(2)-time(1)); dattime = ndatsample / fsample; % total time in seconds of input data % Zero padding if round(pad * fsample) < ndatsample error('the padding that you specified is shorter than the data'); end if isempty(pad) % if no padding is specified padding is equal to current data length pad = dattime; end postpad = zeros(1,round((pad - dattime) * fsample)); endnsample = round(pad * fsample); % total number of samples of padded data endtime = pad; % total time in seconds of padded data % Set freqboi and freqoi if isnumeric(freqoi) % if input is a vector freqboi = round(freqoi ./ (fsample ./ endnsample)) + 1; freqboi = unique(freqboi); freqoi = (freqboi-1) ./ endtime; % boi - 1 because 0 Hz is included in fourier output elseif strcmp(freqoi,'all') freqboilim = round([0 fsample/2] ./ (fsample ./ endnsample)) + 1; freqboi = freqboilim(1):1:freqboilim(2); freqoi = (freqboi-1) ./ endtime; end % check for freqoi = 0 and remove it, there is no wavelet for freqoi = 0 if freqoi(1)==0 freqoi(1) = []; freqboi(1) = []; if length(timwin) == (length(freqoi) + 1) timwin(1) = []; end end nfreqboi = length(freqboi); nfreqoi = length(freqoi); % Set timeboi and timeoi offset = round(time(1)*fsample); if isnumeric(timeoi) % if input is a vector timeboi = round(timeoi .* fsample - offset) + 1; ntimeboi = length(timeboi); timeoi = round(timeoi .* fsample) ./ fsample; elseif strcmp(timeoi,'all') % if input was 'all' timeboi = 1:length(time); ntimeboi = length(timeboi); timeoi = time; end % set number of samples per time-window (timwin is in seconds) timwinsample = round(timwin .* fsample); % Compute tapers per frequency, multiply with wavelets and compute their fft wltspctrm = cell(nfreqoi,1); ntaper = zeros(nfreqoi,1); for ifreqoi = 1:nfreqoi switch taper case 'dpss' % create a sequence of DPSS tapers, ensure that the input arguments are double precision tap = double_dpss(timwinsample(ifreqoi), timwinsample(ifreqoi) .* (tapsmofrq(ifreqoi) ./ fsample))'; % remove the last taper because the last slepian taper is always messy tap = tap(1:(end-1), :); % give error/warning about number of tapers if isempty(tap) error('%.3f Hz: datalength to short for specified smoothing\ndatalength: %.3f s, smoothing: %.3f Hz, minimum smoothing: %.3f Hz',freqoi(ifreqoi), timwinsample(ifreqoi)/fsample,tapsmofrq(ifreqoi),fsample/timwinsample(ifreqoi)); elseif size(tap,1) == 1 disp([num2str(freqoi(ifreqoi)) ' Hz: WARNING: using only one taper for specified smoothing']) end case 'sine' % create and remove the last taper tap = sine_taper(timwinsample(ifreqoi), timwinsample(ifreqoi) .* (tapsmofrq(ifreqoi) ./ fsample))'; tap = tap(1:(end-1), :); case 'sine_old' % to provide compatibility with the tapers being scaled (which was default % behavior prior to 29apr2011) yet this gave different magnitude of power % when comparing with slepian multi tapers tap = sine_taper_scaled(timwinsample(ifreqoi), timwinsample(ifreqoi) .* (tapsmofrq(ifreqoi) ./ fsample))'; tap = tap(1:(end-1), :); % remove the last taper case 'alpha' tap = alpha_taper(timwinsample(ifreqoi), freqoi(ifreqoi)./ fsample)'; tap = tap./norm(tap)'; case 'hanning' tap = hanning(timwinsample(ifreqoi))'; tap = tap./norm(tap, 'fro'); otherwise % create a single taper according to the window specification as a replacement for the DPSS (Slepian) sequence tap = window(taper, timwinsample(ifreqoi))'; tap = tap ./ norm(tap,'fro'); % make it explicit that the frobenius norm is being used end % set number of tapers ntaper(ifreqoi) = size(tap,1); % Wavelet construction tappad = ceil(endnsample ./ 2) - floor(timwinsample(ifreqoi) ./ 2); prezero = zeros(1,tappad); postzero = zeros(1,round(endnsample) - ((tappad-1) + timwinsample(ifreqoi))-1); % phase consistency: cos must always be 1 and sin must always be centered in upgoing flank, so the centre of the wavelet (untapered) has angle = 0 anglein = (-(timwinsample(ifreqoi)-1)/2 : (timwinsample(ifreqoi)-1)/2)' .* ((2.*pi./fsample) .* freqoi(ifreqoi)); wltspctrm{ifreqoi} = complex(zeros(size(tap,1),round(endnsample))); for itap = 1:ntaper(ifreqoi) try % this try loop tries to fit the wavelet into wltspctrm, when its length is smaller than ndatsample, the rest is 'filled' with zeros because of above code % if a wavelet is longer than ndatsample, it doesn't fit and it is kept at zeros, which is translated to NaN's in the output % construct the complex wavelet coswav = horzcat(prezero, tap(itap,:) .* cos(anglein)', postzero); sinwav = horzcat(prezero, tap(itap,:) .* sin(anglein)', postzero); wavelet = complex(coswav, sinwav); % store the fft of the complex wavelet wltspctrm{ifreqoi}(itap,:) = fft(wavelet,[],2); % % debug plotting % figure('name',['taper #' num2str(itap) ' @ ' num2str(freqoi(ifreqoi)) 'Hz' ],'NumberTitle','off'); % subplot(2,1,1); % hold on; % plot(real(wavelet)); % plot(imag(wavelet),'color','r'); % legend('real','imag'); % tline = length(wavelet)/2; % if mod(tline,2)==0 % line([tline tline],[-max(abs(wavelet)) max(abs(wavelet))],'color','g','linestyle','--') % else % line([ceil(tline) ceil(tline)],[-max(abs(wavelet)) max(abs(wavelet))],'color','g','linestyle','--'); % line([floor(tline) floor(tline)],[-max(abs(wavelet)) max(abs(wavelet))],'color','g','linestyle','--'); % end; % subplot(2,1,2); % plot(angle(wavelet),'color','g'); % if mod(tline,2)==0, % line([tline tline],[-pi pi],'color','r','linestyle','--') % else % line([ceil(tline) ceil(tline)],[-pi pi],'color','r','linestyle','--') % line([floor(tline) floor(tline)],[-pi pi],'color','r','linestyle','--') % end end end end % Switch between memory efficient representation or intuitive default representation switch dimord case 'tap_chan_freq_time' % default % compute fft, major speed increases are possible here, depending on which matlab is being used whether or not it helps, which mainly focuses on orientation of the to be fft'd matrix datspectrum = transpose(fft(transpose([dat repmat(postpad,[nchan, 1])]))); % double explicit transpose to speedup fft spectrum = cell(max(ntaper), nfreqoi); for ifreqoi = 1:nfreqoi str = sprintf('frequency %d (%.2f Hz), %d tapers', ifreqoi,freqoi(ifreqoi),ntaper(ifreqoi)); [st, cws] = dbstack; if length(st)>1 && strcmp(st(2).name, 'ft_freqanalysis') && verbose % specest_mtmconvol has been called by ft_freqanalysis, meaning that ft_progress has been initialised ft_progress(fbopt.i./fbopt.n, ['trial %d, ',str,'\n'], fbopt.i); elseif verbose fprintf([str, '\n']); end for itap = 1:max(ntaper) % compute indices that will be used to extracted the requested fft output nsamplefreqoi = timwin(ifreqoi) .* fsample; reqtimeboiind = find((timeboi >= (nsamplefreqoi ./ 2)) & (timeboi < ndatsample - (nsamplefreqoi ./2))); reqtimeboi = timeboi(reqtimeboiind); % compute datspectrum*wavelet, if there are reqtimeboi's that have data % create a matrix of NaNs if there is no taper for this current frequency-taper-number if itap > ntaper(ifreqoi) spectrum{itap,ifreqoi} = complex(nan(nchan,ntimeboi)); else dum = fftshift(transpose(ifft(transpose(datspectrum .* repmat(wltspctrm{ifreqoi}(itap,:),[nchan 1])))),2); % double explicit transpose to speedup fft tmp = complex(nan(nchan,ntimeboi)); tmp(:,reqtimeboiind) = dum(:,reqtimeboi); tmp = tmp .* sqrt(2 ./ timwinsample(ifreqoi)); spectrum{itap,ifreqoi} = tmp; end end end spectrum = reshape(vertcat(spectrum{:}),[nchan max(ntaper) nfreqoi ntimeboi]); % collecting in a cell-array and later reshaping provides significant speedups spectrum = permute(spectrum, [2 1 3 4]); case 'chan_time_freqtap' % memory efficient representation % create tapfreqind freqtapind = []; tempntaper = [0; cumsum(ntaper(:))]; for ifreqoi = 1:nfreqoi freqtapind{ifreqoi} = tempntaper(ifreqoi)+1:tempntaper(ifreqoi+1); end % start fft'ing datspectrum = transpose(fft(transpose([dat repmat(postpad,[nchan, 1])]))); % double explicit transpose to speedup fft spectrum = complex(zeros([nchan ntimeboi sum(ntaper)])); for ifreqoi = 1:nfreqoi str = sprintf('frequency %d (%.2f Hz), %d tapers', ifreqoi,freqoi(ifreqoi),ntaper(ifreqoi)); [st, cws] = dbstack; if length(st)>1 && strcmp(st(2).name, 'ft_freqanalysis') && verbose % specest_mtmconvol has been called by ft_freqanalysis, meaning that ft_progress has been initialised ft_progress(fbopt.i./fbopt.n, ['trial %d, ',str,'\n'], fbopt.i); elseif verbose fprintf([str, '\n']); end for itap = 1:ntaper(ifreqoi) % compute indices that will be used to extracted the requested fft output nsamplefreqoi = timwin(ifreqoi) .* fsample; reqtimeboiind = find((timeboi >= (nsamplefreqoi ./ 2)) & (timeboi < (ndatsample - (nsamplefreqoi ./2)))); reqtimeboi = timeboi(reqtimeboiind); % compute datspectrum*wavelet, if there are reqtimeboi's that have data dum = fftshift(transpose(ifft(transpose(datspectrum .* repmat(wltspctrm{ifreqoi}(itap,:),[nchan 1])))),2); % double explicit transpose to speedup fft tmp = complex(nan(nchan,ntimeboi),nan(nchan,ntimeboi)); tmp(:,reqtimeboiind) = dum(:,reqtimeboi); tmp = tmp .* sqrt(2 ./ timwinsample(ifreqoi)); spectrum(:,:,freqtapind{ifreqoi}(itap)) = tmp; end end % for nfreqoi end % switch dimord % % below code does the exact same as above, but without the trick of converting to cell-arrays for speed increases. however, when there is a huge variability in number of tapers per freqoi % % than this approach can benefit from the fact that the array can be precreated containing nans % % compute fft, major speed increases are possible here, depending on which matlab is being used whether or not it helps, which mainly focuses on orientation of the to be fft'd matrix % datspectrum = transpose(fft(transpose([dat repmat(postpad,[nchan, 1])]))); % double explicit transpose to speedup fft % spectrum = complex(nan([max(ntaper) nchan nfreqoi ntimeboi]),nan([max(ntaper) nchan nfreqoi ntimeboi])); % assumes fixed number of tapers % for ifreqoi = 1:nfreqoi % fprintf('processing frequency %d (%.2f Hz), %d tapers\n', ifreqoi,freqoi(ifreqoi),ntaper(ifreqoi)); % for itap = 1:max(ntaper) % % compute indices that will be used to extracted the requested fft output % nsamplefreqoi = timwin(ifreqoi) .* fsample; % reqtimeboiind = find((timeboi >= (nsamplefreqoi ./ 2)) & (timeboi < ndatsample - (nsamplefreqoi ./2))); % reqtimeboi = timeboi(reqtimeboiind); % % % compute datspectrum*wavelet, if there are reqtimeboi's that have data % % create a matrix of NaNs if there is no taper for this current frequency-taper-number % if itap <= ntaper(ifreqoi) % dum = fftshift(transpose(ifft(transpose(datspectrum .* repmat(wltspctrm{ifreqoi}(itap,:),[nchan 1])))),2); % double explicit transpose to speedup fft % tmp = complex(nan(nchan,ntimeboi)); % tmp(:,reqtimeboiind) = dum(:,reqtimeboi); % tmp = tmp .* sqrt(2 ./ timwinsample(ifreqoi)); % spectrum(itap,:,ifreqoi,:) = tmp; % else % break % end % end % end % Below the code used to implement variable amount of tapers in a different way, kept here for testing, please do not remove % % build tapfreq vector % tapfreq = []; % for ifreqoi = 1:nfreqoi % tapfreq = [tapfreq ones(1,ntaper(ifreqoi)) * ifreqoi]; % end % tapfreq = tapfreq(:); % % % compute fft, major speed increases are possible here, depending on which matlab is being used whether or not it helps, which mainly focuses on orientation of the to be fft'd matrix % %spectrum = complex(nan([numel(tapfreq),nchan,ntimeboi])); % datspectrum = fft([dat repmat(postpad,[nchan, 1])],[],2); % spectrum = cell(numel(tapfreq), nchan, ntimeboi); % for ifreqoi = 1:nfreqoi % fprintf('processing frequency %d (%.2f Hz), %d tapers\n', ifreqoi,freqoi(ifreqoi),ntaper(ifreqoi)); % for itap = 1:ntaper(ifreqoi) % tapfreqind = sum(ntaper(1:ifreqoi-1)) + itap; % for ichan = 1:nchan % % compute indices that will be used to extracted the requested fft output % nsamplefreqoi = timwin(ifreqoi) .* fsample; % reqtimeboiind = find((timeboi >= (nsamplefreqoi ./ 2)) & (timeboi < ndatsample - (nsamplefreqoi ./2))); % reqtimeboi = timeboi(reqtimeboiind); % % % compute datspectrum*wavelet, if there are reqtimeboi's that have data % if ~isempty(reqtimeboi) % dum = fftshift(ifft(datspectrum(ichan,:) .* wltspctrm{ifreqoi}(itap,:),[],2)); % fftshift is necessary because of post zero-padding, not necessary when pre-padding % %spectrum(tapfreqind,ichan,reqtimeboiind) = dum(reqtimeboi); % tmp = complex(nan(1,ntimeboi)); % tmp(reqtimeboiind) = dum(reqtimeboi); % spectrum{tapfreqind,ichan} = tmp; % end % end % end % end % spectrum = reshape(vertcat(spectrum{:}),[numel(tapfreq) nchan ntimeboi]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION ensure that the first two input arguments are of double % precision this prevents an instability (bug) in the computation of the % tapers for Matlab 6.5 and 7.0 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [tap] = double_dpss(a, b, varargin) tap = dpss(double(a), double(b), varargin{:});
github
philippboehmsturm/antx-master
ft_specest_convol.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/specest/ft_specest_convol.m
7,359
utf_8
ac22d33e4455715f0e05fecaf3d8b412
function [spectrum, freqoi, timeoi] = ft_specest_convol(dat, time, varargin) % SPECEST_CONVOL performs wavelet convolution in the time domain by % convolution with Morlet's wavelets. % % Use as % [spectrum,freqoi,timeoi] = specest_convol(dat,time,...) % where % dat = matrix of chan*sample % time = vector, containing time in seconds for each sample % spectrum = matrix of chan*freqoi*timeoi of fourier coefficients % freqoi = vector of frequencies in spectrum % timeoi = vector of timebins in spectrum % % Optional arguments should be specified in key-value pairs and can include: % timeoi = vector, containing time points of interest (in seconds, analysis window will be centered around these time points) % freqoi = vector, containing frequencies (in Hz) % waveletwidth = number, 'width' of wavelets expressed in cycles (default = 7) % % OPTION DOWNSAMPLE: this looks like something that would fit in better in the (freqanalysis) wrapper I think % OPTION LATENCY, WHAT TO DO WITH THIS? % HOW TO MAKE CONSISTENT freqoi'S OVER TRIALS (e.g. multiple runs of this function)? ZERO-PADDING NOT AN OPTION... YET WE SHOULD STILL ONLY HAVE freqoi'S THAT ACTUALLY MATCH THE FREQUENCIES IN OUTPUT % % See also SPECEST_MTMFFT, SPECEST_MTMCONVOL, SPECEST_HILBERT, SPECEST_NANFFT, SPECEST_MVAR, SPECEST_WAVELET % Copyright (C) 2010, Donders Institute for Brain, Cognition and Behaviour % % $Log$ % get the optional input arguments keyvalcheck(varargin, 'optional', {'waveletwidth','pad','timeoi','freqoi','polyremoval'}); timeoi = keyval('timeoi', varargin); if isempty(timeoi), timeoi = 'all'; end freqoi = keyval('freqoi', varargin); if isempty(freqoi), freqoi = 'all'; end waveletwidth = keyval('waveletwidth', varargin); if isempty(waveletwidth), waveletwidth = 7; end polyorder = keyval('polyremoval', varargin); if isempty(polyorder), polyorder = 1; end % Set n's [nchan,ndatsample] = size(dat); % Remove polynomial fit from the data -> default is demeaning if polyorder >= 0 dat = ft_preproc_polyremoval(dat, polyorder, 1, ndatsample); end % Determine fsample and set total time-length of data fsample = 1/(time(2)-time(1)); dattime = ndatsample / fsample; % total time in seconds of input data endnsample = ndatsample; % for consistency with mtmconvol and mtmfft endtime = dattime; % for consistency with mtmconvol and mtmfft % Set freqboi and freqoi if isnumeric(freqoi) % if input is a vector freqboi = round(freqoi ./ (fsample ./ endnsample)) + 1; freqboi = unique(freqboi); freqoi = (freqboi-1) ./ endtime; % boi - 1 because 0 Hz is included in fourier output elseif strcmp(freqoi,'all') freqboilim = round([0 fsample/2] ./ (fsample ./ endnsample)) + 1; freqboi = freqboilim(1):1:freqboilim(2); freqoi = (freqboi-1) ./ endtime; end nfreqboi = length(freqboi); nfreqoi = length(freqoi); % Set timeboi and timeoi offset = round(time(1)*fsample); if isnumeric(timeoi) % if input is a vector timeboi = round(timeoi .* fsample - offset) + 1; ntimeboi = length(timeboi); timeoi = round(timeoi .* fsample) ./ fsample; elseif strcmp(timeoi,'all') % if input was 'all' timeboi = 1:length(time); ntimeboi = length(timeboi); timeoi = time; end % compute wavelet family wavfam = waveletfam(freqoi,fsample,waveletwidth); % compute spectrum by convolving the wavelets with the data spectrum = zeros(nchan, nfreqoi, nsample); for ifreqoi = 1:nfreqoi wavelet = wavfam{ifreqoi}; for ichan = 1:nchan spectrum(ichan,ifreqoi,:) = conv(dat(ichan,:), wavelet, 'same'); end % pad the edges with nans to indicate that the wavelet was not fully immersed in the data THERE ARE NO NANS ADDED IN FREQANALYSIS_TFR? nanpad = ceil(length(wavfam{ifreqoi})/2); % the padding should not be longer than the actual data nanpad = min(nanpad, nsample); begnanpad = 1:nanpad; endnanpad = (nsample-nanpad+1):nsample; spectrum(:,ifreqoi,begnanpad) = nan; spectrum(:,ifreqoi,endnanpad) = nan; end % select the samples for the output spectrum = spectrum(:,:,timeboi); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for waveletanalysis %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function M = waveletfam(foi,fsample,waveletwidth) dt = 1/fsample; for k=1:length(foi) sf = foi(k)/waveletwidth; st = 1/(2*pi*sf); toi = -3.5*st:dt:3.5*st; A = 1/sqrt(st*sqrt(pi)); M{k}= A*exp(-toi.^2/(2*st^2)).*exp(i*2*pi*foi(k).*toi); end % state = keyval('state', varargin); % waveletwidth = keyval('waveletwidth', varargin); if isempty(waveletwidth), waveletwidth = 7; end % downsample = keyval('downsample', varargin); % time = keyval('time', varargin); % toi = keyval('toi', varargin); % % % FIXME add width % % if ~isempty(downsample) && ~isempty(toi) % error('the downsample and toi options are mutually exclusive'); % end % % nchans = size(dat,1); % nsamples = size(dat,2); % % if isempty(time) % if ~isempty(toi) % error('specification of toi without time is not permitted'); % end % time = (0:(nsamples-1))/fsample; % end % % if ~isempty(state) && isequal(state.fsample, fsample) && isequal(state.foi, foi) && isequal(state.waveletwidth, waveletwidth) % % reuse the wavelet family from the previous state % disp('using previous state'); % M = state.M; % else % if ~isempty(state) % state = []; % warning('recomputing the state'); % end % % recompute the wavelet family % M = waveletfam(foi,fsample,waveletwidth); % end % % % compute freq by convolving the wavelets with the data % nfreq = length(foi); % spectrum = zeros(nchans, nsamples, nfreq); % % for f=1:nfreq % wavelet = M{f}; % for c=1:nchans % spectrum(c,:,f) = conv(dat(c,:), wavelet, 'same'); % end % % pad the edges with nans to indicate that the wavelet was not fully immersed in the data % pad = ceil(length(M{f})/2); % % the padding should not be longer than the actual data % pad = min(pad, nsamples); % begpad = 1:pad; % endpad = (nsamples-pad+1):nsamples; % spectrum(:,begpad,f) = nan; % spectrum(:,endpad,f) = nan; % end % % if ~isempty(downsample) % % this would be done in case of downsample % tbin = 1:downsample:nsamples; % elseif ~isempty(toi) % % this would be done in case of toi/time specification % tbin = zeros(size(toi)); % for i=1:length(tbin) % tbin = nearest(time, toi(i)); % end % else % tbin = 1:nsamples; % end % % % select the samples for the output % spectrum = spectrum(:,tbin,:); % % % remember the wavelets so that they can be reused in a subsequent call % state.fsample = fsample; % state.foi = foi; % state.waveletwidth = waveletwidth; % state.M = M; % % % %convolves data in chan by time matrix (from one trial) with 1 wavelet for % % %each specified frequency of interest % % spectrum = zeros(size(data,1),length(foi), size(data,2)); % % for k=1:size(data,1) %nchans % % for j=1:length(foi) % % cTmp = conv(data(k,:),M{j}); % % cTmp = 2*(abs(cTmp).^2)/fsample; % % cTmp = cTmp(ceil(length(M{j})/2):length(cTmp)-floor(length(M{j})/2)); % % spectrum(k,j,:) = cTmp; % % end % % % % end % % %output should be chan by freq by time
github
philippboehmsturm/antx-master
ft_specest_mtmfft.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/specest/ft_specest_mtmfft.m
7,105
utf_8
90574c21677d7ac87f08ed43d83b4e2a
function [spectrum,ntaper,freqoi] = ft_specest_mtmfft(dat, time, varargin) % SPECEST_MTMFFT computes a fast Fourier transform using multitapering with % the DPSS sequence or using a variety of single tapers % % Use as % [spectrum,freqoi] = specest_mtmfft(dat,time...) % where % dat = matrix of chan*sample % time = vector, containing time in seconds for each sample % spectrum = matrix of taper*chan*freqoi of fourier coefficients % ntaper = vector containing number of tapers per element of freqoi % freqoi = vector of frequencies in spectrum % % Optional arguments should be specified in key-value pairs and can include: % taper = 'dpss', 'hanning' or many others, see WINDOW (default = 'dpss') % pad = number, total length of data after zero padding (in seconds) % freqoi = vector, containing frequencies of interest % tapsmofrq = the amount of spectral smoothing through multi-tapering. Note: 4 Hz smoothing means plus-minus 4 Hz, i.e. a 8 Hz smoothing box % % See also SPECEST_MTMCONVOL, SPECEST_CONVOL, SPECEST_HILBERT, SPECEST_WAVELET % Copyright (C) 2010, Donders Institute for Brain, Cognition and Behaviour % % $Log$ % get the optional input arguments keyvalcheck(varargin, 'optional', {'taper','pad','freqoi','tapsmofrq','feedback','polyremoval'}); taper = keyval('taper', varargin); if isempty(taper), error('You must specify a taper'); end pad = keyval('pad', varargin); freqoi = keyval('freqoi', varargin); if isempty(freqoi), freqoi = 'all'; end tapsmofrq = keyval('tapsmofrq', varargin); fbopt = keyval('feedback', varargin); polyorder = keyval('polyremoval', varargin); if isempty(polyorder), polyorder = 1; end if isempty(fbopt), fbopt.i = 1; fbopt.n = 1; end % throw errors for required input if isempty(tapsmofrq) && strcmp(taper, 'dpss') error('you need to specify tapsmofrq when using dpss tapers') end % Set n's [nchan,ndatsample] = size(dat); % Remove polynomial fit from the data -> default is demeaning if polyorder >= 0 dat = ft_preproc_polyremoval(dat, polyorder, 1, ndatsample); end % Determine fsample and set total time-length of data fsample = 1/(time(2)-time(1)); dattime = ndatsample / fsample; % total time in seconds of input data % Zero padding if round(pad * fsample) < ndatsample error('the padding that you specified is shorter than the data'); end if isempty(pad) % if no padding is specified padding is equal to current data length pad = dattime; end postpad = zeros(1,ceil((pad - dattime) * fsample)); endnsample = round(pad * fsample); % total number of samples of padded data endtime = pad; % total time in seconds of padded data % Set freqboi and freqoi if isnumeric(freqoi) % if input is a vector freqboi = round(freqoi ./ (fsample ./ endnsample)) + 1; freqboi = unique(freqboi); freqoi = (freqboi-1) ./ endtime; % boi - 1 because 0 Hz is included in fourier output elseif strcmp(freqoi,'all') % if input was 'all' freqboilim = round([0 fsample/2] ./ (fsample ./ endnsample)) + 1; freqboi = freqboilim(1):1:freqboilim(2); freqoi = (freqboi-1) ./ endtime; end nfreqboi = length(freqboi); nfreqoi = length(freqoi); % create tapers switch taper case 'dpss' % create a sequence of DPSS tapers, ensure that the input arguments are double precision tap = double_dpss(ndatsample,ndatsample*(tapsmofrq./fsample))'; % remove the last taper because the last slepian taper is always messy tap = tap(1:(end-1), :); % give error/warning about number of tapers if isempty(tap) error('datalength to short for specified smoothing\ndatalength: %.3f s, smoothing: %.3f Hz, minimum smoothing: %.3f Hz',ndatsample/fsample,tapsmofrq,fsample/ndatsample); elseif size(tap,1) == 1 warning_once('using only one taper for specified smoothing'); end case 'sine' tap = sine_taper(ndatsample, ndatsample*(tapsmofrq./fsample))'; tap = tap(1:(end-1), :); % remove the last taper case 'sine_old' % to provide compatibility with the tapers being scaled (which was default % behavior prior to 29apr2011) yet this gave different magnitude of power % when comparing with slepian multi tapers tap = sine_taper_scaled(ndatsample, ndatsample*(tapsmofrq./fsample))'; tap = tap(1:(end-1), :); % remove the last taper case 'alpha' error('not yet implemented'); case 'hanning' tap = hanning(ndatsample)'; tap = tap./norm(tap, 'fro'); otherwise % create the taper and ensure that it is normalized tap = window(taper, ndatsample)'; tap = tap ./ norm(tap,'fro'); end % switch taper ntaper = repmat(size(tap,1),nfreqoi,1); str = sprintf('nfft: %d samples, datalength: %d samples, %d tapers',endnsample,ndatsample,ntaper(1)); [st, cws] = dbstack; if length(st)>1 && strcmp(st(2).name, 'ft_freqanalysis') % specest_mtmfft has been called by ft_freqanalysis, meaning that ft_progress has been initialised ft_progress(fbopt.i./fbopt.n, ['processing trial %d/%d ',str,'\n'], fbopt.i, fbopt.n); else fprintf([str, '\n']); end % determine phase-shift so that for all frequencies angle(t=0) = 0 timedelay = time(1); if timedelay ~= 0 angletransform = complex(zeros(1,nfreqoi)); for ifreqoi = 1:nfreqoi missedsamples = round(timedelay * fsample); % determine angle of freqoi if oscillation started at 0 % the angle of wavelet(cos,sin) = 0 at the first point of a cycle, with sine being in upgoing flank, which is the same convention as in mtmconvol anglein = (missedsamples) .* ((2.*pi./fsample) .* freqoi(ifreqoi)); coswav = cos(anglein); sinwav = sin(anglein); angletransform(ifreqoi) = angle(complex(coswav,sinwav)); end angletransform = repmat(angletransform,[nchan,1]); end % compute fft, major speed increases are possible here, depending on which matlab is being used whether or not it helps, which mainly focuses on orientation of the to be fft'd matrix spectrum = cell(ntaper(1),1); for itap = 1:ntaper(1) dum = transpose(fft(transpose([dat .* repmat(tap(itap,:),[nchan, 1]) repmat(postpad,[nchan, 1])]))); % double explicit transpose to speedup fft dum = dum(:,freqboi); % phase-shift according to above angles if timedelay ~= 0 dum = dum .* exp(-1i*angletransform); end dum = dum .* sqrt(2 ./ endnsample); spectrum{itap} = dum; end spectrum = reshape(vertcat(spectrum{:}),[nchan ntaper(1) nfreqboi]);% collecting in a cell-array and later reshaping provides significant speedups spectrum = permute(spectrum, [2 1 3]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION ensure that the first two input arguments are of double % precision this prevents an instability (bug) in the computation of the % tapers for Matlab 6.5 and 7.0 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [tap] = double_dpss(a, b, varargin) tap = dpss(double(a), double(b), varargin{:});
github
philippboehmsturm/antx-master
postpad.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/specest/private/postpad.m
2,013
utf_8
2c9539d77ff0f85c9f89108f4dc811e0
% Copyright (C) 1994, 1995, 1996, 1997, 1998, 2000, 2002, 2004, 2005, % 2006, 2007, 2008, 2009 John W. Eaton % % This file is part of Octave. % % Octave is free software; you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 3 of the License, or (at % your option) any later version. % % Octave is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % % You should have received a copy of the GNU General Public License % along with Octave; see the file COPYING. If not, see % <http://www.gnu.org/licenses/>. % -*- texinfo -*- % @deftypefn {Function File} {} postpad (@var{x}, @var{l}, @var{c}) % @deftypefnx {Function File} {} postpad (@var{x}, @var{l}, @var{c}, @var{dim}) % @seealso{prepad, resize} % @end deftypefn % Author: Tony Richardson <[email protected]> % Created: June 1994 function y = postpad (x, l, c, dim) if nargin < 2 || nargin > 4 %print_usage (); error('wrong number of input arguments, should be between 2 and 4'); end if nargin < 3 || isempty(c) c = 0; else if ~isscalar(c) error ('postpad: third argument must be empty or a scalar'); end end nd = ndims(x); sz = size(x); if nargin < 4 % Find the first non-singleton dimension dim = 1; while dim < nd+1 && sz(dim)==1 dim = dim + 1; end if dim > nd dim = 1; elseif ~(isscalar(dim) && dim == round(dim)) && dim > 0 && dim< nd+1 error('postpad: dim must be an integer and valid dimension'); end end if ~isscalar(l) || l<0 error ('second argument must be a positive scalar'); end if dim > nd sz(nd+1:dim) = 1; end d = sz(dim); if d >= l idx = cell(1,nd); for i = 1:nd idx{i} = 1:sz(i); end idx{dim} = 1:l; y = x(idx{:}); else sz(dim) = l-d; y = cat(dim, x, c * ones(sz)); end
github
philippboehmsturm/antx-master
sftrans.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/specest/private/sftrans.m
7,947
utf_8
f64cb2e7d19bcdc6232b39d8a6d70e7c
% Copyright (C) 1999 Paul Kienzle % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop) % % Transform band edges of a generic lowpass filter (cutoff at W=1) % represented in splane zero-pole-gain form. W is the edge of the % target filter (or edges if band pass or band stop). Stop is true for % high pass and band stop filters or false for low pass and band pass % filters. Filter edges are specified in radians, from 0 to pi (the % nyquist frequency). % % Theory: Given a low pass filter represented by poles and zeros in the % splane, you can convert it to a low pass, high pass, band pass or % band stop by transforming each of the poles and zeros individually. % The following table summarizes the transformation: % % Transform Zero at x Pole at x % ---------------- ------------------------- ------------------------ % Low Pass zero: Fc x/C pole: Fc x/C % S -> C S/Fc gain: C/Fc gain: Fc/C % ---------------- ------------------------- ------------------------ % High Pass zero: Fc C/x pole: Fc C/x % S -> C Fc/S pole: 0 zero: 0 % gain: -x gain: -1/x % ---------------- ------------------------- ------------------------ % Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S^2+FhFl pole: 0 zero: 0 % S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C % S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ % Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl) % S -> C -------- gain: -x gain: -1/x % S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ % Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT) % 2 z-1 pole: -1 zero: -1 % S -> - --- gain: (2-xT)/T gain: (2-xT)/T % T z+1 % ---------------- ------------------------- ------------------------ % % where C is the cutoff frequency of the initial lowpass filter, Fc is % the edge of the target low/high pass filter and [Fl,Fh] are the edges % of the target band pass/stop filter. With abundant tedious algebra, % you can derive the above formulae yourself by substituting the % transform for S into H(S)=S-x for a zero at x or H(S)=1/(S-x) for a % pole at x, and converting the result into the form: % % H(S)=g prod(S-Xi)/prod(S-Xj) % % The transforms are from the references. The actual pole-zero-gain % changes I derived myself. % % Please note that a pole and a zero at the same place exactly cancel. % This is significant for High Pass, Band Pass and Band Stop filters % which create numerous extra poles and zeros, most of which cancel. % Those which do not cancel have a 'fill-in' effect, extending the % shorter of the sets to have the same number of as the longer of the % sets of poles and zeros (or at least split the difference in the case % of the band pass filter). There may be other opportunistic % cancellations but I will not check for them. % % Also note that any pole on the unit circle or beyond will result in % an unstable filter. Because of cancellation, this will only happen % if the number of poles is smaller than the number of zeros and the % filter is high pass or band pass. The analytic design methods all % yield more poles than zeros, so this will not be a problem. % % References: % % Proakis & Manolakis (1992). Digital Signal Processing. New York: % Macmillan Publishing Company. % Author: Paul Kienzle <[email protected]> % 2000-03-01 [email protected] % leave transformed Sg as a complex value since cheby2 blows up % otherwise (but only for odd-order low-pass filters). bilinear % will return Zg as real, so there is no visible change to the % user of the IIR filter design functions. % 2001-03-09 [email protected] % return real Sg; don't know what to do for imaginary filters function [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop) if (nargin ~= 5) usage('[Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)'); end; C = 1; p = length(Sp); z = length(Sz); if z > p || p == 0 error('sftrans: must have at least as many poles as zeros in s-plane'); end if length(W)==2 Fl = W(1); Fh = W(2); if stop % ---------------- ------------------------- ------------------------ % Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl) % S -> C -------- gain: -x gain: -1/x % S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ if (isempty(Sz)) Sg = Sg * real (1./ prod(-Sp)); elseif (isempty(Sp)) Sg = Sg * real(prod(-Sz)); else Sg = Sg * real(prod(-Sz)/prod(-Sp)); end b = (C*(Fh-Fl)/2)./Sp; Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; extend = [sqrt(-Fh*Fl), -sqrt(-Fh*Fl)]; if isempty(Sz) Sz = [extend(1+rem([1:2*p],2))]; else b = (C*(Fh-Fl)/2)./Sz; Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; if (p > z) Sz = [Sz, extend(1+rem([1:2*(p-z)],2))]; end end else % ---------------- ------------------------- ------------------------ % Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S^2+FhFl pole: 0 zero: 0 % S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C % S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ Sg = Sg * (C/(Fh-Fl))^(z-p); b = Sp*((Fh-Fl)/(2*C)); Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; if isempty(Sz) Sz = zeros(1,p); else b = Sz*((Fh-Fl)/(2*C)); Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; if (p>z) Sz = [Sz, zeros(1, (p-z))]; end end end else Fc = W; if stop % ---------------- ------------------------- ------------------------ % High Pass zero: Fc C/x pole: Fc C/x % S -> C Fc/S pole: 0 zero: 0 % gain: -x gain: -1/x % ---------------- ------------------------- ------------------------ if (isempty(Sz)) Sg = Sg * real (1./ prod(-Sp)); elseif (isempty(Sp)) Sg = Sg * real(prod(-Sz)); else Sg = Sg * real(prod(-Sz)/prod(-Sp)); end Sp = C * Fc ./ Sp; if isempty(Sz) Sz = zeros(1,p); else Sz = [C * Fc ./ Sz]; if (p > z) Sz = [Sz, zeros(1,p-z)]; end end else % ---------------- ------------------------- ------------------------ % Low Pass zero: Fc x/C pole: Fc x/C % S -> C S/Fc gain: C/Fc gain: Fc/C % ---------------- ------------------------- ------------------------ Sg = Sg * (C/Fc)^(z-p); Sp = Fc * Sp / C; Sz = Fc * Sz / C; end end
github
philippboehmsturm/antx-master
hanning.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/specest/private/hanning.m
2,015
utf_8
cac22a4ad0f0b038d6f17439d97dfc36
function [tap] = hanning(n, str) %HANNING Hanning window. % HANNING(N) returns the N-point symmetric Hanning window in a column % vector. Note that the first and last zero-weighted window samples % are not included. % % HANNING(N,'symmetric') returns the same result as HANNING(N). % % HANNING(N,'periodic') returns the N-point periodic Hanning window, % and includes the first zero-weighted window sample. % % NOTE: Use the HANN function to get a Hanning window which has the % first and last zero-weighted samples. % % See also BARTLETT, BLACKMAN, BOXCAR, CHEBWIN, HAMMING, HANN, KAISER % and TRIANG. % % This is a drop-in replacement to bypass the signal processing toolbox % Copyright (c) 2010, Jan-Mathijs Schoffelen, DCCN Nijmegen % % 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: hanning.m 2212 2010-11-27 11:55:07Z roboos $ if nargin==1, str = 'symmetric'; end switch str, case 'periodic' % Includes the first zero sample tap = [0; hanningX(n-1)]; case 'symmetric' % Does not include the first and last zero sample tap = hanningX(n); end function tap = hanningX(n) % compute taper N = n+1; tap = 0.5*(1-cos((2*pi*(1:n))./N))'; % make symmetric halfn = floor(n/2); tap( (n+1-halfn):n ) = flipud(tap(1:halfn));
github
philippboehmsturm/antx-master
filtfilt.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/specest/private/filtfilt.m
3,297
iso_8859_1
d01a26a827bc3379f05bbc57f46ac0a9
% Copyright (C) 1999 Paul Kienzle % Copyright (C) 2007 Francesco Potortì % Copyright (C) 2008 Luca Citi % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: y = filtfilt(b, a, x) % % Forward and reverse filter the signal. This corrects for phase % distortion introduced by a one-pass filter, though it does square the % magnitude response in the process. That's the theory at least. In % practice the phase correction is not perfect, and magnitude response % is distorted, particularly in the stop band. %% % Example % [b, a]=butter(3, 0.1); % 10 Hz low-pass filter % t = 0:0.01:1.0; % 1 second sample % x=sin(2*pi*t*2.3)+0.25*randn(size(t)); % 2.3 Hz sinusoid+noise % y = filtfilt(b,a,x); z = filter(b,a,x); % apply filter % plot(t,x,';data;',t,y,';filtfilt;',t,z,';filter;') % Changelog: % 2000 02 [email protected] % - pad with zeros to load up the state vector on filter reverse. % - add example % 2007 12 [email protected] % - use filtic to compute initial and final states % - work for multiple columns as well % 2008 12 [email protected] % - fixed instability issues with IIR filters and noisy inputs % - initial states computed according to Likhterov & Kopeika, 2003 % - use of a "reflection method" to reduce end effects % - added some basic tests % TODO: (pkienzle) My version seems to have similar quality to matlab, % but both are pretty bad. They do remove gross lag errors, though. function y = filtfilt(b, a, x) if (nargin ~= 3) usage('y=filtfilt(b,a,x)'); end rotate = (size(x, 1)==1); if rotate % a row vector x = x(:); % make it a column vector end lx = size(x,1); a = a(:).'; b = b(:).'; lb = length(b); la = length(a); n = max(lb, la); lrefl = 3 * (n - 1); if la < n, a(n) = 0; end if lb < n, b(n) = 0; end % Compute a the initial state taking inspiration from % Likhterov & Kopeika, 2003. "Hardware-efficient technique for % minimizing startup transients in Direct Form II digital filters" kdc = sum(b) / sum(a); if (abs(kdc) < inf) % neither NaN nor +/- Inf si = fliplr(cumsum(fliplr(b - kdc * a))); else si = zeros(size(a)); % fall back to zero initialization end si(1) = []; y = zeros(size(x)); for c = 1:size(x, 2) % filter all columns, one by one v = [2*x(1,c)-x((lrefl+1):-1:2,c); x(:,c); 2*x(end,c)-x((end-1):-1:end-lrefl,c)]; % a column vector % Do forward and reverse filtering v = filter(b,a,v,si*v(1)); % forward filter v = flipud(filter(b,a,flipud(v),si*v(end))); % reverse filter y(:,c) = v((lrefl+1):(lx+lrefl)); end if (rotate) % x was a row vector y = rot90(y); % rotate it back end
github
philippboehmsturm/antx-master
bilinear.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/specest/private/bilinear.m
4,339
utf_8
17250db27826cad87fa3384823e1242f
% Copyright (C) 1999 Paul Kienzle % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T) % [Zb, Za] = bilinear(Sb, Sa, T) % % Transform a s-plane filter specification into a z-plane % specification. Filters can be specified in either zero-pole-gain or % transfer function form. The input form does not have to match the % output form. 1/T is the sampling frequency represented in the z plane. % % Note: this differs from the bilinear function in the signal processing % toolbox, which uses 1/T rather than T. % % Theory: Given a piecewise flat filter design, you can transform it % from the s-plane to the z-plane while maintaining the band edges by % means of the bilinear transform. This maps the left hand side of the % s-plane into the interior of the unit circle. The mapping is highly % non-linear, so you must design your filter with band edges in the % s-plane positioned at 2/T tan(w*T/2) so that they will be positioned % at w after the bilinear transform is complete. % % The following table summarizes the transformation: % % +---------------+-----------------------+----------------------+ % | Transform | Zero at x | Pole at x | % | H(S) | H(S) = S-x | H(S)=1/(S-x) | % +---------------+-----------------------+----------------------+ % | 2 z-1 | zero: (2+xT)/(2-xT) | zero: -1 | % | S -> - --- | pole: -1 | pole: (2+xT)/(2-xT) | % | T z+1 | gain: (2-xT)/T | gain: (2-xT)/T | % +---------------+-----------------------+----------------------+ % % With tedious algebra, you can derive the above formulae yourself by % substituting the transform for S into H(S)=S-x for a zero at x or % H(S)=1/(S-x) for a pole at x, and converting the result into the % form: % % H(Z)=g prod(Z-Xi)/prod(Z-Xj) % % Please note that a pole and a zero at the same place exactly cancel. % This is significant since the bilinear transform creates numerous % extra poles and zeros, most of which cancel. Those which do not % cancel have a 'fill-in' effect, extending the shorter of the sets to % have the same number of as the longer of the sets of poles and zeros % (or at least split the difference in the case of the band pass % filter). There may be other opportunistic cancellations but I will % not check for them. % % Also note that any pole on the unit circle or beyond will result in % an unstable filter. Because of cancellation, this will only happen % if the number of poles is smaller than the number of zeros. The % analytic design methods all yield more poles than zeros, so this will % not be a problem. % % References: % % Proakis & Manolakis (1992). Digital Signal Processing. New York: % Macmillan Publishing Company. % Author: Paul Kienzle <[email protected]> function [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T) if nargin==3 T = Sg; [Sz, Sp, Sg] = tf2zp(Sz, Sp); elseif nargin~=4 usage('[Zz, Zp, Zg]=bilinear(Sz,Sp,Sg,T) or [Zb, Za]=blinear(Sb,Sa,T)'); end; p = length(Sp); z = length(Sz); if z > p || p==0 error('bilinear: must have at least as many poles as zeros in s-plane'); end % ---------------- ------------------------- ------------------------ % Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT) % 2 z-1 pole: -1 zero: -1 % S -> - --- gain: (2-xT)/T gain: (2-xT)/T % T z+1 % ---------------- ------------------------- ------------------------ Zg = real(Sg * prod((2-Sz*T)/T) / prod((2-Sp*T)/T)); Zp = (2+Sp*T)./(2-Sp*T); if isempty(Sz) Zz = -ones(size(Zp)); else Zz = [(2+Sz*T)./(2-Sz*T)]; Zz = postpad(Zz, p, -1); end if nargout==2, [Zz, Zp] = zp2tf(Zz, Zp, Zg); end
github
philippboehmsturm/antx-master
warning_once.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/specest/private/warning_once.m
3,060
utf_8
f046009e4f6ffe5745af9c5e527614e8
function [ws warned] = warning_once(varargin) % % Use as % warning_once(string) % or % warning_once(string, timeout) % or % warning_once(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. The default timeout value is 60 seconds. % % Can be used instead of the MATLAB built-in function WARNING, thus as % s = warning_once(...) % or % warning_once(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. % In other words, warning_once accepts as an input the same structure it % returns as an output. This returns or restores the states of warnings to % their previous values. % % Can also be used as % [s w] = warning_once(...) % where w is a boolean that indicates whether a warning as been % thrown or not. persistent stopwatch previous if nargin < 1 error('You need to specify at least a warning message'); end warned = false; if isstruct(varargin{1}) warning(varargin{1}); return; end if nargin==3 msgid = varargin{1}; msgstr = varargin{2}; timeout = varargin{3}; elseif nargin==2 msgstr= ''; % this becomes irrelevant msgid = varargin{1}; % this becomes the real msgstr timeout = varargin{2}; elseif nargin==1 msgstr= ''; % this becomes irrelevant msgid = varargin{1}; % this becomes the real msgstr timeout = 60; % default timeout in seconds end if isempty(timeout) error('Timeout ill-specified'); end if isempty(stopwatch) stopwatch = tic; end if isempty(previous) previous = struct; end now = toc(stopwatch); % measure time since first function call fname = fixname([msgid '_' msgstr]); % make a nice string that is allowed as structure fieldname, copy the subfunction from ft_hastoolbox fname = decomma(fname); if length(fname) > 63 % MATLAB max name fname = fname(1:63); end if isfield(previous, fname) && now>previous.(fname).timeout % it has timed out, give the warning again ws = warning(msgid, msgstr); previous.(fname).timeout = now+timeout; previous.(fname).ws = ws; warned = true; elseif ~isfield(previous, fname) % the warning has not been issued before ws = warning(msgid, msgstr); previous.(fname).timeout = now+timeout; previous.(fname).ws = ws; warned = true; else % the warning has been issued before, but has not timed out yet ws = previous.(fname).ws; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out = fixname(toolbox) out = lower(toolbox); out(out=='-') = '_'; % fix dashes out(out==' ') = '_'; % fix spaces out(out=='/') = '_'; % fix forward slashes out(out=='\') = '_'; % fix backward slashes while(out(1) == '_'), out = out(2:end); end; % remove preceding underscore while(out(end) == '_'), out = out(1:end-1); end; % remove subsequent underscore end function nameout = decomma(name) nameout = name; indx = findstr(name,','); nameout(indx)=[]; end
github
philippboehmsturm/antx-master
butter.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/specest/private/butter.m
3,559
utf_8
ad82b4c04911a5ea11fd6bd2cc5fd590
% Copyright (C) 1999 Paul Kienzle % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % Generate a butterworth filter. % Default is a discrete space (Z) filter. % % [b,a] = butter(n, Wc) % low pass filter with cutoff pi*Wc radians % % [b,a] = butter(n, Wc, 'high') % high pass filter with cutoff pi*Wc radians % % [b,a] = butter(n, [Wl, Wh]) % band pass filter with edges pi*Wl and pi*Wh radians % % [b,a] = butter(n, [Wl, Wh], 'stop') % band reject filter with edges pi*Wl and pi*Wh radians % % [z,p,g] = butter(...) % return filter as zero-pole-gain rather than coefficients of the % numerator and denominator polynomials. % % [...] = butter(...,'s') % return a Laplace space filter, W can be larger than 1. % % [a,b,c,d] = butter(...) % return state-space matrices % % References: % % Proakis & Manolakis (1992). Digital Signal Processing. New York: % Macmillan Publishing Company. % Author: Paul Kienzle <[email protected]> % Modified by: Doug Stewart <[email protected]> Feb, 2003 function [a, b, c, d] = butter (n, W, varargin) if (nargin>4 || nargin<2) || (nargout>4 || nargout<2) usage ('[b, a] or [z, p, g] or [a,b,c,d] = butter (n, W [, "ftype"][,"s"])'); end % interpret the input parameters if (~(length(n)==1 && n == round(n) && n > 0)) error ('butter: filter order n must be a positive integer'); end stop = 0; digital = 1; for i=1:length(varargin) switch varargin{i} case 's', digital = 0; case 'z', digital = 1; case { 'high', 'stop' }, stop = 1; case { 'low', 'pass' }, stop = 0; otherwise, error ('butter: expected [high|stop] or [s|z]'); end end [r, c]=size(W); if (~(length(W)<=2 && (r==1 || c==1))) error ('butter: frequency must be given as w0 or [w0, w1]'); elseif (~(length(W)==1 || length(W) == 2)) error ('butter: only one filter band allowed'); elseif (length(W)==2 && ~(W(1) < W(2))) error ('butter: first band edge must be smaller than second'); end if ( digital && ~all(W >= 0 & W <= 1)) error ('butter: critical frequencies must be in (0 1)'); elseif ( ~digital && ~all(W >= 0 )) error ('butter: critical frequencies must be in (0 inf)'); end % Prewarp to the band edges to s plane if digital T = 2; % sampling frequency of 2 Hz W = 2/T*tan(pi*W/T); end % Generate splane poles for the prototype butterworth filter % source: Kuc C = 1; % default cutoff frequency pole = C*exp(1i*pi*(2*[1:n] + n - 1)/(2*n)); if mod(n,2) == 1, pole((n+1)/2) = -1; end % pure real value at exp(i*pi) zero = []; gain = C^n; % splane frequency transform [zero, pole, gain] = sftrans(zero, pole, gain, W, stop); % Use bilinear transform to convert poles to the z plane if digital [zero, pole, gain] = bilinear(zero, pole, gain, T); end % convert to the correct output form if nargout==2, a = real(gain*poly(zero)); b = real(poly(pole)); elseif nargout==3, a = zero; b = pole; c = gain; else % output ss results [a, b, c, d] = zp2ss (zero, pole, gain); end
github
philippboehmsturm/antx-master
nan_sum.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/nan_sum.m
1,345
utf_8
ddf503cdb0cfbf8060276a3304a2c60e
% nan_sum() - Take the sum, not considering NaN values % % Usage: same as sum() % Author: Arnaud Delorme, CNL / Salk Institute, 16 Oct 2002 %123456789012345678901234567890123456789012345678901234567890123456789012 % 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 out = nan_sum(in, dim) if nargin < 1 help nan_sum; return; end; if nargin < 2 if size(in,1) ~= 1 dim = 1; elseif size(in,2) ~= 1 dim = 2; else dim = 3; end; end; tmpin = in; tmpin(find(isnan(in(:)))) = 0; out = sum(tmpin, dim);
github
philippboehmsturm/antx-master
avw_hdr_make.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/avw_hdr_make.m
4,182
utf_8
8ca7457260adb412763652b40d1495c4
function [ avw ] = avw_hdr_make % AVW_HDR_MAKE - Create Analyze format data header (avw.hdr) % % [ avw ] = avw_hdr_make % % avw.hdr - a struct, all fields returned from the header. % For details, find a good description on the web % or see the Analyze File Format pdf in the % mri_toolbox doc folder or see avw_hdr_read.m % % See also, AVW_HDR_READ AVW_HDR_WRITE % AVW_IMG_READ AVW_IMG_WRITE % % $Revision: 2885 $ $Date: 2009/01/14 09:24:45 $ % Licence: GNU GPL, no express or implied warranties % History: 06/2002, [email protected] % 02/2003, [email protected] % date/time bug at lines 97-98 % identified by [email protected] % % The Analyze format is copyright % (c) Copyright, 1986-1995 % Biomedical Imaging Resource, Mayo Foundation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% version = '[$Revision: 2885 $]'; fprintf('\nAVW_HDR_MAKE [v%s]\n',version(12:16)); tic; % Comments % The header format is flexible and can be extended for new % user-defined data types. The essential structures of the header % are the header_key and the image_dimension. See avw_hdr_read % for more detail of the header structure avw.hdr = make_header; t=toc; fprintf('...done (%5.2f sec).\n',t); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ hdr ] = make_header hdr.hk = header_key; hdr.dime = image_dimension; hdr.hist = data_history; return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [hk] = header_key hk.sizeof_hdr = int32(348); % must be 348! hk.data_type(1:10) = sprintf('%10s',''); hk.db_name(1:18) = sprintf('%18s',''); hk.extents = int32(16384); hk.session_error = int16(0); hk.regular = sprintf('%1s','r'); % might be uint8 hk.hkey_un0 = uint8(0); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ dime ] = image_dimension dime.dim(1:8) = int16([4 256 256 256 1 0 0 0]); dime.vox_units(1:4) = sprintf('%4s','mm'); dime.cal_units(1:8) = sprintf('%8s',''); dime.unused1 = int16(0); dime.datatype = int16(2); dime.bitpix = int16(8); dime.dim_un0 = int16(0); dime.pixdim(1:8) = single([0 1 1 1 1000 0 0 0]); dime.vox_offset = single(0); dime.funused1 = single(0); dime.funused2 = single(0); % Set default 8bit intensity scale (from MRIcro), otherwise funused3 dime.roi_scale = single(1); dime.cal_max = single(0); dime.cal_min = single(0); dime.compressed = int32(0); dime.verified = int32(0); dime.glmax = int32(255); dime.glmin = int32(0); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ hist ] = data_history datime = clock; hist.descrip(1:80) = sprintf('%-80s','mri_toolbox @ http://eeg.sf.net/'); hist.aux_file(1:24) = sprintf('%-24s',''); hist.orient = uint8(0); % sprintf( '%1s',''); % see notes in avw_hdr_read hist.originator(1:10) = sprintf('%-10s',''); hist.generated(1:10) = sprintf('%-10s','mri_toolbx'); hist.scannum(1:10) = sprintf('%-10s',''); hist.patient_id(1:10) = sprintf('%-10s',''); hist.exp_date(1:10) = sprintf('%02d-%02d-%04d',datime(3),datime(2),datime(1)); hist.exp_time(1:10) = sprintf('%02d-%02d-%04.1f',datime(4),datime(5),datime(6)); hist.hist_un0(1:3) = sprintf( '%-3s',''); hist.views = int32(0); hist.vols_added = int32(0); hist.start_field = int32(0); hist.field_skip = int32(0); hist.omax = int32(0); hist.omin = int32(0); hist.smax = int32(0); hist.smin = int32(0); return
github
philippboehmsturm/antx-master
normals.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/normals.m
2,391
utf_8
62a8e5ee7314da0eadbc13fa82ab95c1
function [nrm] = normals(pnt, dhk, opt); % NORMALS compute the surface normals of a triangular mesh % for each triangle or for each vertex % % [nrm] = normals(pnt, dhk, opt) % where opt is either 'vertex' or 'triangle' % Copyright (C) 2002-2007, 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: normals.m 2885 2011-02-16 09:41:58Z roboos $ if nargin<3 opt='vertex'; elseif (opt(1)=='v' | opt(1)=='V') opt='vertex'; elseif (opt(1)=='t' | opt(1)=='T') opt='triangle'; else error('invalid optional argument'); end npnt = size(pnt,1); ndhk = size(dhk,1); % shift to center pnt(:,1) = pnt(:,1)-mean(pnt(:,1),1); pnt(:,2) = pnt(:,2)-mean(pnt(:,2),1); pnt(:,3) = pnt(:,3)-mean(pnt(:,3),1); % compute triangle normals nrm_dhk = zeros(ndhk, 3); for i=1:ndhk v2 = pnt(dhk(i,2),:) - pnt(dhk(i,1),:); v3 = pnt(dhk(i,3),:) - pnt(dhk(i,1),:); nrm_dhk(i,:) = cross(v2, v3); end if strcmp(opt, 'vertex') % compute vertex normals nrm_pnt = zeros(npnt, 3); for i=1:ndhk nrm_pnt(dhk(i,1),:) = nrm_pnt(dhk(i,1),:) + nrm_dhk(i,:); nrm_pnt(dhk(i,2),:) = nrm_pnt(dhk(i,2),:) + nrm_dhk(i,:); nrm_pnt(dhk(i,3),:) = nrm_pnt(dhk(i,3),:) + nrm_dhk(i,:); end % normalise the direction vectors to have length one nrm = nrm_pnt ./ (sqrt(sum(nrm_pnt.^2, 2)) * ones(1,3)); else % normalise the direction vectors to have length one nrm = nrm_dhk ./ (sqrt(sum(nrm_dhk.^2, 2)) * ones(1,3)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fast cross product to replace the Matlab standard version function [c] = cross(a,b) c = [a(2)*b(3)-a(3)*b(2) a(3)*b(1)-a(1)*b(3) a(1)*b(2)-a(2)*b(1)];
github
philippboehmsturm/antx-master
rejectvisual_trial.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/rejectvisual_trial.m
9,119
utf_8
945cc5cc5b3b80e76833663a16adfc5f
function [chansel, trlsel, cfg] = rejectvisual_trial(cfg, data); % SUBFUNCTION for ft_rejectvisual % determine the initial selection of trials and channels nchan = length(data.label); ntrl = length(data.trial); cfg.channel = ft_channelselection(cfg.channel, data.label); trlsel = true(1,ntrl); chansel = false(1,nchan); chansel(match_str(data.label, cfg.channel)) = 1; % compute the sampling frequency from the first two timepoints fsample = 1/(data.time{1}(2) - data.time{1}(1)); % compute the offset from the time axes offset = zeros(ntrl,1); for i=1:ntrl offset(i) = time2offset(data.time{i}, fsample); end ft_progress('init', cfg.feedback, 'filtering data'); for i=1:ntrl ft_progress(i/ntrl, 'filtering data in trial %d of %d\n', i, ntrl); [data.trial{i}, label, time, cfg.preproc] = preproc(data.trial{i}, data.label, fsample, cfg.preproc, offset(i)); end ft_progress('close'); % select the specified latency window from the data % this is done AFTER the filtering to prevent edge artifacts for i=1:ntrl begsample = nearest(data.time{i}, cfg.latency(1)); endsample = nearest(data.time{i}, cfg.latency(2)); data.time{i} = data.time{i}(begsample:endsample); data.trial{i} = data.trial{i}(:,begsample:endsample); end h = figure; axis([0 1 0 1]); axis off % the info structure will be attached to the figure % and passed around between the callback functions if strcmp(cfg.plotlayout,'1col') % hidden config option for plotting trials differently info = []; info.ncols = 1; info.nrows = nchan; info.chanlop = 1; info.trlop = 1; info.ltrlop = 0; info.quit = 0; info.ntrl = ntrl; info.nchan = nchan; info.data = data; info.cfg = cfg; info.offset = offset; info.chansel = chansel; info.trlsel = trlsel; % determine the position of each subplot within the axis for row=1:info.nrows for col=1:info.ncols indx = (row-1)*info.ncols + col; if indx>info.nchan continue end info.x(indx) = (col-0.9)/info.ncols; info.y(indx) = 1 - (row-0.45)/(info.nrows+1); end end info.label = info.data.label; elseif strcmp(cfg.plotlayout,'square') info = []; info.ncols = ceil(sqrt(nchan)); info.nrows = ceil(sqrt(nchan)); info.chanlop = 1; info.trlop = 1; info.ltrlop = 0; info.quit = 0; info.ntrl = ntrl; info.nchan = nchan; info.data = data; info.cfg = cfg; info.offset = offset; info.chansel = chansel; info.trlsel = trlsel; % determine the position of each subplot within the axis for row=1:info.nrows for col=1:info.ncols indx = (row-1)*info.ncols + col; if indx>info.nchan continue end info.x(indx) = (col-0.9)/info.ncols; info.y(indx) = 1 - (row-0.45)/(info.nrows+1); end end info.label = info.data.label; end info.ui.quit = uicontrol(h,'units','pixels','position',[ 5 5 40 18],'String','quit','Callback',@stop); info.ui.prev = uicontrol(h,'units','pixels','position',[ 50 5 25 18],'String','<','Callback',@prev); info.ui.next = uicontrol(h,'units','pixels','position',[ 75 5 25 18],'String','>','Callback',@next); info.ui.prev10 = uicontrol(h,'units','pixels','position',[105 5 25 18],'String','<<','Callback',@prev10); info.ui.next10 = uicontrol(h,'units','pixels','position',[130 5 25 18],'String','>>','Callback',@next10); info.ui.bad = uicontrol(h,'units','pixels','position',[160 5 50 18],'String','bad','Callback',@markbad); info.ui.good = uicontrol(h,'units','pixels','position',[210 5 50 18],'String','good','Callback',@markgood); info.ui.badnext = uicontrol(h,'units','pixels','position',[270 5 50 18],'String','bad>','Callback',@markbad_next); info.ui.goodnext = uicontrol(h,'units','pixels','position',[320 5 50 18],'String','good>','Callback',@markgood_next); set(gcf, 'WindowButtonUpFcn', @button); set(gcf, 'KeyPressFcn', @key); guidata(h,info); interactive = 1; while interactive && ishandle(h) redraw(h); info = guidata(h); if info.quit == 0, uiwait; else chansel = info.chansel; trlsel = info.trlsel; delete(h); break end end % while interactive %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function varargout = markbad_next(varargin) markbad(varargin{:}); next(varargin{:}); function varargout = markgood_next(varargin) markgood(varargin{:}); next(varargin{:}); function varargout = next(h, eventdata, handles, varargin) info = guidata(h); info.ltrlop = info.trlop; if info.trlop < info.ntrl, info.trlop = info.trlop + 1; end; guidata(h,info); uiresume; function varargout = prev(h, eventdata, handles, varargin) info = guidata(h); info.ltrlop = info.trlop; if info.trlop > 1, info.trlop = info.trlop - 1; end; guidata(h,info); uiresume; function varargout = next10(h, eventdata, handles, varargin) info = guidata(h); info.ltrlop = info.trlop; if info.trlop < info.ntrl - 10, info.trlop = info.trlop + 10; else info.trlop = info.ntrl; end; guidata(h,info); uiresume; function varargout = prev10(h, eventdata, handles, varargin) info = guidata(h); info.ltrlop = info.trlop; if info.trlop > 10, info.trlop = info.trlop - 10; else info.trlop = 1; end; guidata(h,info); uiresume; function varargout = markgood(h, eventdata, handles, varargin) info = guidata(h); info.trlsel(info.trlop) = 1; fprintf(description_trial(info)); title(description_trial(info)); guidata(h,info); % uiresume; function varargout = markbad(h, eventdata, handles, varargin) info = guidata(h); info.trlsel(info.trlop) = 0; fprintf(description_trial(info)); title(description_trial(info)); guidata(h,info); % uiresume; function varargout = key(h, eventdata, handles, varargin) info = guidata(h); switch lower(eventdata.Key) case 'rightarrow' if info.trlop ~= info.ntrl next(h); else fprintf('at last trial\n'); end case 'leftarrow' if info.trlop ~= 1 prev(h); else fprintf('at first trial\n'); end case 'g' markgood(h); case 'b' markbad(h); case 'q' stop(h); otherwise fprintf('unknown key pressed\n'); end function varargout = button(h, eventdata, handles, varargin) pos = get(gca, 'CurrentPoint'); x = pos(1,1); y = pos(1,2); info = guidata(h); dx = info.x - x; dy = info.y - y; dd = sqrt(dx.^2 + dy.^2); [d, i] = min(dd); if d<0.5/max(info.nrows, info.ncols) && i<=info.nchan info.chansel(i) = ~info.chansel(i); % toggle info.chanlop = i; fprintf(description_channel(info)); guidata(h,info); uiresume; else fprintf('button clicked\n'); return end function varargout = stop(h, eventdata, handles, varargin) info = guidata(h); info.quit = 1; guidata(h,info); uiresume; function str = description_channel(info); if info.chansel(info.chanlop) str = sprintf('channel %s marked as GOOD\n', info.data.label{info.chanlop}); else str = sprintf('channel %s marked as BAD\n', info.data.label{info.chanlop}); end function str = description_trial(info); if info.trlsel(info.trlop) str = sprintf('trial %d marked as GOOD\n', info.trlop); else str = sprintf('trial %d marked as BAD\n', info.trlop); end function redraw(h) if ~ishandle(h) return end info = guidata(h); fprintf(description_trial(info)); cla; title(''); drawnow hold on dat = info.data.trial{info.trlop}; time = info.data.time{info.trlop}; if ~isempty(info.cfg.alim) % use fixed amplitude limits for amplitude scaling amax = info.cfg.alim; else % use automatic amplitude limits for scaling, these are different for each trial amax = max(max(abs(dat(info.chansel,:)))); end tmin = time(1); tmax = time(end); % scale the time values between 0.1 and 0.9 time = 0.1 + 0.8*(time-tmin)/(tmax-tmin); % scale the amplitude values between -0.5 and 0.5, offset should not be removed dat = dat ./ (2*amax); for row=1:info.nrows for col=1:info.ncols chanindx = (row-1)*info.ncols + col; if chanindx>info.nchan || ~info.chansel(chanindx) continue end % scale the time values for this subplot tim = (col-1)/info.ncols + time/info.ncols; % scale the amplitude values for this subplot amp = dat(chanindx,:)./info.nrows + 1 - row/(info.nrows+1); plot(tim, amp, 'k') end end % enable or disable buttons as appropriate if info.trlop == 1 set(info.ui.prev, 'Enable', 'off'); set(info.ui.prev10, 'Enable', 'off'); else set(info.ui.prev, 'Enable', 'on'); set(info.ui.prev10, 'Enable', 'on'); end if info.trlop == info.ntrl set(info.ui.next, 'Enable', 'off'); set(info.ui.next10, 'Enable', 'off'); else set(info.ui.next, 'Enable', 'on'); set(info.ui.next10, 'Enable', 'on'); end if info.ltrlop == info.trlop && info.trlop == info.ntrl set(info.ui.badnext,'Enable', 'off'); set(info.ui.goodnext,'Enable', 'off'); else set(info.ui.badnext,'Enable', 'on'); set(info.ui.goodnext,'Enable', 'on'); end text(info.x, info.y, info.label); title(description_trial(info)); hold off
github
philippboehmsturm/antx-master
wizard_base.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/wizard_base.m
11,678
utf_8
98f06b96b2740061c19fde46d418bc51
function h = wizard_gui(filename) % This is the low level wizard function. It evaluates the matlab content % in the workspace of the calling function. To prevent overwriting % variables in the BASE workspace, this function should be called from a % wrapper function. The wrapper function whoudl pause execution untill the % wizard figure is deleted. % Copyright (C) 2007, 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: wizard_base.m 952 2010-04-21 18:29:51Z roboos $ % create a new figure h = figure('Name','Wizard',... 'NumberTitle','off',... 'MenuBar','none',... 'KeyPressFcn', @cb_keyboard,... 'resizeFcn', @cb_resize,... 'closeRequestFcn', @cb_cancel); % movegui(h,'center'); % set(h, 'ToolBar', 'figure'); if nargin>0 filename = which(filename); [p, f, x] = fileparts(filename); data = []; data.path = p; data.file = f; data.ext = x; data.current = 0; data.script = script_parse(filename); guidata(h, data); % attach the data to the GUI figure else data = []; data.path = []; data.file = []; data.ext = []; data.current = 0; data.script = script_parse([]); guidata(h, data); % attach the data to the GUI figure cb_load(h); end cb_show(h); % show the GUI figure return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_keyboard(h, eventdata) h = parentfig(h); dbstack if isequal(eventdata.Key, 'o') && isequal(eventdata.Modifier, {'control'}) cb_load(h); elseif isequal(eventdata.Key, 's') && isequal(eventdata.Modifier, {'control'}) cb_save(h); elseif isequal(eventdata.Key, 'e') && isequal(eventdata.Modifier, {'control'}) cb_edit(h); elseif isequal(eventdata.Key, 'p') && isequal(eventdata.Modifier, {'control'}) cb_prev(h); elseif isequal(eventdata.Key, 'n') && isequal(eventdata.Modifier, {'control'}) cb_next(h); elseif isequal(eventdata.Key, 'q') && isequal(eventdata.Modifier, {'control'}) cb_cancel(h); elseif isequal(eventdata.Key, 'x') && isequal(eventdata.Modifier, {'control'}) % FIXME this does not work cb_done(h); elseif isequal(eventdata.Key, 'n') && any(strcmp(eventdata.Modifier, 'shift')) && any(strcmp(eventdata.Modifier, 'control')) % FIXME this does not always work correctly cb_skip(h); end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_show(h, eventdata) h = parentfig(h); data = guidata(h); clf(h); if data.current<1 % introduction, construct the GUI elements ui_next = uicontrol(h, 'tag', 'ui_next', 'KeyPressFcn', @cb_keyboard, 'style', 'pushbutton', 'string', 'next >', 'callback', @cb_next); ui_help = uicontrol(h, 'tag', 'ui_help', 'KeyPressFcn', @cb_keyboard, 'style', 'text', 'max', 10, 'horizontalAlignment', 'left', 'FontName', '', 'backgroundColor', get(h, 'color')); % display the introduction text title = cat(2, data.file, ' - introduction'); tmp = {data.script.title}; help = sprintf('%s\n', tmp{:}); help = sprintf('This wizard will help you through the following steps:\n\n%s', help); set(ui_help, 'string', help); set(h, 'Name', title); elseif data.current>length(data.script) % finalization, construct the GUI elements ui_prev = uicontrol(h, 'tag', 'ui_prev', 'KeyPressFcn', @cb_keyboard, 'style', 'pushbutton', 'string', '< prev', 'callback', @cb_prev); ui_next = uicontrol(h, 'tag', 'ui_next', 'KeyPressFcn', @cb_keyboard, 'style', 'pushbutton', 'string', 'finish', 'callback', @cb_done); ui_help = uicontrol(h, 'tag', 'ui_help', 'KeyPressFcn', @cb_keyboard, 'style', 'text', 'max', 10, 'horizontalAlignment', 'left', 'FontName', '', 'backgroundColor', get(h, 'color')); % display the finalization text title = cat(2, data.file, ' - finish'); help = sprintf('If you click finish, the variables created by the script will be exported to the Matlab workspace\n'); set(ui_help, 'string', help); set(h, 'Name', title); else % normal wizard step, construct the GUI elements ui_prev = uicontrol(h, 'tag', 'ui_prev', 'KeyPressFcn', @cb_keyboard, 'style', 'pushbutton', 'string', '< prev', 'callback', @cb_prev); ui_next = uicontrol(h, 'tag', 'ui_next', 'KeyPressFcn', @cb_keyboard, 'style', 'pushbutton', 'string', 'next >', 'callback', @cb_next); ui_help = uicontrol(h, 'tag', 'ui_help', 'KeyPressFcn', @cb_keyboard, 'style', 'text', 'max', 10, 'horizontalAlignment', 'left', 'FontName', '', 'backgroundColor', get(h, 'color')); ui_code = uicontrol(h, 'tag', 'ui_code', 'KeyPressFcn', @cb_keyboard, 'style', 'edit', 'max', 10, 'horizontalAlignment', 'left', 'FontName', 'Courier', 'backgroundColor', 'white'); % display the current wizard content help = data.script(data.current).help; code = data.script(data.current).code; title = cat(2, data.file, ' - ', data.script(data.current).title); set(ui_help, 'string', help); set(ui_code, 'string', code); set(h, 'Name', title); end cb_resize(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_resize(h, eventdata) h = parentfig(h); ui_prev = findobj(h, 'tag', 'ui_prev'); ui_next = findobj(h, 'tag', 'ui_next'); ui_help = findobj(h, 'tag', 'ui_help'); ui_code = findobj(h, 'tag', 'ui_code'); siz = get(h, 'position'); x = siz(3); y = siz(4); w = (y-40-20)/2; if ~isempty(ui_prev) set(ui_prev, 'position', [x-150 10 60 20]); end if ~isempty(ui_next) set(ui_next, 'position', [x-080 10 60 20]); end if ~isempty(ui_code) && ~isempty(ui_help) set(ui_code, 'position', [10 40 x-20 w]); set(ui_help, 'position', [10 50+w x-20 w]); else set(ui_help, 'position', [10 40 x-20 y-50]); end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_prev(h, eventdata) h = parentfig(h); cb_disable(h); data = guidata(h); if data.current>0 data.current = data.current - 1; end guidata(h, data); cb_show(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_next(h, eventdata) h = parentfig(h); cb_disable(h); data = guidata(h); if data.current>0 title = cat(2, data.file, ' - busy'); set(h, 'Name', title); ui_code = findobj(h, 'tag', 'ui_code'); code = get(ui_code, 'string'); try for i=1:size(code,1) evalin('caller', code(i,:)); end catch lasterr; end data.script(data.current).code = code; end data.current = data.current+1; guidata(h, data); cb_show(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_skip(h, eventdata) h = parentfig(h); cb_disable(h); data = guidata(h); data.current = data.current+1; guidata(h, data); cb_show(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_disable(h, eventdata) h = parentfig(h); ui_prev = findobj(h, 'tag', 'ui_prev'); ui_next = findobj(h, 'tag', 'ui_next'); ui_help = findobj(h, 'tag', 'ui_help'); ui_code = findobj(h, 'tag', 'ui_code'); set(ui_prev, 'Enable', 'off'); set(ui_next, 'Enable', 'off'); set(ui_help, 'Enable', 'off'); set(ui_code, 'Enable', 'off'); drawnow return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_enable(h, eventdata) h = parentfig(h); ui_prev = findobj(h, 'tag', 'ui_prev'); ui_next = findobj(h, 'tag', 'ui_next'); ui_help = findobj(h, 'tag', 'ui_help'); ui_code = findobj(h, 'tag', 'ui_code'); set(ui_prev, 'Enable', 'on'); set(ui_next, 'Enable', 'on'); set(ui_help, 'Enable', 'on'); set(ui_code, 'Enable', 'on'); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_edit(h, eventdata) h = parentfig(h); data = guidata(h); filename = fullfile(data.path, [data.file data.ext]); edit(filename); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_load(h, eventdata) h = parentfig(h); cb_disable(h); [f, p] = uigetfile('*.m', 'Load script from an M-file'); if ~isequal(f,0) data = guidata(h); filename = fullfile(p, f); [p, f, x] = fileparts(filename); str = script_parse(filename); data.script = str; data.current = 0; data.path = p; data.file = f; data.ext = x; guidata(h, data); cb_show(h); end cb_enable(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_save(h, eventdata) cb_disable(h); data = guidata(h); filename = fullfile(data.path, [data.file data.ext]); [f, p] = uiputfile('*.m', 'Save script to an M-file', filename); if ~isequal(f,0) filename = fullfile(p, f); [p, f, x] = fileparts(filename); fid = fopen(filename, 'wt'); script = data.script; for k=1:length(script) fprintf(fid, '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n'); for i=1:size(script(k).help, 1) fprintf(fid, '%% %s\n', deblank(script(k).help(i,:))); end for i=1:size(script(k).code, 1) fprintf(fid, '%s\n', deblank(script(k).code(i,:))); end end fclose(fid); data.path = p; data.file = f; data.ext = x; guidata(h, data); cb_show(h); end cb_enable(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_done(h, eventdata) h = parentfig(h); cb_disable(h); assignin('caller', 'wizard_ok', 1); delete(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_cancel(h, eventdata) h = parentfig(h); cb_disable(h); assignin('caller', 'wizard_ok', 0); delete(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function script = script_parse(filename) if isempty(filename) script.title = ''; script.help = ''; script.code = ''; return end fid = fopen(filename); str = {}; while ~feof(fid) str{end+1} = fgetl(fid); end str = str(:); fclose(fid); i = 1; % line number k = 1; % block number script = []; while i<=length(str) script(k).title = {}; script(k).help = {}; script(k).code = {}; while i<=length(str) && ~isempty(regexp(str{i}, '^%%%%', 'once')) % skip the seperator lines i = i+1; end while i<=length(str) && ~isempty(regexp(str{i}, '^%', 'once')) script(k).help{end+1} = str{i}(2:end); i = i+1; end while i<=length(str) && isempty(regexp(str{i}, '^%%%%', 'once')) script(k).code{end+1} = str{i}; i = i+1; end k = k+1; end sel = false(size(script)); for k=1:length(script) sel(k) = isempty(script(k).help) && isempty(script(k).code); if length(script(k).help)>0 script(k).title = char(script(k).help{1}); else script(k).title = '<unknown>'; end script(k).help = char(script(k).help(:)); script(k).code = char(script(k).code(:)); end script(sel) = []; return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = parentfig(h) while get(h, 'parent') h = get(h, 'parent'); end return
github
philippboehmsturm/antx-master
spikesort.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/spikesort.m
5,888
utf_8
5c6df4c516e14b804e816e99bc002149
function [numA, numB, indA, indB] = spikesort(numA, numB, varargin); % SPIKESORT uses a variation on the cocktail sort algorithm in combination % with a city block distance to achieve N-D trial pairing between spike % counts. The sorting is not guaranteed to result in the optimal pairing. A % linear pre-sorting algorithm is used to create good initial starting % positions. % % The goal of this function is to achieve optimal trial-pairing prior to % stratifying the spike numbers in two datasets by random removal of some % spikes in the trial and channel with the largest numnber of spikes. % Pre-sorting based on the city-block distance between the spike count % ensures that as few spikes as possible are lost. % % Use as % [srtA, srtB, indA, indB] = spikesort(numA, numB, ...) % % Optional arguments should be specified as key-value pairs and can include % 'presort' number representing the column, 'rowwise' or 'global' % % Example % numA = reshape(randperm(100*3), 100, 3); % numB = reshape(randperm(100*3), 100, 3); % [srtA, srtB, indA, indB] = spikesort(numA, numB); % % check that the order is correct, the following should be zero % numA(indA,:) - srtA % numB(indB,:) - srtB % % See also COCKTAILSORT % Copyright (C) 2007, 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: spikesort.m 952 2010-04-21 18:29:51Z roboos $ % use global flag for debugging global fb if isempty(fb) fb = 0; end % get the options presort = keyval('presort', varargin); if any(size(numA)~=size(numB)) error('input dimensions should be the same'); end bottom = 1; top = size(numA,1); swapped = true; dist = zeros(1,top); % this will hold the distance between the trials in each pair distswap = zeros(1,2); % this will hold the distance for two trials after swapping % this is to keep track of the row-ordering during sorting sel = 1:size(numA,2); numA(:,end+1) = 1:top; numB(:,end+1) = 1:top; % compute the initial distance between the trial pairs using city block distance metric for i=1:top dist(i) = sum(abs(numA(i,sel)-numB(i,sel))); end if fb fprintf('initial cost = %d\n', sum(dist)); end if isnumeric(presort) % start by pre-sorting on the first column only [dum, indA] = sort(numA(:,presort)); [dum, indB] = sort(numB(:,presort)); numA = numA(indA,:); numB = numB(indB,:); elseif strcmp(presort, 'rowwise') full = cityblock(numA(:,sel), numB(:,sel)); link = zeros(1,top); for i=1:top d = full(i,:); d(link(1:(i-1))) = inf; [m, ind] = min(d); link(i) = ind; end indA = 1:top; indB = link; numB = numB(link,:); elseif strcmp(presort, 'global') full = cityblock(numA(:,sel), numB(:,sel)); link = zeros(1,top); while ~all(link) [m, i] = min(full(:)); [j, k] = ind2sub(size(full), i); full(j,:) = inf; full(:,k) = inf; link(j) = k; end indA = 1:top; indB = link; numB = numB(link,:); end % compute the initial distance between the trial pairs % using city block distance metric for i=1:top dist(i) = sum(abs(numA(i,sel)-numB(i,sel))); end if fb fprintf('cost after pre-sort = %d\n', sum(dist)); end while swapped swapped = false; for i=bottom:(top-1) % compute the distances between the trials after swapping % using city block distance metric distswap(1) = sum(abs(numA(i,sel)-numB(i+1,sel))); distswap(2) = sum(abs(numA(i+1,sel)-numB(i,sel))); costNow = sum(dist([i i+1])); costSwp = sum(distswap); if costNow>costSwp % test whether the two elements are in the correct order numB([i i+1], :) = numB([i+1 i], :); % let the two elements change places dist([i i+1]) = distswap; % update the distance vector swapped = true; end end % decreases `top` because the element with the largest value in the unsorted % part of the list is now on the position top top = top - 1; for i=top:-1:(bottom+1) % compute the distances between the trials after swapping % using city block distance metric distswap(1) = sum(abs(numA(i,sel)-numB(i-1,sel))); distswap(2) = sum(abs(numA(i-1,sel)-numB(i,sel))); costNow = sum(dist([i i-1])); costSwp = sum(distswap); if costNow>costSwp numB([i i-1], :) = numB([i-1 i], :); % let the two elements change places dist([i i-1]) = distswap; % update the distance vector swapped = true; end end % increases `bottom` because the element with the smallest value in the unsorted % part of the list is now on the position bottom bottom = bottom + 1; end % while swapped if fb fprintf('final cost = %d\n', sum(dist)); end indA = numA(:,end); numA = numA(:,sel); indB = numB(:,end); numB = numB(:,sel); end % function spikesort %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function d = cityblock(a, b) d = zeros(size(a,1), size(b,1)); for i=1:size(a,1) for j=1:size(b,1) d(i,j) = sum(abs(a(i,:)-b(j,:))); end end end % function cityblock
github
philippboehmsturm/antx-master
nansum.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/nansum.m
2,076
utf_8
d6579c8dc9f4712aa24dfce348a7bd56
% nansum() - Take the sum, not considering NaN values % % Usage: same as sum() % Author: Arnaud Delorme, CNL / Salk Institute, 16 Oct 2002 %123456789012345678901234567890123456789012345678901234567890123456789012 % 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 % 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: nansum.m 2885 2011-02-16 09:41:58Z roboos $ function out = nansum(in, dim) if nargin < 1 help nansum; return; end; if nargin < 2 if size(in,1) ~= 1 dim = 1; elseif size(in,2) ~= 1 dim = 2; else dim = 3; end; end; tmpin = in; tmpin(find(isnan(in(:)))) = 0; out = sum(tmpin, dim);
github
philippboehmsturm/antx-master
shiftpredict.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/shiftpredict.m
8,737
utf_8
e5898e2a69f8ec80039bf23508a498bc
function [prb, cohobs, mcohrnd] = shiftpredict(cfg, dat, datindx, refindx, trltapcnt); % SHIFTPREDICT implements a shift-predictor for testing significance % of coherence within a single condition. This function is a subfunction % for SOURCESTATISTICS_SHIFTPREDICT and FREQSTATISTICS_SHIFTPREDICT. % % cfg.method % cfg.numrandomization % cfg.method % cfg.method % cfg.loopdim % cfg.feedback % cfg.method % cfg.loopdim % cfg.correctm % cfg.tail % TODO this function should be reimplemented as statfun_shiftpredict for the general statistics framework % 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: shiftpredict.m 952 2010-04-21 18:29:51Z roboos $ nsgn = size(dat,1); ntap = size(dat,2); % total number of tapers over all trials nfrq = size(dat,3); if nargin<4 % assume that each trial consists of a single taper only ntrl = size(dat,2); trltapcnt = ones(1,ntrl); fprintf('assuming one taper per trial\n'); else % each trial contains multiple tapers ntrl = length(trltapcnt); trltapcnt = trltapcnt(:)'; fprintf('number of tapers varies from %d to %d\n', min(trltapcnt), max(trltapcnt)); end % allocate memory to hold the probabilities if version('-release')>=14 prb_pos = zeros(length(refindx),length(datindx),nfrq, 'single'); prb_neg = zeros(length(refindx),length(datindx),nfrq, 'single'); else prb_pos = zeros(length(refindx),length(datindx),nfrq); prb_neg = zeros(length(refindx),length(datindx),nfrq); end % compute the power per taper, per trial, and in total pow_tap = (abs(dat).^2); pow_trl = zeros(nsgn,ntrl,nfrq); for i=1:ntrl % this is the taper selection if the number of tapers per trial is different tapbeg = 1 + sum([0 trltapcnt(1:(i-1))]); tapend = sum([0 trltapcnt(1:(i ))]); % this would be the taper selection if the number of tapers per trial is identical % tapbeg = 1 + (i-1)*ntap; % tapend = (i )*ntap; % average the power per trial over the tapers in that trial pow_trl(:,i,:) = mean(pow_tap(:,tapbeg:tapend,:),2); end pow_tot = reshape(mean(pow_trl,2), nsgn, nfrq); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % normalise the data, also see the COMPUTECOH subfunction switch cfg.method case {'abscoh', 'imagcoh', 'absimagcoh', 'atanh', 'atanh_randphase'} % normalise, so that the complex conjugate multiplication immediately results in coherence if ~all(trltapcnt==trltapcnt(1)) error('all trials should have the same number of tapers'); end for i=1:nsgn for k=1:nfrq dat(i,:,k) = dat(i,:,k) ./ sqrt(pow_tot(i,k)*ntrl*trltapcnt(1)); end end case {'amplcorr', 'absamplcorr'} % normalize so that the multiplication immediately results in correlation % this uses the amplitude, which is the sqrt of the power per trial dat = sqrt(pow_trl); % each signal should have zero mean fa = reshape(mean(dat,2), nsgn, nfrq); % mean over trials for i=1:ntrl dat(:,i,:) = (dat(:,i,:) - fa); end % each signal should have unit variance fs = reshape(sqrt(sum(dat.^2,2)/ntrl), nsgn, nfrq); % standard deviation over trials for i=1:ntrl dat(:,i,:) = dat(:,i,:)./fs; end % also normalize for the number of trials dat = dat./sqrt(ntrl); otherwise error('unknown method for shift-predictor') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % create the random shuffling index vectors nrnd = cfg.numrandomization; randsel = []; switch cfg.method case {'abscoh', 'imagcoh', 'absimagcoh', 'atanh'} for i=1:nrnd % the number of tapers is identical for each trial randsel(i,:) = randblockshift(1:sum(trltapcnt), trltapcnt(1)); end case {'amplcorr', 'absamplcorr'} for i=1:nrnd randsel(i,:) = randperm(ntrl); end case {'atanh_randphase'}, for i=1:nrnd rndphs = exp(j.*2.*pi.*rand(length(unique(cfg.origtrl)))); randsel(i,:) = rndphs(cfg.origtrl); end end % select the subset of reference signals if all(refindx(:)'==1:size(dat,1)) % only make a shallow copy to save memory datref = dat; else % make a deep copy of the selected data datref = dat(refindx,:,:); end % select the subset of target signals if all(datindx(:)'==1:size(dat,1)) % only make a shallow copy to save memory dat = dat; else % make a deep copy of the selected data dat = dat(datindx,:,:); end % compute the observed coherence cohobs = computecoh(datref, dat, cfg.method, cfg.loopdim); mcohrnd = zeros(size(cohobs)); progress('init', cfg.feedback, 'Computing shift-predicted coherence'); for i=1:nrnd progress(i/nrnd, 'Computing shift-predicted coherence %d/%d\n', i, nrnd); % randomize the reference signal and re-compute coherence if all(isreal(randsel(i,:))), datrnd = datref(:,randsel(i,:),:); else datrnd = datref.*conj(repmat(randsel(i,:), [size(datref,1) 1 size(datref,3)])); end cohrnd = computecoh(datrnd, dat, cfg.method, cfg.loopdim); mcohrnd = cohrnd + mcohrnd; % compare the observed coherence with the randomized one if strcmp(cfg.correctm, 'yes') prb_pos = prb_pos + (cohobs<max(cohrnd(:))); prb_neg = prb_neg + (cohobs>min(cohrnd(:))); else prb_pos = prb_pos + (cohobs<cohrnd); prb_neg = prb_neg + (cohobs>cohrnd); end end progress('close'); mcohrnd = mcohrnd./nrnd; if cfg.tail==1 clear prb_neg % not needed any more, free some memory prb = prb_pos./nrnd; elseif cfg.tail==-1 clear prb_pos % not needed any more, free some memory prb = prb_neg./nrnd; else prb_neg = prb_neg./nrnd; prb_pos = prb_pos./nrnd; % for each observation select the tail that corresponds with the lowest probability prb = min(prb_neg, prb_pos); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % this assumes that the data is properly normalised % and assumes that all trials have the same number of tapers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function coh = computecoh(datref, dat, method, loopdim) nref = size(datref,1); nsgn = size(dat,1); nfrq = size(dat,3); coh = zeros(nref,nsgn,nfrq); switch loopdim case 3 % for each frequency, simultaneously compute coherence between all reference and target signals for i=1:nfrq switch method case 'abscoh' coh(:,:,i) = abs( datref(:,:,i) * dat(:,:,i)'); case 'imagcoh' coh(:,:,i) = imag(datref(:,:,i) * dat(:,:,i)'); case 'absimagcoh' coh(:,:,i) = abs(imag(datref(:,:,i) * dat(:,:,i)')); case {'atanh' 'atanh_randphase'} coh(:,:,i) = atanh(abs(datref(:,:,i)* dat(:,:,i)')); case 'amplcorr' coh(:,:,i) = datref(:,:,i) * dat(:,:,i)'; case 'absamplcorr' coh(:,:,i) = abs( datref(:,:,i) * dat(:,:,i)'); otherwise error('unsupported method'); end end case 1 % for each reference and target signal, simultaneously compute coherence over all frequencies for i=1:nref for k=1:nsgn switch method case 'abscoh' coh(i,k,:) = abs( sum(datref(i,:,:) .* conj(dat(k,:,:)), 2)); case 'imagcoh' coh(i,k,:) = imag(sum(datref(i,:,:) .* conj(dat(k,:,:)), 2)); case 'absimagcoh' coh(i,k,:) = abs(imag(sum(datref(i,:,:) .* conj(dat(k,:,:)), 2))); case {'atanh' 'atanh_randphase'} coh(i,k,:) = atanh(abs(sum(datref(i,:,:).* conj(dat(k,:,:)), 2))); case 'amplcorr' coh(i,k,:) = sum(datref(i,:,:) .* conj(dat(k,:,:)), 2); case 'absamplcorr' coh(i,k,:) = abs( sum(datref(i,:,:) .* conj(dat(k,:,:)), 2)); otherwise error('unsupported method'); end end end otherwise error('unsupported loopdim'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that shuffles in blocks %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [out] = randblockshift(n, k); n = n(:); nbin = length(n)/k; n = reshape(n, [k nbin]); n = n(:,randperm(nbin)); out = n(:);
github
philippboehmsturm/antx-master
postpad.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/postpad.m
2,013
utf_8
2c9539d77ff0f85c9f89108f4dc811e0
% Copyright (C) 1994, 1995, 1996, 1997, 1998, 2000, 2002, 2004, 2005, % 2006, 2007, 2008, 2009 John W. Eaton % % This file is part of Octave. % % Octave is free software; you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 3 of the License, or (at % your option) any later version. % % Octave is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % % You should have received a copy of the GNU General Public License % along with Octave; see the file COPYING. If not, see % <http://www.gnu.org/licenses/>. % -*- texinfo -*- % @deftypefn {Function File} {} postpad (@var{x}, @var{l}, @var{c}) % @deftypefnx {Function File} {} postpad (@var{x}, @var{l}, @var{c}, @var{dim}) % @seealso{prepad, resize} % @end deftypefn % Author: Tony Richardson <[email protected]> % Created: June 1994 function y = postpad (x, l, c, dim) if nargin < 2 || nargin > 4 %print_usage (); error('wrong number of input arguments, should be between 2 and 4'); end if nargin < 3 || isempty(c) c = 0; else if ~isscalar(c) error ('postpad: third argument must be empty or a scalar'); end end nd = ndims(x); sz = size(x); if nargin < 4 % Find the first non-singleton dimension dim = 1; while dim < nd+1 && sz(dim)==1 dim = dim + 1; end if dim > nd dim = 1; elseif ~(isscalar(dim) && dim == round(dim)) && dim > 0 && dim< nd+1 error('postpad: dim must be an integer and valid dimension'); end end if ~isscalar(l) || l<0 error ('second argument must be a positive scalar'); end if dim > nd sz(nd+1:dim) = 1; end d = sz(dim); if d >= l idx = cell(1,nd); for i = 1:nd idx{i} = 1:sz(i); end idx{dim} = 1:l; y = x(idx{:}); else sz(dim) = l-d; y = cat(dim, x, c * ones(sz)); end
github
philippboehmsturm/antx-master
statistics_wrapper.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/statistics_wrapper.m
23,511
utf_8
dcc5a9eab9191a3b0e10008f11254e8d
function [stat, cfg] = statistics_wrapper(cfg, varargin) % STATISTICS_WRAPPER performs the selection of the biological data for % timelock, frequency or source data and sets up the design vector or % matrix. % % The specific configuration options for selecting timelock, frequency % of source data are described in TIMELOCKSTATISTICS, FREQSTATISTICS and % SOURCESTATISTICS, respectively. % % After selecting the data, control is passed on to a data-independent % statistical subfunction that computes test statistics plus their associated % significance probabilities and critical values under some null-hypothesis. The statistical % subfunction that is called is STATISTICS_xxx, where cfg.method='xxx'. At % this moment, we have implemented two statistical subfunctions: % STATISTICS_ANALYTIC, which calculates analytic significance probabilities and critical % values (exact or asymptotic), and STATISTICS_MONTECARLO, which calculates % Monte-Carlo approximations of the significance probabilities and critical values. % % The specific configuration options for the statistical test are % described in STATISTICS_xxx. % This function depends on PREPARE_TIMEFREQ_DATA which has the following options: % cfg.avgoverchan % cfg.avgoverfreq % cfg.avgovertime % cfg.channel % cfg.channelcmb % cfg.datarepresentation (set in STATISTICS_WRAPPER cfg.datarepresentation = 'concatenated') % cfg.frequency % cfg.latency % cfg.precision % cfg.previous (set in STATISTICS_WRAPPER cfg.previous = []) % cfg.version (id and name set in STATISTICS_WRAPPER) % Copyright (C) 2005-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: statistics_wrapper.m 3834 2011-07-12 10:03:54Z jorhor $ % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamed', {'approach', 'method'}); cfg = ft_checkconfig(cfg, 'required', {'method'}); cfg = ft_checkconfig(cfg, 'forbidden', {'transform'}); % set the defaults if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end if ~isfield(cfg, 'latency'), cfg.latency = 'all'; end if ~isfield(cfg, 'frequency'), cfg.frequency = 'all'; end if ~isfield(cfg, 'roi'), cfg.roi = []; end if ~isfield(cfg, 'avgoverchan'), cfg.avgoverchan = 'no'; end if ~isfield(cfg, 'avgovertime'), cfg.avgovertime = 'no'; end if ~isfield(cfg, 'avgoverfreq'), cfg.avgoverfreq = 'no'; end if ~isfield(cfg, 'avgoverroi'), cfg.avgoverroi = 'no'; end % determine the type of the input and hence the output data if ~exist('OCTAVE_VERSION') [s, i] = dbstack; if length(s)>1 [caller_path, caller_name, caller_ext] = fileparts(s(2).name); else caller_path = ''; caller_name = ''; caller_ext = ''; end % evalin('caller', 'mfilename') does not work for Matlab 6.1 and 6.5 istimelock = strcmp(caller_name,'ft_timelockstatistics'); isfreq = strcmp(caller_name,'ft_freqstatistics'); issource = strcmp(caller_name,'ft_sourcestatistics'); else % cannot determine the calling function in Octave, try looking at the % data instead istimelock = isfield(varargin{1},'time') && ~isfield(varargin{1},'freq') && isfield(varargin{1},'avg'); isfreq = isfield(varargin{1},'time') && isfield(varargin{1},'freq'); issource = isfield(varargin{1},'pos') || isfield(varargin{1},'transform'); end if (istimelock+isfreq+issource)~=1 error('Could not determine the type of the input data'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % collect the biological data (the dependent parameter) % and the experimental design (the independent parameter) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if issource % test that all source inputs have the same dimensions and are spatially aligned for i=2:length(varargin) if isfield(varargin{1}, 'dim') && (length(varargin{i}.dim)~=length(varargin{1}.dim) || ~all(varargin{i}.dim==varargin{1}.dim)) error('dimensions of the source reconstructions do not match, use NORMALISEVOLUME first'); end if isfield(varargin{1}, 'pos') && (length(varargin{i}.pos(:))~=length(varargin{1}.pos(:)) || ~all(varargin{i}.pos(:)==varargin{1}.pos(:))) error('grid locations of the source reconstructions do not match, use NORMALISEVOLUME first'); end if isfield(varargin{1}, 'transform') && ~all(varargin{i}.transform(:)==varargin{1}.transform(:)) error('spatial coordinates of the source reconstructions do not match, use NORMALISEVOLUME first'); end end Nsource = length(varargin); Nvoxel = length(varargin{1}.inside) + length(varargin{1}.outside); if ~isempty(cfg.roi) if ischar(cfg.roi) cfg.roi = {cfg.roi}; end % the source representation should specify the position of each voxel in MNI coordinates x = varargin{1}.pos(:,1); % this is from left (negative) to right (positive) % determine the mask to restrict the subsequent analysis % process each of the ROIs, and optionally also left and/or right seperately roimask = {}; roilabel = {}; for i=1:length(cfg.roi) tmpcfg.roi = cfg.roi{i}; tmpcfg.inputcoord = cfg.inputcoord; tmpcfg.atlas = cfg.atlas; tmp = volumelookup(tmpcfg, varargin{1}); if strcmp(cfg.avgoverroi, 'no') && ~isfield(cfg, 'hemisphere') % no reason to deal with seperated left/right hemispheres cfg.hemisphere = 'combined'; end if strcmp(cfg.hemisphere, 'left') tmp(x>=0) = 0; % exclude the right hemisphere roimask{end+1} = tmp; roilabel{end+1} = ['Left ' cfg.roi{i}]; elseif strcmp(cfg.hemisphere, 'right') tmp(x<=0) = 0; % exclude the right hemisphere roimask{end+1} = tmp; roilabel{end+1} = ['Right ' cfg.roi{i}]; elseif strcmp(cfg.hemisphere, 'both') % deal seperately with the voxels on the left and right side of the brain tmpL = tmp; tmpL(x>=0) = 0; % exclude the right hemisphere tmpR = tmp; tmpR(x<=0) = 0; % exclude the left hemisphere roimask{end+1} = tmpL; roimask{end+1} = tmpR; roilabel{end+1} = ['Left ' cfg.roi{i}]; roilabel{end+1} = ['Right ' cfg.roi{i}]; clear tmpL tmpR elseif strcmp(cfg.hemisphere, 'combined') % all voxels of the ROI can be combined roimask{end+1} = tmp; roilabel{end+1} = cfg.roi{i}; else error('incorrect specification of cfg.hemisphere'); end clear tmp end % for each roi % note that avgoverroi=yes is implemented differently at a later stage % avgoverroi=no is implemented using the inside/outside mask if strcmp(cfg.avgoverroi, 'no') for i=2:length(roimask) % combine them all in the first mask roimask{1} = roimask{1} | roimask{i}; end roimask = roimask{1}; % only keep the combined mask % the source representation should have an inside and outside vector containing indices sel = find(~roimask); varargin{1}.inside = setdiff(varargin{1}.inside, sel); varargin{1}.outside = union(varargin{1}.outside, sel); clear roimask roilabel end % if avgoverroi=no end % get the source parameter on which the statistic should be evaluated if strcmp(cfg.parameter, 'mom') && isfield(varargin{1}, 'avg') && isfield(varargin{1}.avg, 'csdlabel') && isfield(varargin{1}, 'cumtapcnt') [dat, cfg] = get_source_pcc_mom(cfg, varargin{:}); elseif strcmp(cfg.parameter, 'mom') && isfield(varargin{1}, 'avg') && ~isfield(varargin{1}.avg, 'csdlabel') [dat, cfg] = get_source_lcmv_mom(cfg, varargin{:}); elseif isfield(varargin{1}, 'trial') [dat, cfg] = get_source_trial(cfg, varargin{:}); else [dat, cfg] = get_source_avg(cfg, varargin{:}); end cfg.dimord = 'voxel'; % note that avgoverroi=no is implemented differently at an earlier stage if strcmp(cfg.avgoverroi, 'yes') tmp = zeros(length(roimask), size(dat,2)); for i=1:length(roimask) % the data only reflects those points that are inside the brain, % the atlas-based mask reflects points inside and outside the brain roi = roimask{i}(varargin{1}.inside); tmp(i,:) = mean(dat(roi,:), 1); end % replace the original data with the average over each ROI dat = tmp; clear tmp roi roimask % remember the ROIs cfg.dimord = 'roi'; end elseif isfreq || istimelock % get the ERF/TFR data by means of PREPARE_TIMEFREQ_DATA cfg.datarepresentation = 'concatenated'; [cfg, data] = prepare_timefreq_data(cfg, varargin{:}); cfg = rmfield(cfg, 'datarepresentation'); dim = size(data.biol); if length(dim)<3 % seems to be singleton frequency and time dimension dim(3)=1; dim(4)=1; elseif length(dim)<4 % seems to be singleton time dimension dim(4)=1; end cfg.dimord = 'chan_freq_time'; % the dimension of the original data (excluding the replication dimension) has to be known for clustering cfg.dim = dim(2:end); % all dimensions have to be concatenated except the replication dimension and the data has to be transposed dat = transpose(reshape(data.biol, dim(1), prod(dim(2:end)))); % remove to save some memory data.biol = []; % add gradiometer/electrode information to the configuration if ~isfield(cfg,'neighbours') && isfield(cfg, 'correctm') && strcmp(cfg.correctm, 'cluster') error('You need to specify a neighbourstructure'); %cfg.neighbours = ft_neighbourselection(cfg,varargin{1}); end end % get the design from the information in cfg and data. if ~isfield(cfg,'design') warning('Please think about how you would create cfg.design. Soon the call to prepare_design will be deprecated') cfg.design = data.design; [cfg] = prepare_design(cfg); end if size(cfg.design,2)~=size(dat,2) cfg.design = transpose(cfg.design); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute the statistic, using the data-independent statistical subfunction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % determine the function handle to the intermediate-level statistics function if exist(['statistics_' cfg.method]) statmethod = str2func(['statistics_' cfg.method]); else error(sprintf('could not find the corresponding function for cfg.method="%s"\n', cfg.method)); end fprintf('using "%s" for the statistical testing\n', func2str(statmethod)); % check that the design completely describes the data if size(dat,2) ~= size(cfg.design,2) error('the size of the design matrix does not match the number of observations in the data'); end % determine the number of output arguments try % the nargout function in Matlab 6.5 and older does not work on function handles num = nargout(statmethod); catch num = 1; end design=cfg.design; cfg=rmfield(cfg,'design'); % to not confuse lower level functions with both cfg.design and design input % perform the statistical test if strcmp(func2str(statmethod),'statistics_montecarlo') % because statistics_montecarlo (or to be precise, clusterstat) requires to know whether it is getting source data, % the following (ugly) work around is necessary if num>1 [stat, cfg] = statmethod(cfg, dat, design, 'issource',issource); else [stat] = statmethod(cfg, dat, design, 'issource', issource); end else if num>1 [stat, cfg] = statmethod(cfg, dat, design); else [stat] = statmethod(cfg, dat, design); end end if isstruct(stat) % the statistical output contains multiple elements, e.g. F-value, beta-weights and probability statfield = fieldnames(stat); else % only the probability was returned as a single matrix, reformat into a structure dum = stat; stat = []; % this prevents a Matlab warning that appears from release 7.0.4 onwards stat.prob = dum; statfield = fieldnames(stat); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % add descriptive information to the output and rehape into the input format %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if issource if ~isfield(varargin{1},'dim') % FIX ME; this is added temporarily (20110427) to cope with ft_sourceanalysis output not having a dim field since r3273 varargin{1}.dim = [Nvoxel 1]; end if isempty(cfg.roi) || strcmp(cfg.avgoverroi, 'no') % remember the definition of the volume, assume that they are identical for all input arguments try stat.dim = varargin{1}.dim; end try stat.xgrid = varargin{1}.xgrid; end try stat.ygrid = varargin{1}.ygrid; end try stat.zgrid = varargin{1}.zgrid; end try stat.inside = varargin{1}.inside; end try stat.outside = varargin{1}.outside; end try stat.pos = varargin{1}.pos; end try stat.transform = varargin{1}.transform; end else stat.inside = 1:length(roilabel); stat.outside = []; stat.label = roilabel(:); end for i=1:length(statfield) tmp = getsubfield(stat, statfield{i}); if isfield(varargin{1}, 'inside') && numel(tmp)==length(varargin{1}.inside) % the statistic was only computed on voxels that are inside the brain % sort the inside and outside voxels back into their original place if islogical(tmp) tmp(varargin{1}.inside) = tmp; tmp(varargin{1}.outside) = false; else tmp(varargin{1}.inside) = tmp; tmp(varargin{1}.outside) = nan; end end if numel(tmp)==prod(varargin{1}.dim) % reshape the statistical volumes into the original format stat = setsubfield(stat, statfield{i}, reshape(tmp, varargin{1}.dim)); end end else haschan = isfield(data, 'label'); % this one remains relevant, even after averaging over channels haschancmb = isfield(data, 'labelcmb'); % this one remains relevant, even after averaging over channels hasfreq = strcmp(cfg.avgoverfreq, 'no') && ~any(isnan(data.freq)); hastime = strcmp(cfg.avgovertime, 'no') && ~any(isnan(data.time)); stat.dimord = ''; if haschan stat.dimord = [stat.dimord 'chan_']; stat.label = data.label; chandim = dim(2); elseif haschancmb stat.dimord = [stat.dimord 'chancmb_']; stat.labelcmb = data.labelcmb; chandim = dim(2); end if hasfreq stat.dimord = [stat.dimord 'freq_']; stat.freq = data.freq; freqdim = dim(3); end if hastime stat.dimord = [stat.dimord 'time_']; stat.time = data.time; timedim = dim(4); end if ~isempty(stat.dimord) % remove the last '_' stat.dimord = stat.dimord(1:(end-1)); end for i=1:length(statfield) try % reshape the fields that have the same dimension as the input data if strcmp(stat.dimord, 'chan') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim 1])); elseif strcmp(stat.dimord, 'chan_time') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim timedim])); elseif strcmp(stat.dimord, 'chan_freq') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim freqdim])); elseif strcmp(stat.dimord, 'chan_freq_time') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim freqdim timedim])); elseif strcmp(stat.dimord, 'chancmb_time') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim timedim])); elseif strcmp(stat.dimord, 'chancmb_freq') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim freqdim])); elseif strcmp(stat.dimord, 'chancmb_freq_time') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim freqdim timedim])); elseif strcmp(stat.dimord, 'time') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [1 timedim])); elseif strcmp(stat.dimord, 'freq') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [1 freqdim])); elseif strcmp(stat.dimord, 'freq_time') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [freqdim timedim])); end end end end return % statistics_wrapper main() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for extracting the data of interest % data resemples PCC beamed source reconstruction, multiple trials are coded in mom %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dat, cfg] = get_source_pcc_mom(cfg, varargin) Nsource = length(varargin); Nvoxel = length(varargin{1}.inside) + length(varargin{1}.outside); Ninside = length(varargin{1}.inside); dim = varargin{1}.dim; for i=1:Nsource dipsel = find(strcmp(varargin{i}.avg.csdlabel, 'scandip')); ntrltap = sum(varargin{i}.cumtapcnt); dat{i} = zeros(Ninside, ntrltap); for j=1:Ninside k = varargin{1}.inside(j); dat{i}(j,:) = reshape(varargin{i}.avg.mom{k}(dipsel,:), 1, ntrltap); end end % concatenate the data matrices of the individual input arguments dat = cat(2, dat{:}); % remember the dimension of the source data cfg.dim = dim; % remember which voxels are inside the brain cfg.inside = varargin{1}.inside; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for extracting the data of interest % data resemples LCMV beamed source reconstruction, mom contains timecourse %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dat, cfg] = get_source_lcmv_mom(cfg, varargin) Nsource = length(varargin); Nvoxel = length(varargin{1}.inside) + length(varargin{1}.outside); Ntime = length(varargin{1}.avg.mom{varargin{1}.inside(1)}); Ninside = length(varargin{1}.inside); dim = [varargin{1}.dim Ntime]; dat = zeros(Ninside*Ntime, Nsource); for i=1:Nsource % collect the 4D data of this input argument tmp = nan*zeros(Ninside, Ntime); for j=1:Ninside k = varargin{1}.inside(j); tmp(j,:) = reshape(varargin{i}.avg.mom{k}, 1, dim(4)); end dat(:,i) = tmp(:); end % remember the dimension of the source data cfg.dim = dim; % remember which voxels are inside the brain cfg.inside = varargin{1}.inside; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for extracting the data of interest % data contains single-trial or single-subject source reconstructions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dat, cfg] = get_source_trial(cfg, varargin) Nsource = length(varargin); Nvoxel = length(varargin{1}.inside) + length(varargin{1}.outside); for i=1:Nsource Ntrial(i) = length(varargin{i}.trial); end k = 1; for i=1:Nsource for j=1:Ntrial(i) tmp = getsubfield(varargin{i}.trial(j), cfg.parameter); if ~iscell(tmp), %dim = size(tmp); dim = [Nvoxel 1]; else dim = [Nvoxel size(tmp{varargin{i}.inside(1)})]; end if i==1 && j==1 && numel(tmp)~=Nvoxel, warning('the input-data contains more entries than the number of voxels in the volume, the data will be concatenated'); dat = zeros(prod(dim), sum(Ntrial)); %FIXME this is old code should be removed elseif i==1 && j==1 && iscell(tmp), warning('the input-data contains more entries than the number of voxels in the volume, the data will be concatenated'); dat = zeros(Nvoxel*numel(tmp{varargin{i}.inside(1)}), sum(Ntrial)); elseif i==1 && j==1, dat = zeros(Nvoxel, sum(Ntrial)); end if ~iscell(tmp), dat(:,k) = tmp(:); else Ninside = length(varargin{i}.inside); %tmpvec = (varargin{i}.inside-1)*prod(size(tmp{varargin{i}.inside(1)})); tmpvec = varargin{i}.inside; insidevec = []; for m = 1:numel(tmp{varargin{i}.inside(1)}) insidevec = [insidevec; tmpvec(:)+(m-1)*Nvoxel]; end insidevec = insidevec(:)'; tmpdat = reshape(permute(cat(3,tmp{varargin{1}.inside}), [3 1 2]), [Ninside numel(tmp{varargin{1}.inside(1)})]); dat(insidevec, k) = tmpdat(:); end % add original dimensionality of the data to the configuration, is required for clustering %FIXME: this was obviously wrong, because often trial-data is one-dimensional, so no dimensional information is present %cfg.dim = dim(2:end); k = k+1; end end if isfield(varargin{1}, 'inside') fprintf('only selecting voxels inside the brain for statistics (%.1f%%)\n', 100*length(varargin{1}.inside)/prod(dim)); for j=prod(dim(2:end)):-1:1 dat((j-1).*dim(1) + varargin{1}.outside, :) = []; end end % remember the dimension of the source data if ~isfield(cfg, 'dim') warning('for clustering on trial-based data you explicitly have to specify cfg.dim'); end % remember which voxels are inside the brain cfg.inside = varargin{1}.inside; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for extracting the data of interest % get the average source reconstructions, the repetitions are in multiple input arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dat, cfg] = get_source_avg(cfg, varargin) Nsource = length(varargin); Nvoxel = length(varargin{1}.inside) + length(varargin{1}.outside); dim = varargin{1}.dim; dat = zeros(Nvoxel, Nsource); for i=1:Nsource tmp = getsubfield(varargin{i}, cfg.parameter); dat(:,i) = tmp(:); end if isfield(varargin{1}, 'inside') fprintf('only selecting voxels inside the brain for statistics (%.1f%%)\n', 100*length(varargin{1}.inside)/prod(varargin{1}.dim)); dat = dat(varargin{1}.inside,:); end % remember the dimension of the source data cfg.dim = dim; % remember which voxels are inside the brain cfg.inside = varargin{1}.inside; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for creating a design matrix % should be called in the code above, or in prepare_design %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [cfg] = get_source_design_pcc_mom(cfg, varargin) % should be implemented function [cfg] = get_source_design_lcmv_mom(cfg, varargin) % should be implemented function [cfg] = get_source_design_trial(cfg, varargin) % should be implemented function [cfg] = get_source_design_avg(cfg, varargin) % should be implemented
github
philippboehmsturm/antx-master
arrow.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/arrow.m
58,199
utf_8
84edd90f9c83830a3a85aec7c3bbbc47
function [h,yy,zz] = arrow(varargin) % ARROW Draw a line with an arrowhead. % % ARROW(Start,Stop) draws a line with an arrow from Start to Stop (points % should be vectors of length 2 or 3, or matrices with 2 or 3 % columns), and returns the graphics handle of the arrow(s). % % ARROW uses the mouse (click-drag) to create an arrow. % % ARROW DEMO & ARROW DEMO2 show 3-D & 2-D demos of the capabilities of ARROW. % % ARROW may be called with a normal argument list or a property-based list. % ARROW(Start,Stop,Length,BaseAngle,TipAngle,Width,Page,CrossDir) is % the full normal argument list, where all but the Start and Stop % points are optional. If you need to specify a later argument (e.g., % Page) but want default values of earlier ones (e.g., TipAngle), % pass an empty matrix for the earlier ones (e.g., TipAngle=[]). % % ARROW('Property1',PropVal1,'Property2',PropVal2,...) creates arrows with the % given properties, using default values for any unspecified or given as % 'default' or NaN. Some properties used for line and patch objects are % used in a modified fashion, others are passed directly to LINE, PATCH, % or SET. For a detailed properties explanation, call ARROW PROPERTIES. % % Start The starting points. B % Stop The end points. /|\ ^ % Length Length of the arrowhead in pixels. /|||\ | % BaseAngle Base angle in degrees (ADE). //|||\\ L| % TipAngle Tip angle in degrees (ABC). ///|||\\\ e| % Width Width of the base in pixels. ////|||\\\\ n| % Page Use hardcopy proportions. /////|D|\\\\\ g| % CrossDir Vector || to arrowhead plane. //// ||| \\\\ t| % NormalDir Vector out of arrowhead plane. /// ||| \\\ h| % Ends Which end has an arrowhead. //<----->|| \\ | % ObjectHandles Vector of handles to update. / base ||| \ V % E angle||<-------->C % ARROW(H,'Prop1',PropVal1,...), where H is a |||tipangle % vector of handles to previously-created arrows ||| % and/or line objects, will update the previously- ||| % created arrows according to the current view -->|A|<-- width % and any specified properties, and will convert % two-point line objects to corresponding arrows. ARROW(H) will update % the arrows if the current view has changed. Root, figure, or axes % handles included in H are replaced by all descendant Arrow objects. % % A property list can follow any specified normal argument list, e.g., % ARROW([1 2 3],[0 0 0],36,'BaseAngle',60) creates an arrow from (1,2,3) to % the origin, with an arrowhead of length 36 pixels and 60-degree base angle. % % The basic arguments or properties can generally be vectorized to create % multiple arrows with the same call. This is done by passing a property % with one row per arrow, or, if all arrows are to have the same property % value, just one row may be specified. % % You may want to execute AXIS(AXIS) before calling ARROW so it doesn't change % the axes on you; ARROW determines the sizes of arrow components BEFORE the % arrow is plotted, so if ARROW changes axis limits, arrows may be malformed. % % This version of ARROW uses features of MATLAB 5 and is incompatible with % earlier MATLAB versions (ARROW for MATLAB 4.2c is available separately); % some problems with perspective plots still exist. % Copyright (c)1995-2002, Dr. Erik A. Johnson <[email protected]>, 11/15/02 % Revision history: % 11/15/02 EAJ Accomodate how MATLAB 6.5 handles NaN and logicals % 7/28/02 EAJ Tried (but failed) work-around for MATLAB 6.x / OpenGL bug % if zero 'Width' or not double-ended % 11/10/99 EAJ Add logical() to eliminate zero index problem in MATLAB 5.3. % 11/10/99 EAJ Corrected warning if axis limits changed on multiple axes. % 11/10/99 EAJ Update e-mail address. % 2/10/99 EAJ Some documentation updating. % 2/24/98 EAJ Fixed bug if Start~=Stop but both colinear with viewpoint. % 8/14/97 EAJ Added workaround for MATLAB 5.1 scalar logical transpose bug. % 7/21/97 EAJ Fixed a few misc bugs. % 7/14/97 EAJ Make arrow([],'Prop',...) do nothing (no old handles) % 6/23/97 EAJ MATLAB 5 compatible version, release. % 5/27/97 EAJ Added Line Arrows back in. Corrected a few bugs. % 5/26/97 EAJ Changed missing Start/Stop to mouse-selected arrows. % 5/19/97 EAJ MATLAB 5 compatible version, beta. % 4/13/97 EAJ MATLAB 5 compatible version, alpha. % 1/31/97 EAJ Fixed bug with multiple arrows and unspecified Z coords. % 12/05/96 EAJ Fixed one more bug with log plots and NormalDir specified % 10/24/96 EAJ Fixed bug with log plots and NormalDir specified % 11/13/95 EAJ Corrected handling for 'reverse' axis directions % 10/06/95 EAJ Corrected occasional conflict with SUBPLOT % 4/24/95 EAJ A major rewrite. % Fall 94 EAJ Original code. % Things to be done: % - segment parsing, computing, and plotting into separate subfunctions % - change computing from Xform to Camera paradigms % + this will help especially with 3-D perspective plots % + if the WarpToFill section works right, remove warning code % + when perpsective works properly, remove perspective warning code % - add cell property values and struct property name/values (like get/set) % - get rid of NaN as the "default" data label % + perhaps change userdata to a struct and don't include (or leave % empty) the values specified as default; or use a cell containing % an empty matrix for a default value % - add functionality of GET to retrieve current values of ARROW properties % Many thanks to Keith Rogers <[email protected]> for his many excellent % suggestions and beta testing. Check out his shareware package MATDRAW % (at ftp://ftp.mathworks.com/pub/contrib/v5/graphics/matdraw/) -- he has % permission to distribute ARROW with MATDRAW. % Permission is granted to distribute ARROW with the toolboxes for the book % "Solving Solid Mechanics Problems with MATLAB 5", by F. Golnaraghi et al. % (Prentice Hall, 1999). % global variable initialization global ARROW_PERSP_WARN ARROW_STRETCH_WARN ARROW_AXLIMITS if isempty(ARROW_PERSP_WARN ), ARROW_PERSP_WARN =1; end; if isempty(ARROW_STRETCH_WARN), ARROW_STRETCH_WARN=1; end; % Handle callbacks if (nargin>0 & ischar(varargin{1}) & strcmp(lower(varargin{1}),'callback')), arrow_callback(varargin{2:end}); return; end; % Are we doing the demo? c = sprintf('\n'); if (nargin==1 & ischar(varargin{1})), arg1 = lower(varargin{1}); if strncmp(arg1,'prop',4), arrow_props; elseif strncmp(arg1,'demo',4) clf reset demo_info = arrow_demo; if ~strncmp(arg1,'demo2',5), hh=arrow_demo3(demo_info); else, hh=arrow_demo2(demo_info); end; if (nargout>=1), h=hh; end; elseif strncmp(arg1,'fixlimits',3), arrow_fixlimits(ARROW_AXLIMITS); ARROW_AXLIMITS=[]; elseif strncmp(arg1,'help',4), disp(help(mfilename)); else, error([upper(mfilename) ' got an unknown single-argument string ''' deblank(arg1) '''.']); end; return; end; % Check # of arguments if (nargout>3), error([upper(mfilename) ' produces at most 3 output arguments.']); end; % find first property number firstprop = nargin+1; for k=1:length(varargin), if ~isnumeric(varargin{k}), firstprop=k; break; end; end; lastnumeric = firstprop-1; % check property list if (firstprop<=nargin), for k=firstprop:2:nargin, curarg = varargin{k}; if ~ischar(curarg) | sum(size(curarg)>1)>1, error([upper(mfilename) ' requires that a property name be a single string.']); end; end; if (rem(nargin-firstprop,2)~=1), error([upper(mfilename) ' requires that the property ''' ... varargin{nargin} ''' be paired with a property value.']); end; end; % default output if (nargout>0), h=[]; end; if (nargout>1), yy=[]; end; if (nargout>2), zz=[]; end; % set values to empty matrices start = []; stop = []; len = []; baseangle = []; tipangle = []; wid = []; page = []; crossdir = []; ends = []; ax = []; oldh = []; ispatch = []; defstart = [NaN NaN NaN]; defstop = [NaN NaN NaN]; deflen = 16; defbaseangle = 90; deftipangle = 16; defwid = 0; defpage = 0; defcrossdir = [NaN NaN NaN]; defends = 1; defoldh = []; defispatch = 1; % The 'Tag' we'll put on our arrows ArrowTag = 'Arrow'; % check for oldstyle arguments if (firstprop==2), % assume arg1 is a set of handles oldh = varargin{1}(:); if isempty(oldh), return; end; elseif (firstprop>9), error([upper(mfilename) ' takes at most 8 non-property arguments.']); elseif (firstprop>2), s = str2mat('start','stop','len','baseangle','tipangle','wid','page','crossdir'); for k=1:firstprop-1, eval([deblank(s(k,:)) '=varargin{k};']); end; end; % parse property pairs extraprops={}; for k=firstprop:2:nargin, prop = varargin{k}; val = varargin{k+1}; prop = [lower(prop(:)') ' ']; if strncmp(prop,'start' ,5), start = val; elseif strncmp(prop,'stop' ,4), stop = val; elseif strncmp(prop,'len' ,3), len = val(:); elseif strncmp(prop,'base' ,4), baseangle = val(:); elseif strncmp(prop,'tip' ,3), tipangle = val(:); elseif strncmp(prop,'wid' ,3), wid = val(:); elseif strncmp(prop,'page' ,4), page = val; elseif strncmp(prop,'cross' ,5), crossdir = val; elseif strncmp(prop,'norm' ,4), if (ischar(val)), crossdir=val; else, crossdir=val*sqrt(-1); end; elseif strncmp(prop,'end' ,3), ends = val; elseif strncmp(prop,'object',6), oldh = val(:); elseif strncmp(prop,'handle',6), oldh = val(:); elseif strncmp(prop,'type' ,4), ispatch = val; elseif strncmp(prop,'userd' ,5), %ignore it else, % make sure it is a valid patch or line property eval('get(0,[''DefaultPatch'' varargin{k}]);err=0;','err=1;'); errstr=lasterr; if (err), eval('get(0,[''DefaultLine'' varargin{k}]);err=0;','err=1;'); end; if (err), errstr(1:max(find(errstr==setstr(13)|errstr==setstr(10)))) = ''; error([upper(mfilename) ' got ' errstr]); end; extraprops={extraprops{:},varargin{k},val}; end; end; % Check if we got 'default' values start = arrow_defcheck(start ,defstart ,'Start' ); stop = arrow_defcheck(stop ,defstop ,'Stop' ); len = arrow_defcheck(len ,deflen ,'Length' ); baseangle = arrow_defcheck(baseangle,defbaseangle,'BaseAngle' ); tipangle = arrow_defcheck(tipangle ,deftipangle ,'TipAngle' ); wid = arrow_defcheck(wid ,defwid ,'Width' ); crossdir = arrow_defcheck(crossdir ,defcrossdir ,'CrossDir' ); page = arrow_defcheck(page ,defpage ,'Page' ); ends = arrow_defcheck(ends ,defends ,'' ); oldh = arrow_defcheck(oldh ,[] ,'ObjectHandles'); ispatch = arrow_defcheck(ispatch ,defispatch ,'' ); % check transpose on arguments [m,n]=size(start ); if any(m==[2 3])&(n==1|n>3), start = start'; end; [m,n]=size(stop ); if any(m==[2 3])&(n==1|n>3), stop = stop'; end; [m,n]=size(crossdir); if any(m==[2 3])&(n==1|n>3), crossdir = crossdir'; end; % convert strings to numbers if ~isempty(ends) & ischar(ends), endsorig = ends; [m,n] = size(ends); col = lower([ends(:,1:min(3,n)) ones(m,max(0,3-n))*' ']); ends = NaN*ones(m,1); oo = ones(1,m); ii=find(all(col'==['non']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*0; end; ii=find(all(col'==['sto']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*1; end; ii=find(all(col'==['sta']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*2; end; ii=find(all(col'==['bot']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*3; end; if any(isnan(ends)), ii = min(find(isnan(ends))); error([upper(mfilename) ' does not recognize ''' deblank(endsorig(ii,:)) ''' as a valid ''Ends'' value.']); end; else, ends = ends(:); end; if ~isempty(ispatch) & ischar(ispatch), col = lower(ispatch(:,1)); patchchar='p'; linechar='l'; defchar=' '; mask = col~=patchchar & col~=linechar & col~=defchar; if any(mask), error([upper(mfilename) ' does not recognize ''' deblank(ispatch(min(find(mask)),:)) ''' as a valid ''Type'' value.']); end; ispatch = (col==patchchar)*1 + (col==linechar)*0 + (col==defchar)*defispatch; else, ispatch = ispatch(:); end; oldh = oldh(:); % check object handles if ~all(ishandle(oldh)), error([upper(mfilename) ' got invalid object handles.']); end; % expand root, figure, and axes handles if ~isempty(oldh), ohtype = get(oldh,'Type'); mask = strcmp(ohtype,'root') | strcmp(ohtype,'figure') | strcmp(ohtype,'axes'); if any(mask), oldh = num2cell(oldh); for ii=find(mask)', oldh(ii) = {findobj(oldh{ii},'Tag',ArrowTag)}; end; oldh = cat(1,oldh{:}); if isempty(oldh), return; end; % no arrows to modify, so just leave end; end; % largest argument length [mstart,junk]=size(start); [mstop,junk]=size(stop); [mcrossdir,junk]=size(crossdir); argsizes = [length(oldh) mstart mstop ... length(len) length(baseangle) length(tipangle) ... length(wid) length(page) mcrossdir length(ends) ]; args=['length(ObjectHandle) '; ... '#rows(Start) '; ... '#rows(Stop) '; ... 'length(Length) '; ... 'length(BaseAngle) '; ... 'length(TipAngle) '; ... 'length(Width) '; ... 'length(Page) '; ... '#rows(CrossDir) '; ... '#rows(Ends) ']; if (any(imag(crossdir(:))~=0)), args(9,:) = '#rows(NormalDir) '; end; if isempty(oldh), narrows = max(argsizes); else, narrows = length(oldh); end; if (narrows<=0), narrows=1; end; % Check size of arguments ii = find((argsizes~=0)&(argsizes~=1)&(argsizes~=narrows)); if ~isempty(ii), s = args(ii',:); while ((size(s,2)>1)&((abs(s(:,size(s,2)))==0)|(abs(s(:,size(s,2)))==abs(' ')))), s = s(:,1:size(s,2)-1); end; s = [ones(length(ii),1)*[upper(mfilename) ' requires that '] s ... ones(length(ii),1)*[' equal the # of arrows (' num2str(narrows) ').' c]]; s = s'; s = s(:)'; s = s(1:length(s)-1); error(setstr(s)); end; % check element length in Start, Stop, and CrossDir if ~isempty(start), [m,n] = size(start); if (n==2), start = [start NaN*ones(m,1)]; elseif (n~=3), error([upper(mfilename) ' requires 2- or 3-element Start points.']); end; end; if ~isempty(stop), [m,n] = size(stop); if (n==2), stop = [stop NaN*ones(m,1)]; elseif (n~=3), error([upper(mfilename) ' requires 2- or 3-element Stop points.']); end; end; if ~isempty(crossdir), [m,n] = size(crossdir); if (n<3), crossdir = [crossdir NaN*ones(m,3-n)]; elseif (n~=3), if (all(imag(crossdir(:))==0)), error([upper(mfilename) ' requires 2- or 3-element CrossDir vectors.']); else, error([upper(mfilename) ' requires 2- or 3-element NormalDir vectors.']); end; end; end; % fill empty arguments if isempty(start ), start = [Inf Inf Inf]; end; if isempty(stop ), stop = [Inf Inf Inf]; end; if isempty(len ), len = Inf; end; if isempty(baseangle ), baseangle = Inf; end; if isempty(tipangle ), tipangle = Inf; end; if isempty(wid ), wid = Inf; end; if isempty(page ), page = Inf; end; if isempty(crossdir ), crossdir = [Inf Inf Inf]; end; if isempty(ends ), ends = Inf; end; if isempty(ispatch ), ispatch = Inf; end; % expand single-column arguments o = ones(narrows,1); if (size(start ,1)==1), start = o * start ; end; if (size(stop ,1)==1), stop = o * stop ; end; if (length(len )==1), len = o * len ; end; if (length(baseangle )==1), baseangle = o * baseangle ; end; if (length(tipangle )==1), tipangle = o * tipangle ; end; if (length(wid )==1), wid = o * wid ; end; if (length(page )==1), page = o * page ; end; if (size(crossdir ,1)==1), crossdir = o * crossdir ; end; if (length(ends )==1), ends = o * ends ; end; if (length(ispatch )==1), ispatch = o * ispatch ; end; ax = o * gca; % if we've got handles, get the defaults from the handles if ~isempty(oldh), for k=1:narrows, oh = oldh(k); ud = get(oh,'UserData'); ax(k) = get(oh,'Parent'); ohtype = get(oh,'Type'); if strcmp(get(oh,'Tag'),ArrowTag), % if it's an arrow already if isinf(ispatch(k)), ispatch(k)=strcmp(ohtype,'patch'); end; % arrow UserData format: [start' stop' len base tip wid page crossdir' ends] start0 = ud(1:3); stop0 = ud(4:6); if (isinf(len(k))), len(k) = ud( 7); end; if (isinf(baseangle(k))), baseangle(k) = ud( 8); end; if (isinf(tipangle(k))), tipangle(k) = ud( 9); end; if (isinf(wid(k))), wid(k) = ud(10); end; if (isinf(page(k))), page(k) = ud(11); end; if (isinf(crossdir(k,1))), crossdir(k,1) = ud(12); end; if (isinf(crossdir(k,2))), crossdir(k,2) = ud(13); end; if (isinf(crossdir(k,3))), crossdir(k,3) = ud(14); end; if (isinf(ends(k))), ends(k) = ud(15); end; elseif strcmp(ohtype,'line')|strcmp(ohtype,'patch'), % it's a non-arrow line or patch convLineToPatch = 1; %set to make arrow patches when converting from lines. if isinf(ispatch(k)), ispatch(k)=convLineToPatch|strcmp(ohtype,'patch'); end; x=get(oh,'XData'); x=x(~isnan(x(:))); if isempty(x), x=NaN; end; y=get(oh,'YData'); y=y(~isnan(y(:))); if isempty(y), y=NaN; end; z=get(oh,'ZData'); z=z(~isnan(z(:))); if isempty(z), z=NaN; end; start0 = [x(1) y(1) z(1) ]; stop0 = [x(end) y(end) z(end)]; else, error([upper(mfilename) ' cannot convert ' ohtype ' objects.']); end; ii=find(isinf(start(k,:))); if ~isempty(ii), start(k,ii)=start0(ii); end; ii=find(isinf(stop( k,:))); if ~isempty(ii), stop( k,ii)=stop0( ii); end; end; end; % convert Inf's to NaN's start( isinf(start )) = NaN; stop( isinf(stop )) = NaN; len( isinf(len )) = NaN; baseangle( isinf(baseangle)) = NaN; tipangle( isinf(tipangle )) = NaN; wid( isinf(wid )) = NaN; page( isinf(page )) = NaN; crossdir( isinf(crossdir )) = NaN; ends( isinf(ends )) = NaN; ispatch( isinf(ispatch )) = NaN; % set up the UserData data (here so not corrupted by log10's and such) ud = [start stop len baseangle tipangle wid page crossdir ends]; % Set Page defaults page = ~isnan(page) & trueornan(page); % Get axes limits, range, min; correct for aspect ratio and log scale axm = zeros(3,narrows); axr = zeros(3,narrows); axrev = zeros(3,narrows); ap = zeros(2,narrows); xyzlog = zeros(3,narrows); limmin = zeros(2,narrows); limrange = zeros(2,narrows); oldaxlims = zeros(narrows,7); oneax = all(ax==ax(1)); if (oneax), T = zeros(4,4); invT = zeros(4,4); else, T = zeros(16,narrows); invT = zeros(16,narrows); end; axnotdone = logical(ones(size(ax))); while (any(axnotdone)), ii = min(find(axnotdone)); curax = ax(ii); curpage = page(ii); % get axes limits and aspect ratio axl = [get(curax,'XLim'); get(curax,'YLim'); get(curax,'ZLim')]; oldaxlims(min(find(oldaxlims(:,1)==0)),:) = [curax reshape(axl',1,6)]; % get axes size in pixels (points) u = get(curax,'Units'); axposoldunits = get(curax,'Position'); really_curpage = curpage & strcmp(u,'normalized'); if (really_curpage), curfig = get(curax,'Parent'); pu = get(curfig,'PaperUnits'); set(curfig,'PaperUnits','points'); pp = get(curfig,'PaperPosition'); set(curfig,'PaperUnits',pu); set(curax,'Units','pixels'); curapscreen = get(curax,'Position'); set(curax,'Units','normalized'); curap = pp.*get(curax,'Position'); else, set(curax,'Units','pixels'); curapscreen = get(curax,'Position'); curap = curapscreen; end; set(curax,'Units',u); set(curax,'Position',axposoldunits); % handle non-stretched axes position str_stretch = { 'DataAspectRatioMode' ; ... 'PlotBoxAspectRatioMode' ; ... 'CameraViewAngleMode' }; str_camera = { 'CameraPositionMode' ; ... 'CameraTargetMode' ; ... 'CameraViewAngleMode' ; ... 'CameraUpVectorMode' }; notstretched = strcmp(get(curax,str_stretch),'manual'); manualcamera = strcmp(get(curax,str_camera),'manual'); if ~arrow_WarpToFill(notstretched,manualcamera,curax), % give a warning that this has not been thoroughly tested if 0 & ARROW_STRETCH_WARN, ARROW_STRETCH_WARN = 0; strs = {str_stretch{1:2},str_camera{:}}; strs = [char(ones(length(strs),1)*sprintf('\n ')) char(strs)]'; warning([upper(mfilename) ' may not yet work quite right ' ... 'if any of the following are ''manual'':' strs(:).']); end; % find the true pixel size of the actual axes texttmp = text(axl(1,[1 2 2 1 1 2 2 1]), ... axl(2,[1 1 2 2 1 1 2 2]), ... axl(3,[1 1 1 1 2 2 2 2]),''); set(texttmp,'Units','points'); textpos = get(texttmp,'Position'); delete(texttmp); textpos = cat(1,textpos{:}); textpos = max(textpos(:,1:2)) - min(textpos(:,1:2)); % adjust the axes position if (really_curpage), % adjust to printed size textpos = textpos * min(curap(3:4)./textpos); curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos]; else, % adjust for pixel roundoff textpos = textpos * min(curapscreen(3:4)./textpos); curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos]; end; end; if ARROW_PERSP_WARN & ~strcmp(get(curax,'Projection'),'orthographic'), ARROW_PERSP_WARN = 0; warning([upper(mfilename) ' does not yet work right for 3-D perspective projection.']); end; % adjust limits for log scale on axes curxyzlog = [strcmp(get(curax,'XScale'),'log'); ... strcmp(get(curax,'YScale'),'log'); ... strcmp(get(curax,'ZScale'),'log')]; if (any(curxyzlog)), ii = find([curxyzlog;curxyzlog]); if (any(axl(ii)<=0)), error([upper(mfilename) ' does not support non-positive limits on log-scaled axes.']); else, axl(ii) = log10(axl(ii)); end; end; % correct for 'reverse' direction on axes; curreverse = [strcmp(get(curax,'XDir'),'reverse'); ... strcmp(get(curax,'YDir'),'reverse'); ... strcmp(get(curax,'ZDir'),'reverse')]; ii = find(curreverse); if ~isempty(ii), axl(ii,[1 2])=-axl(ii,[2 1]); end; % compute the range of 2-D values curT = get(curax,'Xform'); lim = curT*[0 1 0 1 0 1 0 1;0 0 1 1 0 0 1 1;0 0 0 0 1 1 1 1;1 1 1 1 1 1 1 1]; lim = lim(1:2,:)./([1;1]*lim(4,:)); curlimmin = min(lim')'; curlimrange = max(lim')' - curlimmin; curinvT = inv(curT); if (~oneax), curT = curT.'; curinvT = curinvT.'; curT = curT(:); curinvT = curinvT(:); end; % check which arrows to which cur corresponds ii = find((ax==curax)&(page==curpage)); oo = ones(1,length(ii)); axr(:,ii) = diff(axl')' * oo; axm(:,ii) = axl(:,1) * oo; axrev(:,ii) = curreverse * oo; ap(:,ii) = curap(3:4)' * oo; xyzlog(:,ii) = curxyzlog * oo; limmin(:,ii) = curlimmin * oo; limrange(:,ii) = curlimrange * oo; if (oneax), T = curT; invT = curinvT; else, T(:,ii) = curT * oo; invT(:,ii) = curinvT * oo; end; axnotdone(ii) = zeros(1,length(ii)); end; oldaxlims(oldaxlims(:,1)==0,:)=[]; % correct for log scales curxyzlog = xyzlog.'; ii = find(curxyzlog(:)); if ~isempty(ii), start( ii) = real(log10(start( ii))); stop( ii) = real(log10(stop( ii))); if (all(imag(crossdir)==0)), % pulled (ii) subscript on crossdir, 12/5/96 eaj crossdir(ii) = real(log10(crossdir(ii))); end; end; % correct for reverse directions ii = find(axrev.'); if ~isempty(ii), start( ii) = -start( ii); stop( ii) = -stop( ii); crossdir(ii) = -crossdir(ii); end; % transpose start/stop values start = start.'; stop = stop.'; % take care of defaults, page was done above ii=find(isnan(start(:) )); if ~isempty(ii), start(ii) = axm(ii)+axr(ii)/2; end; ii=find(isnan(stop(:) )); if ~isempty(ii), stop(ii) = axm(ii)+axr(ii)/2; end; ii=find(isnan(crossdir(:) )); if ~isempty(ii), crossdir(ii) = zeros(length(ii),1); end; ii=find(isnan(len )); if ~isempty(ii), len(ii) = ones(length(ii),1)*deflen; end; ii=find(isnan(baseangle )); if ~isempty(ii), baseangle(ii) = ones(length(ii),1)*defbaseangle; end; ii=find(isnan(tipangle )); if ~isempty(ii), tipangle(ii) = ones(length(ii),1)*deftipangle; end; ii=find(isnan(wid )); if ~isempty(ii), wid(ii) = ones(length(ii),1)*defwid; end; ii=find(isnan(ends )); if ~isempty(ii), ends(ii) = ones(length(ii),1)*defends; end; % transpose rest of values len = len.'; baseangle = baseangle.'; tipangle = tipangle.'; wid = wid.'; page = page.'; crossdir = crossdir.'; ends = ends.'; ax = ax.'; % given x, a 3xN matrix of points in 3-space; % want to convert to X, the corresponding 4xN 2-space matrix % % tmp1=[(x-axm)./axr; ones(1,size(x,1))]; % if (oneax), X=T*tmp1; % else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; % tmp2=zeros(4,4*N); tmp2(:)=tmp1(:); % X=zeros(4,N); X(:)=sum(tmp2)'; end; % X = X ./ (ones(4,1)*X(4,:)); % for all points with start==stop, start=stop-(verysmallvalue)*(up-direction); ii = find(all(start==stop)); if ~isempty(ii), % find an arrowdir vertical on screen and perpendicular to viewer % transform to 2-D tmp1 = [(stop(:,ii)-axm(:,ii))./axr(:,ii);ones(1,length(ii))]; if (oneax), twoD=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,ii).*tmp1; tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:); twoD=zeros(4,length(ii)); twoD(:)=sum(tmp2)'; end; twoD=twoD./(ones(4,1)*twoD(4,:)); % move the start point down just slightly tmp1 = twoD + [0;-1/1000;0;0]*(limrange(2,ii)./ap(2,ii)); % transform back to 3-D if (oneax), threeD=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT(:,ii).*tmp1; tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:); threeD=zeros(4,length(ii)); threeD(:)=sum(tmp2)'; end; start(:,ii) = (threeD(1:3,:)./(ones(3,1)*threeD(4,:))).*axr(:,ii)+axm(:,ii); end; % compute along-arrow points % transform Start points tmp1=[(start-axm)./axr;ones(1,narrows)]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); X0=zeros(4,narrows); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % transform Stop points tmp1=[(stop-axm)./axr;ones(1,narrows)]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); Xf=zeros(4,narrows); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute pixel distance between points D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*(ap./limrange)).^2)); D = D + (D==0); %eaj new 2/24/98 % compute and modify along-arrow distances len1 = len; len2 = len - (len.*tan(tipangle/180*pi)-wid/2).*tan((90-baseangle)/180*pi); slen0 = zeros(1,narrows); slen1 = len1 .* ((ends==2)|(ends==3)); slen2 = len2 .* ((ends==2)|(ends==3)); len0 = zeros(1,narrows); len1 = len1 .* ((ends==1)|(ends==3)); len2 = len2 .* ((ends==1)|(ends==3)); % for no start arrowhead ii=find((ends==1)&(D<len2)); if ~isempty(ii), slen0(ii) = D(ii)-len2(ii); end; % for no end arrowhead ii=find((ends==2)&(D<slen2)); if ~isempty(ii), len0(ii) = D(ii)-slen2(ii); end; len1 = len1 + len0; len2 = len2 + len0; slen1 = slen1 + slen0; slen2 = slen2 + slen0; % note: the division by D below will probably not be accurate if both % of the following are true: % 1. the ratio of the line length to the arrowhead % length is large % 2. the view is highly perspective. % compute stoppoints tmp1=X0.*(ones(4,1)*(len0./D))+Xf.*(ones(4,1)*(1-len0./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; stoppoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute tippoints tmp1=X0.*(ones(4,1)*(len1./D))+Xf.*(ones(4,1)*(1-len1./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; tippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute basepoints tmp1=X0.*(ones(4,1)*(len2./D))+Xf.*(ones(4,1)*(1-len2./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; basepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute startpoints tmp1=X0.*(ones(4,1)*(1-slen0./D))+Xf.*(ones(4,1)*(slen0./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; startpoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute stippoints tmp1=X0.*(ones(4,1)*(1-slen1./D))+Xf.*(ones(4,1)*(slen1./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; stippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute sbasepoints tmp1=X0.*(ones(4,1)*(1-slen2./D))+Xf.*(ones(4,1)*(slen2./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; sbasepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute cross-arrow directions for arrows with NormalDir specified if (any(imag(crossdir(:))~=0)), ii = find(any(imag(crossdir)~=0)); crossdir(:,ii) = cross((stop(:,ii)-start(:,ii))./axr(:,ii), ... imag(crossdir(:,ii))).*axr(:,ii); end; % compute cross-arrow directions basecross = crossdir + basepoint; tipcross = crossdir + tippoint; sbasecross = crossdir + sbasepoint; stipcross = crossdir + stippoint; ii = find(all(crossdir==0)|any(isnan(crossdir))); if ~isempty(ii), numii = length(ii); % transform start points tmp1 = [basepoint(:,ii) tippoint(:,ii) sbasepoint(:,ii) stippoint(:,ii)]; tmp1 = (tmp1-axm(:,[ii ii ii ii])) ./ axr(:,[ii ii ii ii]); tmp1 = [tmp1; ones(1,4*numii)]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); X0=zeros(4,4*numii); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % transform stop points tmp1 = [(2*stop(:,ii)-start(:,ii)-axm(:,ii))./axr(:,ii);ones(1,numii)]; tmp1 = [tmp1 tmp1 tmp1 tmp1]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); Xf=zeros(4,4*numii); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute perpendicular directions pixfact = ((limrange(1,ii)./limrange(2,ii)).*(ap(2,ii)./ap(1,ii))).^2; pixfact = [pixfact pixfact pixfact pixfact]; pixfact = [pixfact;1./pixfact]; [dummyval,jj] = max(abs(Xf(1:2,:)-X0(1:2,:))); jj1 = ((1:4)'*ones(1,length(jj))==ones(4,1)*jj); jj2 = ((1:4)'*ones(1,length(jj))==ones(4,1)*(3-jj)); jj3 = jj1(1:2,:); Xf(jj1)=Xf(jj1)+(Xf(jj1)-X0(jj1)==0); %eaj new 2/24/98 Xp = X0; Xp(jj2) = X0(jj2) + ones(sum(jj2(:)),1); Xp(jj1) = X0(jj1) - (Xf(jj2)-X0(jj2))./(Xf(jj1)-X0(jj1)) .* pixfact(jj3); % inverse transform the cross points if (oneax), Xp=invT*Xp; else, tmp1=[Xp;Xp;Xp;Xp]; tmp1=invT(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); Xp=zeros(4,4*numii); Xp(:)=sum(tmp2)'; end; Xp=(Xp(1:3,:)./(ones(3,1)*Xp(4,:))).*axr(:,[ii ii ii ii])+axm(:,[ii ii ii ii]); basecross(:,ii) = Xp(:,0*numii+(1:numii)); tipcross(:,ii) = Xp(:,1*numii+(1:numii)); sbasecross(:,ii) = Xp(:,2*numii+(1:numii)); stipcross(:,ii) = Xp(:,3*numii+(1:numii)); end; % compute all points % compute start points axm11 = [axm axm axm axm axm axm axm axm axm axm axm]; axr11 = [axr axr axr axr axr axr axr axr axr axr axr]; st = [stoppoint tippoint basepoint sbasepoint stippoint startpoint stippoint sbasepoint basepoint tippoint stoppoint]; tmp1 = (st - axm11) ./ axr11; tmp1 = [tmp1; ones(1,size(tmp1,2))]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); X0=zeros(4,11*narrows); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % compute stop points tmp1 = ([start tipcross basecross sbasecross stipcross stop stipcross sbasecross basecross tipcross start] ... - axm11) ./ axr11; tmp1 = [tmp1; ones(1,size(tmp1,2))]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); Xf=zeros(4,11*narrows); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute lengths len0 = len.*((ends==1)|(ends==3)).*tan(tipangle/180*pi); slen0 = len.*((ends==2)|(ends==3)).*tan(tipangle/180*pi); le = [zeros(1,narrows) len0 wid/2 wid/2 slen0 zeros(1,narrows) -slen0 -wid/2 -wid/2 -len0 zeros(1,narrows)]; aprange = ap./limrange; aprange = [aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange]; D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*aprange).^2)); Dii=find(D==0); if ~isempty(Dii), D=D+(D==0); le(Dii)=zeros(1,length(Dii)); end; %should fix DivideByZero warnings tmp1 = X0.*(ones(4,1)*(1-le./D)) + Xf.*(ones(4,1)*(le./D)); % inverse transform if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[invT invT invT invT invT invT invT invT invT invT invT].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,11*narrows); tmp3(:)=sum(tmp2)'; end; pts = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)) .* axr11 + axm11; % correct for ones where the crossdir was specified ii = find(~(all(crossdir==0)|any(isnan(crossdir)))); if ~isempty(ii), D1 = [pts(:,1*narrows+ii)-pts(:,9*narrows+ii) ... pts(:,2*narrows+ii)-pts(:,8*narrows+ii) ... pts(:,3*narrows+ii)-pts(:,7*narrows+ii) ... pts(:,4*narrows+ii)-pts(:,6*narrows+ii) ... pts(:,6*narrows+ii)-pts(:,4*narrows+ii) ... pts(:,7*narrows+ii)-pts(:,3*narrows+ii) ... pts(:,8*narrows+ii)-pts(:,2*narrows+ii) ... pts(:,9*narrows+ii)-pts(:,1*narrows+ii)]/2; ii = ii'*ones(1,8) + ones(length(ii),1)*[1:4 6:9]*narrows; ii = ii(:)'; pts(:,ii) = st(:,ii) + D1; end; % readjust for reverse directions iicols=(1:narrows)'; iicols=iicols(:,ones(1,11)); iicols=iicols(:).'; tmp1=axrev(:,iicols); ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=-pts(ii); end; % readjust for log scale on axes tmp1=xyzlog(:,iicols); ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=10.^pts(ii); end; % compute the x,y,z coordinates of the patches; ii = narrows*(0:10)'*ones(1,narrows) + ones(11,1)*(1:narrows); ii = ii(:)'; x = zeros(11,narrows); y = zeros(11,narrows); z = zeros(11,narrows); x(:) = pts(1,ii)'; y(:) = pts(2,ii)'; z(:) = pts(3,ii)'; % do the output if (nargout<=1), % % create or modify the patches newpatch = trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'patch')); newline = ~trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'line')); if isempty(oldh), H=zeros(narrows,1); else, H=oldh; end; % % make or modify the arrows for k=1:narrows, if all(isnan(ud(k,[3 6])))&arrow_is2DXY(ax(k)), zz=[]; else, zz=z(:,k); end; % work around a MATLAB 6.x OpenGL bug -- 7/28/02 xx=x(:,k); yy=y(:,k); mask=any([ones(1,2+size(zz,2));diff([xx yy zz],[],1)],2); xx=xx(mask); yy=yy(mask); if ~isempty(zz), zz=zz(mask); end; % plot the patch or line xyz = {'XData',xx,'YData',yy,'ZData',zz,'Tag',ArrowTag}; if newpatch(k)|newline(k), if newpatch(k), H(k) = patch(xyz{:}); else, H(k) = line(xyz{:}); end; if ~isempty(oldh), arrow_copyprops(oldh(k),H(k)); end; else, if ispatch(k), xyz={xyz{:},'CData',[]}; end; set(H(k),xyz{:}); end; end; if ~isempty(oldh), delete(oldh(oldh~=H)); end; % % additional properties set(H,'Clipping','off'); set(H,{'UserData'},num2cell(ud,2)); if (length(extraprops)>0), set(H,extraprops{:}); end; % handle choosing arrow Start and/or Stop locations if unspecified [H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims); if ~isempty(errstr), error([upper(mfilename) ' got ' errstr]); end; % set the output if (nargout>0), h=H; end; % make sure the axis limits did not change if isempty(oldaxlims), ARROW_AXLIMITS = []; else, lims = get(oldaxlims(:,1),{'XLim','YLim','ZLim'})'; lims = reshape(cat(2,lims{:}),6,size(lims,2)); mask = arrow_is2DXY(oldaxlims(:,1)); oldaxlims(mask,6:7) = lims(5:6,mask)'; ARROW_AXLIMITS = oldaxlims(find(any(oldaxlims(:,2:7)'~=lims)),:); if ~isempty(ARROW_AXLIMITS), warning(arrow_warnlimits(ARROW_AXLIMITS,narrows)); end; end; else, % don't create the patch, just return the data h=x; yy=y; zz=z; end; function out = arrow_defcheck(in,def,prop) % check if we got 'default' values out = in; if ~ischar(in), return; end; if size(in,1)==1 & strncmp(lower(in),'def',3), out = def; elseif ~isempty(prop), error([upper(mfilename) ' does not recognize ''' in(:)' ''' as a valid ''' prop ''' string.']); end; function [H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims) % handle choosing arrow Start and/or Stop locations if necessary errstr = ''; if isempty(H)|isempty(ud)|isempty(x), return; end; % determine which (if any) need Start and/or Stop needStart = all(isnan(ud(:,1:3)'))'; needStop = all(isnan(ud(:,4:6)'))'; mask = any(needStart|needStop); if ~any(mask), return; end; ud(~mask,:)=[]; ax(:,~mask)=[]; x(:,~mask)=[]; y(:,~mask)=[]; z(:,~mask)=[]; % make them invisible for the time being set(H,'Visible','off'); % save the current axes and limits modes; set to manual for the time being oldAx = gca; limModes=get(ax(:),{'XLimMode','YLimMode','ZLimMode'}); set(ax(:),{'XLimMode','YLimMode','ZLimMode'},{'manual','manual','manual'}); % loop over each arrow that requires attention jj = find(mask); for ii=1:length(jj), h = H(jj(ii)); axes(ax(ii)); % figure out correct call if needStart(ii), prop='Start'; else, prop='Stop'; end; [wasInterrupted,errstr] = arrow_click(needStart(ii)&needStop(ii),h,prop,ax(ii)); % handle errors and control-C if wasInterrupted, delete(H(jj(ii:end))); H(jj(ii:end))=[]; oldaxlims(jj(ii:end),:)=[]; break; end; end; % restore the axes and limit modes axes(oldAx); set(ax(:),{'XLimMode','YLimMode','ZLimMode'},limModes); function [wasInterrupted,errstr] = arrow_click(lockStart,H,prop,ax) % handle the clicks for one arrow fig = get(ax,'Parent'); % save some things oldFigProps = {'Pointer','WindowButtonMotionFcn','WindowButtonUpFcn'}; oldFigValue = get(fig,oldFigProps); oldArrowProps = {'EraseMode'}; oldArrowValue = get(H,oldArrowProps); set(H,'EraseMode','background'); %because 'xor' makes shaft invisible unless Width>1 global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z ARROW_CLICK_H=H; ARROW_CLICK_PROP=prop; ARROW_CLICK_AX=ax; ARROW_CLICK_USE_Z=~arrow_is2DXY(ax)|~arrow_planarkids(ax); set(fig,'Pointer','crosshair'); % set up the WindowButtonMotion so we can see the arrow while moving around set(fig,'WindowButtonUpFcn','set(gcf,''WindowButtonUpFcn'','''')', ... 'WindowButtonMotionFcn',''); if ~lockStart, set(H,'Visible','on'); set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']); end; % wait for the button to be pressed [wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig); % if we wanted to click-drag, set the Start point if lockStart & ~wasInterrupted, pt = arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z); feval(mfilename,H,'Start',pt,'Stop',pt); set(H,'Visible','on'); ARROW_CLICK_PROP='Stop'; set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']); % wait for the mouse button to be released eval('waitfor(fig,''WindowButtonUpFcn'','''');','wasInterrupted=1;'); if wasInterrupted, errstr=lasterr; end; end; if ~wasInterrupted, feval(mfilename,'callback','motion'); end; % restore some things set(gcf,oldFigProps,oldFigValue); set(H,oldArrowProps,oldArrowValue); function arrow_callback(varargin) % handle redrawing callbacks if nargin==0, return; end; str = varargin{1}; if ~ischar(str), error([upper(mfilename) ' got an invalid Callback command.']); end; s = lower(str); if strcmp(s,'motion'), % motion callback global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z feval(mfilename,ARROW_CLICK_H,ARROW_CLICK_PROP,arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z)); drawnow; else, error([upper(mfilename) ' does not recognize ''' str(:).' ''' as a valid Callback option.']); end; function out = arrow_point(ax,use_z) % return the point on the given axes if nargin==0, ax=gca; end; if nargin<2, use_z=~arrow_is2DXY(ax)|~arrow_planarkids(ax); end; out = get(ax,'CurrentPoint'); out = out(1,:); if ~use_z, out=out(1:2); end; function [wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig) % wait for button down ignoring object ButtonDownFcn's if nargin==0, fig=gcf; end; errstr = ''; % save ButtonDownFcn values objs = findobj(fig); buttonDownFcns = get(objs,'ButtonDownFcn'); mask=~strcmp(buttonDownFcns,''); objs=objs(mask); buttonDownFcns=buttonDownFcns(mask); set(objs,'ButtonDownFcn',''); % save other figure values figProps = {'KeyPressFcn','WindowButtonDownFcn'}; figValue = get(fig,figProps); % do the real work set(fig,'KeyPressFcn','set(gcf,''KeyPressFcn'','''',''WindowButtonDownFcn'','''');', ... 'WindowButtonDownFcn','set(gcf,''WindowButtonDownFcn'','''')'); lasterr(''); wasInterrupted=0; eval('waitfor(fig,''WindowButtonDownFcn'','''');','wasInterrupted=1;'); wasKeyPress = ~wasInterrupted & strcmp(get(fig,'KeyPressFcn'),''); if wasInterrupted, errstr=lasterr; end; % restore ButtonDownFcn and other figure values set(objs,'ButtonDownFcn',buttonDownFcns); set(fig,figProps,figValue); function [out,is2D] = arrow_is2DXY(ax) % check if axes are 2-D X-Y plots % may not work for modified camera angles, etc. out = logical(zeros(size(ax))); % 2-D X-Y plots is2D = out; % any 2-D plots views = get(ax(:),{'View'}); views = cat(1,views{:}); out(:) = abs(views(:,2))==90; is2D(:) = out(:) | all(rem(views',90)==0)'; function out = arrow_planarkids(ax) % check if axes descendents all have empty ZData (lines,patches,surfaces) out = logical(ones(size(ax))); allkids = get(ax(:),{'Children'}); for k=1:length(allkids), kids = get([findobj(allkids{k},'flat','Type','line') findobj(allkids{k},'flat','Type','patch') findobj(allkids{k},'flat','Type','surface')],{'ZData'}); for j=1:length(kids), if ~isempty(kids{j}), out(k)=logical(0); break; end; end; end; function arrow_fixlimits(axlimits) % reset the axis limits as necessary if isempty(axlimits), disp([upper(mfilename) ' does not remember any axis limits to reset.']); end; for k=1:size(axlimits,1), if any(get(axlimits(k,1),'XLim')~=axlimits(k,2:3)), set(axlimits(k,1),'XLim',axlimits(k,2:3)); end; if any(get(axlimits(k,1),'YLim')~=axlimits(k,4:5)), set(axlimits(k,1),'YLim',axlimits(k,4:5)); end; if any(get(axlimits(k,1),'ZLim')~=axlimits(k,6:7)), set(axlimits(k,1),'ZLim',axlimits(k,6:7)); end; end; function out = arrow_WarpToFill(notstretched,manualcamera,curax) % check if we are in "WarpToFill" mode. out = strcmp(get(curax,'WarpToFill'),'on'); % 'WarpToFill' is undocumented, so may need to replace this by % out = ~( any(notstretched) & any(manualcamera) ); function out = arrow_warnlimits(axlimits,narrows) % create a warning message if we've changed the axis limits msg = ''; switch (size(axlimits,1)) case 1, msg=''; case 2, msg='on two axes '; otherwise, msg='on several axes '; end; msg = [upper(mfilename) ' changed the axis limits ' msg ... 'when adding the arrow']; if (narrows>1), msg=[msg 's']; end; out = [msg '.' sprintf('\n') ' Call ' upper(mfilename) ... ' FIXLIMITS to reset them now.']; function arrow_copyprops(fm,to) % copy line properties to patches props = {'EraseMode','LineStyle','LineWidth','Marker','MarkerSize',... 'MarkerEdgeColor','MarkerFaceColor','ButtonDownFcn', ... 'Clipping','DeleteFcn','BusyAction','HandleVisibility', ... 'Selected','SelectionHighlight','Visible'}; lineprops = {'Color', props{:}}; patchprops = {'EdgeColor',props{:}}; patch2props = {'FaceColor',patchprops{:}}; fmpatch = strcmp(get(fm,'Type'),'patch'); topatch = strcmp(get(to,'Type'),'patch'); set(to( fmpatch& topatch),patch2props,get(fm( fmpatch& topatch),patch2props)); %p->p set(to(~fmpatch&~topatch),lineprops, get(fm(~fmpatch&~topatch),lineprops )); %l->l set(to( fmpatch&~topatch),lineprops, get(fm( fmpatch&~topatch),patchprops )); %p->l set(to(~fmpatch& topatch),patchprops, get(fm(~fmpatch& topatch),lineprops) ,'FaceColor','none'); %l->p function arrow_props % display further help info about ARROW properties c = sprintf('\n'); disp([c ... 'ARROW Properties: Default values are given in [square brackets], and other' c ... ' acceptable equivalent property names are in (parenthesis).' c c ... ' Start The starting points. For N arrows, B' c ... ' this should be a Nx2 or Nx3 matrix. /|\ ^' c ... ' Stop The end points. For N arrows, this /|||\ |' c ... ' should be a Nx2 or Nx3 matrix. //|||\\ L|' c ... ' Length Length of the arrowhead (in pixels on ///|||\\\ e|' c ... ' screen, points on a page). [16] (Len) ////|||\\\\ n|' c ... ' BaseAngle Angle (degrees) of the base angle /////|D|\\\\\ g|' c ... ' ADE. For a simple stick arrow, use //// ||| \\\\ t|' c ... ' BaseAngle=TipAngle. [90] (Base) /// ||| \\\ h|' c ... ' TipAngle Angle (degrees) of tip angle ABC. //<----->|| \\ |' c ... ' [16] (Tip) / base ||| \ V' c ... ' Width Width of the base in pixels. Not E angle ||<-------->C' c ... ' the ''LineWidth'' prop. [0] (Wid) |||tipangle' c ... ' Page If provided, non-empty, and not NaN, |||' c ... ' this causes ARROW to use hardcopy |||' c ... ' rather than onscreen proportions. A' c ... ' This is important if screen aspect --> <-- width' c ... ' ratio and hardcopy aspect ratio are ----CrossDir---->' c ... ' vastly different. []' c... ' CrossDir A vector giving the direction towards which the fletches' c ... ' on the arrow should go. [computed such that it is perpen-' c ... ' dicular to both the arrow direction and the view direction' c ... ' (i.e., as if it was pasted on a normal 2-D graph)] (Note' c ... ' that CrossDir is a vector. Also note that if an axis is' c ... ' plotted on a log scale, then the corresponding component' c ... ' of CrossDir must also be set appropriately, i.e., to 1 for' c ... ' no change in that direction, >1 for a positive change, >0' c ... ' and <1 for negative change.)' c ... ' NormalDir A vector normal to the fletch direction (CrossDir is then' c ... ' computed by the vector cross product [Line]x[NormalDir]). []' c ... ' (Note that NormalDir is a vector. Unlike CrossDir,' c ... ' NormalDir is used as is regardless of log-scaled axes.)' c ... ' Ends Set which end has an arrowhead. Valid values are ''none'',' c ... ' ''stop'', ''start'', and ''both''. [''stop''] (End)' c... ' ObjectHandles Vector of handles to previously-created arrows to be' c ... ' updated or line objects to be converted to arrows.' c ... ' [] (Object,Handle)' c ]); function out = arrow_demo % demo % create the data [x,y,z] = peaks; [ddd,out.iii]=max(z(:)); out.axlim = [min(x(:)) max(x(:)) min(y(:)) max(y(:)) min(z(:)) max(z(:))]; % modify it by inserting some NaN's [m,n] = size(z); m = floor(m/2); n = floor(n/2); z(1:m,1:n) = NaN*ones(m,n); % graph it clf('reset'); out.hs=surf(x,y,z); out.x=x; out.y=y; out.z=z; xlabel('x'); ylabel('y'); function h = arrow_demo3(in) % set the view axlim = in.axlim; axis(axlim); zlabel('z'); %set(in.hs,'FaceColor','interp'); view(viewmtx(-37.5,30,20)); title(['Demo of the capabilities of the ARROW function in 3-D']); % Normal blue arrow h1 = feval(mfilename,[axlim(1) axlim(4) 4],[-.8 1.2 4], ... 'EdgeColor','b','FaceColor','b'); % Normal white arrow, clipped by the surface h2 = feval(mfilename,axlim([1 4 6]),[0 2 4]); t=text(-2.4,2.7,7.7,'arrow clipped by surf'); % Baseangle<90 h3 = feval(mfilename,[3 .125 3.5],[1.375 0.125 3.5],30,50); t2=text(3.1,.125,3.5,'local maximum'); % Baseangle<90, fill and edge colors different h4 = feval(mfilename,axlim(1:2:5)*.5,[0 0 0],36,60,25, ... 'EdgeColor','b','FaceColor','c'); t3=text(axlim(1)*.5,axlim(3)*.5,axlim(5)*.5-.75,'origin'); set(t3,'HorizontalAlignment','center'); % Baseangle>90, black fill h5 = feval(mfilename,[-2.9 2.9 3],[-1.3 .4 3.2],30,120,[],6, ... 'EdgeColor','r','FaceColor','k','LineWidth',2); % Baseangle>90, no fill h6 = feval(mfilename,[-2.9 2.9 1.3],[-1.3 .4 1.5],30,120,[],6, ... 'EdgeColor','r','FaceColor','none','LineWidth',2); % Stick arrow h7 = feval(mfilename,[-1.6 -1.65 -6.5],[0 -1.65 -6.5],[],16,16); t4=text(-1.5,-1.65,-7.25,'global mininum'); set(t4,'HorizontalAlignment','center'); % Normal, black fill h8 = feval(mfilename,[-1.4 0 -7.2],[-1.4 0 -3],'FaceColor','k'); t5=text(-1.5,0,-7.75,'local minimum'); set(t5,'HorizontalAlignment','center'); % Gray fill, crossdir specified, 'LineStyle' -- h9 = feval(mfilename,[-3 2.2 -6],[-3 2.2 -.05],36,[],27,6,[],[0 -1 0], ... 'EdgeColor','k','FaceColor',.75*[1 1 1],'LineStyle','--'); % a series of normal arrows, linearly spaced, crossdir specified h10y=(0:4)'/3; h10 = feval(mfilename,[-3*ones(size(h10y)) h10y -6.5*ones(size(h10y))], ... [-3*ones(size(h10y)) h10y -.05*ones(size(h10y))], ... 12,[],[],[],[],[0 -1 0]); % a series of normal arrows, linearly spaced h11x=(1:.33:2.8)'; h11 = feval(mfilename,[h11x -3*ones(size(h11x)) 6.5*ones(size(h11x))], ... [h11x -3*ones(size(h11x)) -.05*ones(size(h11x))]); % series of magenta arrows, radially oriented, crossdir specified h12x=2; h12y=-3; h12z=axlim(5)/2; h12xr=1; h12zr=h12z; ir=.15;or=.81; h12t=(0:11)'/6*pi; h12 = feval(mfilename, ... [h12x+h12xr*cos(h12t)*ir h12y*ones(size(h12t)) ... h12z+h12zr*sin(h12t)*ir],[h12x+h12xr*cos(h12t)*or ... h12y*ones(size(h12t)) h12z+h12zr*sin(h12t)*or], ... 10,[],[],[],[], ... [-h12xr*sin(h12t) zeros(size(h12t)) h12zr*cos(h12t)],... 'FaceColor','none','EdgeColor','m'); % series of normal arrows, tangentially oriented, crossdir specified or13=.91; h13t=(0:.5:12)'/6*pi; locs = [h12x+h12xr*cos(h13t)*or13 h12y*ones(size(h13t)) h12z+h12zr*sin(h13t)*or13]; h13 = feval(mfilename,locs(1:end-1,:),locs(2:end,:),6); % arrow with no line ==> oriented downwards h14 = feval(mfilename,[3 3 .100001],[3 3 .1],30); t6=text(3,3,3.6,'no line'); set(t6,'HorizontalAlignment','center'); % arrow with arrowheads at both ends h15 = feval(mfilename,[-.5 -3 -3],[1 -3 -3],'Ends','both','FaceColor','g', ... 'Length',20,'Width',3,'CrossDir',[0 0 1],'TipAngle',25); h=[h1;h2;h3;h4;h5;h6;h7;h8;h9;h10;h11;h12;h13;h14;h15]; function h = arrow_demo2(in) axlim = in.axlim; dolog = 1; if (dolog), set(in.hs,'YData',10.^get(in.hs,'YData')); end; shading('interp'); view(2); title(['Demo of the capabilities of the ARROW function in 2-D']); hold on; [C,H]=contour(in.x,in.y,in.z,20,'-'); hold off; for k=H', set(k,'ZData',(axlim(6)+1)*ones(size(get(k,'XData'))),'Color','k'); if (dolog), set(k,'YData',10.^get(k,'YData')); end; end; if (dolog), axis([axlim(1:2) 10.^axlim(3:4)]); set(gca,'YScale','log'); else, axis(axlim(1:4)); end; % Normal blue arrow start = [axlim(1) axlim(4) axlim(6)+2]; stop = [in.x(in.iii) in.y(in.iii) axlim(6)+2]; if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end; h1 = feval(mfilename,start,stop,'EdgeColor','b','FaceColor','b'); % three arrows with varying fill, width, and baseangle start = [-3 -3 10; -3 -1.5 10; -1.5 -3 10]; stop = [-.03 -.03 10; -.03 -1.5 10; -1.5 -.03 10]; if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end; h2 = feval(mfilename,start,stop,24,[90;60;120],[],[0;0;4],'Ends',str2mat('both','stop','stop')); set(h2(2),'EdgeColor',[0 .35 0],'FaceColor',[0 .85 .85]); set(h2(3),'EdgeColor','r','FaceColor',[1 .5 1]); h=[h1;h2]; function out = trueornan(x) if isempty(x), out=x; else, out = isnan(x); out(~out) = x(~out); end;
github
philippboehmsturm/antx-master
read_besa_src.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/read_besa_src.m
2,719
utf_8
6a82938b50944385d04a571d87fb8cf8
function [src] = read_besa_src(filename); % READ_BESA_SRC reads a beamformer source reconstruction from a BESA file % % Use as % [src] = read_besa_src(filename) % % The output structure contains a minimal representation of the contents % of the file. % 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_besa_src.m 2885 2011-02-16 09:41:58Z roboos $ src = []; fid = fopen(filename, 'rt'); % read the header information line = fgetl(fid); while isempty(strmatch('BESA_SA_IMAGE', line)), line = fgetl(fid); check_feof(fid, filename); end % while isempty(strmatch('sd' , line)), line = fgetl(fid); check_feof(fid, filename); end % this line contains condition information while isempty(strmatch('Grid dimen' , line)), line = fgetl(fid); check_feof(fid, filename); end while isempty(strmatch('X:' , line)), line = fgetl(fid); check_feof(fid, filename); end; linex = line; while isempty(strmatch('Y:' , line)), line = fgetl(fid); check_feof(fid, filename); end; liney = line; while isempty(strmatch('Z:' , line)), line = fgetl(fid); check_feof(fid, filename); end; linez = line; tok = tokenize(linex, ' '); src.X = [str2num(tok{2}) str2num(tok{3}) str2num(tok{4})]; tok = tokenize(liney, ' '); src.Y = [str2num(tok{2}) str2num(tok{3}) str2num(tok{4})]; tok = tokenize(linez, ' '); src.Z = [str2num(tok{2}) str2num(tok{3}) str2num(tok{4})]; nx = src.X(3); ny = src.Y(3); nz = src.Z(3); src.vol = zeros(nx, ny, nz); for i=1:nz % search up to the next slice while isempty(strmatch(sprintf('Z: %d', i-1), line)), line = fgetl(fid); check_feof(fid, filename); end; % read all the values for this slice buf = fscanf(fid, '%f', [nx ny]); src.vol(:,:,i) = buf; end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function check_feof(fid, filename) if feof(fid) error(sprintf('could not read all information from file ''%s''', filename)); end
github
philippboehmsturm/antx-master
csd2transfer.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/csd2transfer.m
25,912
utf_8
514b6387ff408463962d6332c65322a2
function [output] = csd2transfer(freq, varargin) % CSD2TRANSFER computes the transfer-function from frequency domain data % using the Wilson-Burg algorithm. The transfer function can be used for % the computation of directional measures of connectivity, such as granger % causality, partial directed coherence, or directed transfer functions % % Use as % [output] = csd2transfer(freq, varargin) % % Where freq is a data structure containing frequency domain data containing % the cross-spectral density computed between all pairs of channels, thus % containing a 'dimord' of 'chan_chan_freq(_time)'. % % Configurable options come in key-value pairs: % % numiteration = scalar value (default: 100) the number of iterations % channelcmb = Nx2 cell-array listing the channel pairs for the spectral % factorization. If not defined or empty (default), a % full multivariate factorization is performed, otherwise % a multiple pairwise factorization is done. % tol = scalar value (default: 1e-18) tolerance limit truncating % the iterations % % The code for the Wilson-Burg algorithm has been very generously provided by % Dr. Mukesh Dhamala, and Prof. Mingzhou Ding and his group. % % If you use this code for studying directed interactions, please cite from % the following references: % -M.Dhamala, R.Rangarajan, M.Ding, Physical Review Letters 100, 018701 (2008) % -M.Dhamala, R.rangarajan, M.Ding, Neuroimage 41, 354 (2008) % Undocumented options: % % block % blockindx % svd % % Copyright (C) 2009-2011, 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: csd2transfer $ numiteration = ft_getopt(varargin, 'numiteration', 100); channelcmb = ft_getopt(varargin, 'channelcmb', {}); block = ft_getopt(varargin, 'block', {}); blockindx = ft_getopt(varargin, 'blockindx', cell(0,2)); tol = ft_getopt(varargin, 'tol', 1e-18); fb = ft_getopt(varargin, 'feedback', 'textbar'); sfmethod = ft_getopt(varargin, 'sfmethod', 'multivariate'); dosvd = ft_getopt(varargin, 'svd', 'no'); dosvd = istrue(dosvd); % check whether input data is valid freq = ft_checkdata(freq, 'datatype', 'freq'); if ~isfield(freq, 'crsspctrm') || ~isfield(freq, 'label') error('the input data does not contain cross-spectral density data in the supported format'); end hasrpt = ~isempty(strfind(freq.dimord, 'rpt')); if hasrpt, nrpt = numel(freq.cumtapcnt); else nrpt = 1; end % if bivariate is requested without channelcmb, do all versus all pairwise if isempty(channelcmb) && strcmp(sfmethod, 'bivariate') channelcmb = {'all' 'all'}; end if ~isempty(channelcmb) channelcmb = ft_channelcombination(channelcmb, freq.label); end if ~isempty(block) % sanity check 1 if ~iscell(block) error('block should be a cell-array containing 3 cells'); end % sanity check 2 if strcmp(sfmethod, 'bivariate') error('when block is specified, it is not OK to do bivariate decomposition'); end end %fsample = findcfg(freq.cfg, 'fsample'); fsample = 0; if isfield(freq, 'time'), ntim = numel(freq.time); else ntim = 1; end siz = size(freq.crsspctrm); if ntim==1, siz = [siz 1]; %add dummy dimensionality for time axis end if strcmp(sfmethod, 'bivariate') fprintf('computing pairwise non-parametric spectral factorization on %d channel pairs\n', size(channelcmb,1) - numel(unique(channelcmb(:)))); elseif strcmp(sfmethod, 'multivariate') fprintf('computing multivariate non-parametric spectral factorization on %d channels\n', numel(freq.label)); else error('unknown sfmethod %s', sfmethod); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the actual computations start here %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(sfmethod, 'multivariate') && isempty(block) && nrpt>1, %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % multiple repetitions, loop over repetitions % multivariate decomposition %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% H = zeros(siz) + 1i.*zeros(siz); S = zeros(siz) + 1i.*zeros(siz); Z = zeros([siz(1:3) siz(end)]); for k = 1:nrpt for m = 1:ntim tmp = reshape(freq.crsspctrm(k,:,:,:,m), siz(2:end-1)); [Htmp, Ztmp, Stmp] = sfactorization_wilson(tmp, fsample, freq.freq, ... numiteration, tol, fb); H(k,:,:,:,m) = Htmp; Z(k,:,:,m) = Ztmp; S(k,:,:,:,m) = Stmp; end end elseif strcmp(sfmethod, 'multivariate') && isempty(block), %%%%%%%%%%%%%%%%%%%%%%%%%%%% % standard code % multivariate decomposition %%%%%%%%%%%%%%%%%%%%%%%%%%%% H = zeros(siz) + 1i.*zeros(siz); S = zeros(siz) + 1i.*zeros(siz); Z = zeros([siz(1:2) siz(end)]); % only do decomposition once for m = 1:ntim tmp = freq.crsspctrm(:,:,:,m); % do SVD to avoid zigzags due to numerical issues if dosvd dat = sum(tmp,3); [u,s,v] = svd(real(dat)); for k = 1:size(tmp,3) tmp(:,:,k) = u'*tmp(:,:,k)*u; end end if any(isnan(tmp(:))), Htmp = nan; Ztmp = nan; Stmp = nan; else [Htmp, Ztmp, Stmp] = sfactorization_wilson(tmp, fsample, freq.freq, ... numiteration, tol, fb); end % undo SVD if dosvd for k = 1:size(tmp,3) Htmp(:,:,k) = u*Htmp(:,:,k)*u'; Stmp(:,:,k) = u*Stmp(:,:,k)*u'; end Ztmp = u*Ztmp*u'; end H(:,:,:,m) = Htmp; Z(:,:,m) = Ztmp; S(:,:,:,m) = Stmp; end elseif strcmp(sfmethod, 'bivariate') && nrpt>1, % error error('single trial estimates and linear combination indexing is not implemented'); elseif nrpt>1 && ~isempty(block), % error error('single trial estimates and blockwise factorisation is not yet implemented'); elseif strcmp(sfmethod, 'bivariate') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % pairwise factorization resulting in linearly indexed transfer functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %convert list of channel labels into indices cmbindx = zeros(size(channelcmb)); ok = true(size(cmbindx,1), 1); for k = 1:size(cmbindx,1) [tmp, cmbindx(k,:)] = match_str(channelcmb(k,:)', freq.label); if ~isempty(intersect(cmbindx(1:(k-1),:), cmbindx(k,:), 'rows')) ok(k) = false; elseif cmbindx(k,1)==cmbindx(k,2) ok(k) = false; end end %remove auto-combinations and double occurrences cmbindx = cmbindx(ok,:); channelcmb = channelcmb(ok,:); %do multiple 2x2 factorization efficiently if ntim>1, for kk = 1:ntim [Htmp, Ztmp, Stmp] = sfactorization_wilson2x2(freq.crsspctrm(:,:,:,kk), fsample, ... freq.freq, numiteration, tol, cmbindx, fb); if kk==1, H = Htmp; Z = Ztmp; S = Stmp; H(:,:,2:ntim) = nan; Z(:,:,2:ntim) = nan; S(:,:,2:ntim) = nan; else H(:,:,kk) = Htmp; Z(:,:,kk) = Ztmp; S(:,:,kk) = Stmp; end end else % if the number of pairs becomes too big, it seems to slow down quite a % bit. try to chunk if size(cmbindx,1)>1000 begchunk = 1:1000:size(cmbindx,1); endchunk = [1000:1000:size(cmbindx,1) size(cmbindx,1)]; H = zeros(4*size(cmbindx,1), numel(freq.freq)); S = zeros(4*size(cmbindx,1), numel(freq.freq)); Z = zeros(4*size(cmbindx,1), 1); for k = 1:numel(begchunk) fprintf('computing factorization of chunck %d/%d\n', k, numel(begchunk)); [Htmp, Ztmp, Stmp] = sfactorization_wilson2x2(freq.crsspctrm, fsample, freq.freq, ... numiteration, tol, cmbindx(begchunk(k):endchunk(k),:), fb); begix = (k-1)*4000+1; endix = min(k*4000, size(cmbindx,1)*4); H(begix:endix, :) = Htmp; S(begix:endix, :) = Stmp; Z(begix:endix, :) = Ztmp; end else [H, Z, S] = sfactorization_wilson2x2(freq.crsspctrm, fsample, freq.freq, ... numiteration, tol, cmbindx, fb); end end %convert crsspctrm accordingly siz = [size(H) 1]; tmpcrsspctrm = complex(zeros([2 2 siz(1)/4 siz(2:end)])); for k = 1:size(cmbindx,1) tmpcrsspctrm(:,:,k,:,:) = freq.crsspctrm(cmbindx(k,:),cmbindx(k,:),:,:); end freq.crsspctrm = reshape(tmpcrsspctrm, siz); labelcmb = cell(size(cmbindx,1)*4, 2); for k = 1:size(cmbindx,1) indx = (k-1)*4 + (1:4); labelcmb{indx(1),1} = [channelcmb{k,1},'[',channelcmb{k,1},channelcmb{k,2},']']; labelcmb{indx(1),2} = [channelcmb{k,1},'[',channelcmb{k,1},channelcmb{k,2},']']; labelcmb{indx(2),1} = [channelcmb{k,2},'[',channelcmb{k,1},channelcmb{k,2},']']; labelcmb{indx(2),2} = [channelcmb{k,1},'[',channelcmb{k,1},channelcmb{k,2},']']; labelcmb{indx(3),1} = [channelcmb{k,1},'[',channelcmb{k,1},channelcmb{k,2},']']; labelcmb{indx(3),2} = [channelcmb{k,2},'[',channelcmb{k,1},channelcmb{k,2},']']; labelcmb{indx(4),1} = [channelcmb{k,2},'[',channelcmb{k,1},channelcmb{k,2},']']; labelcmb{indx(4),2} = [channelcmb{k,2},'[',channelcmb{k,1},channelcmb{k,2},']']; end elseif ~isempty(block) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % blockwise multivariate stuff %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ntim>1, error('blockwise factorization of tfrs is not yet possible'); end %reorder the channel order such that the blocks are ordered nblocks = unique(blockindx{2}); for k = 1:numel(nblocks) %b{k} = cfg.blockindx{2}(find(cfg.blockindx{2}==nblocks(k))); b{k} = find(blockindx{2}==nblocks(k)); end indx = cat(1,b{:}); freq.crsspctrm = freq.crsspctrm(indx, indx, :); freq.label = freq.label(indx); bindx = blockindx{2}(indx); for k = 1:numel(block) sel = find(ismember(bindx, block{k})); Stmp = freq.crsspctrm(sel,sel,:); % do PCA to avoid zigzags due to numerical issues dopca = 1; if dopca dat = sum(Stmp,3); [u,s,v] = svd(real(dat)); for m = 1:size(Stmp,3) Stmp(:,:,m) = u'*Stmp(:,:,m)*u; end end [Htmp, Ztmp, Stmp] = sfactorization_wilson(Stmp, fsample, freq.freq, ... numiteration, tol, fb); % undo PCA if dopca for m = 1:size(Stmp,3) Htmp(:,:,m) = u*Htmp(:,:,m)*u'; Stmp(:,:,m) = u*Stmp(:,:,m)*u'; end Ztmp = u*Ztmp*u'; end siz = [size(Htmp) 1]; siz = [siz(1)*siz(2) siz(3:end)]; Htmp = reshape(Htmp, siz); siz = [size(Ztmp) 1]; siz = [siz(1)*siz(2) siz(3:end)]; Ztmp = reshape(Ztmp, siz); siz = [size(Stmp) 1]; siz = [siz(1)*siz(2) siz(3:end)]; Stmp = reshape(Stmp, siz); tmpindx = []; cmbtmp = cell(siz(1), 2); [tmpindx(:,1), tmpindx(:,2)] = ind2sub(sqrt(siz(1))*[1 1],1:siz(1)); for kk = 1:size(cmbtmp,1) cmbtmp{kk,1} = [freq.label{sel(tmpindx(kk,1))},'[',cat(2,freq.label{sel}),']']; cmbtmp{kk,2} = [freq.label{sel(tmpindx(kk,2))},'[',cat(2,freq.label{sel}),']']; end %concatenate if k == 1, H = Htmp; Z = Ztmp; S = Stmp; labelcmb = cmbtmp; else H = cat(1,H,Htmp); Z = cat(1,Z,Ztmp); S = cat(1,S,Stmp); labelcmb = cat(1,labelcmb,cmbtmp); end end if strcmp(freq.dimord(1:9), 'chan_chan'), freq.dimord = ['chancmb_',freq.dimord(10:end)]; end end % create output output = []; if strcmp(sfmethod, 'multivariate') output.dimord = freq.dimord; else ix = strfind(freq.dimord, 'chan_chan'); newdimord = [freq.dimord(1:(ix+3)),'cmb',freq.dimord(ix+9:end)]; %dimtok = tokenize(freq.dimord, '_'); %chdim = 0; %newdimord = ''; %for k = 1:numel(dimtok) % if strcmp(dimtok{k}, 'chan'), chdim = chdim+1; end % if chdim==1, % newdimord = [newdimord,'_chancmb']; % elseif chdim % newdimord = [newdimord, '_', dimtok{k}]; % end %end output.dimord = newdimord; end output.label = freq.label; output.freq = freq.freq; output.crsspctrm = S; output.transfer = H; output.noisecov = Z; try output.time = freq.time; catch end try output.cumtapcnt = freq.cumtapcnt; catch end try output.cumsumcnt = freq.cumsumcnt; catch end if exist('labelcmb', 'var') && ~isempty(labelcmb) output.labelcmb = labelcmb; output = rmfield(output, 'label'); end %------------------------------------------------------------------- function [H, Z, S, psi] = sfactorization_wilson(S,fs,freq,Niterations,tol,fb) % Usage : [H, Z, S, psi] = sfactorization_wilson(S,fs,freq); % Inputs : S (1-sided, 3D-spectral matrix in the form of Channel x Channel x frequency) % : fs (sampling frequency in Hz) % : freq (a vector of frequencies) at which S is given % Outputs: H (transfer function) % : Z (noise covariance) % : psi (left spectral factor) % This function is an implemention of Wilson's algorithm (Eq. 3.1) % for spectral matrix factorization % Ref: G.T. Wilson,"The Factorization of Matricial Spectral Densities," % SIAM J. Appl. Math.23,420-426(1972). % Written by M. Dhamala & G. Rangarajan, UF, Aug 3-4, 2006. % Email addresses: [email protected], [email protected] % number of channels m = size(S,1); N = length(freq)-1; N2 = 2*N; % preallocate memory for efficiency Sarr = zeros(m,m,N2) + 1i.*zeros(m,m,N2); gam = zeros(m,m,N2); gamtmp = zeros(m,m,N2); psi = zeros(m,m,N2); I = eye(m); % Defining m x m identity matrix %Step 1: Forming 2-sided spectral densities for ifft routine in matlab f_ind = 0; for f = freq f_ind = f_ind+1; Sarr(:,:,f_ind) = S(:,:,f_ind); if(f_ind>1) Sarr(:,:,2*N+2-f_ind) = S(:,:,f_ind).'; end end %Step 2: Computing covariance matrices for k1 = 1:m for k2 = 1:m %gam(k1,k2,:) = real(ifft(squeeze(Sarr(k1,k2,:)))*fs); %FIXME think about this gam(k1,k2,:) = real(ifft(squeeze(Sarr(k1,k2,:)))); end end %Step 3: Initializing for iterations gam0 = gam(:,:,1); [h, dum] = chol(gam0); if dum warning('initialization for iterations did not work well, using arbitrary starting condition'); h = rand(m,m); h = triu(h); %arbitrary initial condition end for ind = 1:N2 psi(:,:,ind) = h; end %Step 4: Iterating to get spectral factors ft_progress('init', fb, 'computing spectral factorization'); for iter = 1:Niterations ft_progress(iter./Niterations, 'computing iteration %d/%d\n', iter, Niterations); for ind = 1:N2 invpsi = inv(psi(:,:,ind));% + I*eps(psi(:,:,ind))); g(:,:,ind) = invpsi*Sarr(:,:,ind)*invpsi'+I;%Eq 3.1 end gp = PlusOperator(g,m,N+1); %gp constitutes positive and half of zero lags psi_old = psi; for k = 1:N2 psi(:,:,k) = psi(:,:,k)*gp(:,:,k); psierr(k) = norm(psi(:,:,k)-psi_old(:,:,k),1); end psierrf = mean(psierr); if(psierrf<tol), fprintf('reaching convergence at iteration %d\n',iter); break; end; % checking convergence end ft_progress('close'); %Step 5: Getting covariance matrix from spectral factors for k1 = 1:m for k2 = 1:m gamtmp(k1,k2,:) = real(ifft(squeeze(psi(k1,k2,:)))); end end %Step 6: Getting noise covariance & transfer function (see Example pp. 424) A0 = gamtmp(:,:,1); A0inv = inv(A0); %Z = A0*A0.'*fs; %Noise covariance matrix Z = A0*A0.'; %Noise covariance matrix not multiplied by sampling frequency %FIXME check this; at least not multiplying it removes the need to correct later on %this also makes it more equivalent to the noisecov estimated by biosig's mvar-function H = zeros(m,m,N+1) + 1i*zeros(m,m,N+1); for k = 1:N+1 H(:,:,k) = psi(:,:,k)*A0inv; %Transfer function S(:,:,k) = psi(:,:,k)*psi(:,:,k)'; %Updated cross-spectral density end %------------------------------------------------------------------------------ function [H, Z, S, psi] = sfactorization_wilson2x2(S,fs,freq,Niterations,tol,cmbindx,fb) % Usage : [H, Z, psi] = sfactorization_wilson(S,fs,freq); % Inputs : S (1-sided, 3D-spectral matrix in the form of Channel x Channel x frequency) % : fs (sampling frequency in Hz) % : freq (a vector of frequencies) at which S is given % Outputs: H (transfer function) % : Z (noise covariance) % : S (cross-spectral density 1-sided) % : psi (left spectral factor) % This function is an implemention of Wilson's algorithm (Eq. 3.1) % for spectral matrix factorization % Ref: G.T. Wilson,"The Factorization of Matricial Spectral Densities," % SIAM J. Appl. Math.23,420-426(1972). % Written by M. Dhamala & G. Rangarajan, UF, Aug 3-4, 2006. % Email addresses: [email protected], [email protected] m = size(cmbindx,1); N = length(freq)-1; N2 = 2*N; % preallocate memory for efficiency Sarr = zeros(2,2,m,N2) + 1i.*zeros(2,2,m,N2); I = repmat(eye(2),[1 1 m N2]); % Defining 2 x 2 identity matrix %Step 1: Forming 2-sided spectral densities for ifft routine in matlab for c = 1:m f_ind = 0; Stmp = S(cmbindx(c,:),cmbindx(c,:),:); for f = freq f_ind = f_ind+1; Sarr(:,:,c,f_ind) = Stmp(:,:,f_ind); if(f_ind>1) Sarr(:,:,c,2*N+2-f_ind) = Stmp(:,:,f_ind).'; end end end %Step 2: Computing covariance matrices gam = real(reshape(ifft(reshape(Sarr, [4*m N2]), [], 2),[2 2 m N2])); %Step 3: Initializing for iterations gam0 = gam(:,:,:,1); h = complex(zeros(size(gam0))); for k = 1:m [tmp, dum] = chol(gam0(:,:,k)); if dum warning('initialization for iterations did not work well, using arbitrary starting condition'); tmp = rand(2,2); h(:,:,k) = triu(tmp); %arbitrary initial condition else h(:,:,k) = tmp; end %h(:,:,k) = chol(gam0(:,:,k)); end psi = repmat(h, [1 1 1 N2]); %Step 4: Iterating to get spectral factors ft_progress('init', fb, 'computing spectral factorization'); for iter = 1:Niterations ft_progress(iter./Niterations, 'computing iteration %d/%d\n', iter, Niterations); invpsi = inv2x2(psi); g = sandwich2x2(invpsi, Sarr) + I; gp = PlusOperator2x2(g,m,N+1); %gp constitutes positive and half of zero lags psi_old = psi; psi = mtimes2x2(psi, gp); psierr = max(sum(abs(psi-psi_old))); psierrf = mean(psierr(:)); if(psierrf<tol), fprintf('reaching convergence at iteration %d\n',iter); break; end; % checking convergence end ft_progress('close'); %Step 5: Getting covariance matrix from spectral factors gamtmp = reshape(real(ifft(transpose(reshape(psi, [4*m N2]))))', [2 2 m N2]); %Step 6: Getting noise covariance & transfer function (see Example pp. 424) A0 = gamtmp(:,:,:,1); A0inv = inv2x2(A0); Z = zeros(2,2,m); for k = 1:m %Z = A0*A0.'*fs; %Noise covariance matrix Z(:,:,k) = A0(:,:,k)*A0(:,:,k).'; %Noise covariance matrix not multiplied by sampling frequency %FIXME check this; at least not multiplying it removes the need to correct later on %this also makes it more equivalent to the noisecov estimated by biosig's mvar-function end H = complex(zeros(2,2,m,N+1)); S = complex(zeros(2,2,m,N+1)); for k = 1:(N+1) for kk = 1:m H(:,:,kk,k) = psi(:,:,kk,k)*A0inv(:,:,kk); % Transfer function S(:,:,kk,k) = psi(:,:,kk,k)*psi(:,:,kk,k)'; % Cross-spectral density end end siz = [size(H) 1 1]; H = reshape(H, [4*siz(3) siz(4:end)]); siz = [size(S) 1 1]; S = reshape(S, [4*siz(3) siz(4:end)]); siz = [size(Z) 1 1]; Z = reshape(Z, [4*siz(3) siz(4:end)]); siz = [size(psi) 1 1]; psi = reshape(psi, [4*siz(3) siz(4:end)]); %--------------------------------------------------------------------- function gp = PlusOperator(g,nchan,nfreq) % This function is for [ ]+operation: % to take the positive lags & half of the zero lag and reconstitute % M. Dhamala, UF, August 2006 g = transpose(reshape(g, [nchan^2 2*(nfreq-1)])); gam = ifft(g); % taking only the positive lags and half of the zero lag gamp = gam; beta0 = 0.5*gam(1,:); gamp(1, :) = reshape(triu(reshape(beta0, [nchan nchan])),[1 nchan^2]); gamp(nfreq+1:end,:) = 0; % reconstituting gp = fft(gamp); gp = reshape(transpose(gp), [nchan nchan 2*(nfreq-1)]); %--------------------------------------------------------------------- function gp = PlusOperator2x2(g,ncmb,nfreq) % This function is for [ ]+operation: % to take the positive lags & half of the zero lag and reconstitute % M. Dhamala, UF, August 2006 g = transpose(reshape(g, [4*ncmb 2*(nfreq-1)])); gam = ifft(g); % taking only the positive lags and half of the zero lag gamp = gam; beta0 = 0.5*gam(1,:); for k = 1:ncmb gamp(1,(k-1)*4+1:k*4) = reshape(triu(reshape(beta0(1,(k-1)*4+1:k*4),[2 2])),[1 4]); end gamp(nfreq+1:end,:) = 0; % reconstituting gp = fft(gamp); gp = reshape(transpose(gp), [2 2 ncmb 2*(nfreq-1)]); %------------------------------------------------------ %this is the original code; above is vectorized version %which is assumed to be faster with many channels present %for k1 = 1:nchan % for k2 = 1:nchan % gam(k1,k2,:) = ifft(squeeze(g(k1,k2,:))); % end %end % %% taking only the positive lags and half of the zero lag %gamp = gam; %beta0 = 0.5*gam(:,:,1); %gamp(:,:,1) = triu(beta0); %this is Stau %gamp(:,:,nfreq+1:end) = 0; % %% reconstituting %for k1 = 1:nchan % for k2 = 1:nchan % gp(k1,k2,:) = fft(squeeze(gamp(k1,k2,:))); % end %end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %subfunctions for the 2x2 functionality %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%% %determinant of a 2x2 matrix function [d] = det2x2(x) %computes determinant of matrix x, using explicit analytic definition if %size(x,1) < 4, otherwise use matlab det-function siz = size(x); if all(siz(1:2)==2), d = x(1,1,:,:).*x(2,2,:,:) - x(1,2,:,:).*x(2,1,:,:); elseif all(siz(1:2)==3), d = x(1,1,:,:).*x(2,2,:,:).*x(3,3,:,:) - ... x(1,1,:,:).*x(2,3,:,:).*x(3,2,:,:) - ... x(1,2,:,:).*x(2,1,:,:).*x(3,3,:,:) + ... x(1,2,:,:).*x(2,3,:,:).*x(3,1,:,:) + ... x(1,3,:,:).*x(2,1,:,:).*x(3,2,:,:) - ... x(1,3,:,:).*x(2,2,:,:).*x(3,1,:,:); elseif numel(siz)==2, d = det(x); else %error %write for loop %for %end end %%%%%%%%%%%%%%%%%%%%%%%%% % inverse of a 2x2 matrix function [d] = inv2x2(x) %computes inverse of matrix x, using explicit analytic definition if %size(x,1) < 4, otherwise use matlab inv-function siz = size(x); if all(siz(1:2)==2), adjx = [x(2,2,:,:) -x(1,2,:,:); -x(2,1,:,:) x(1,1,:,:)]; denom = det2x2(x); d = adjx./denom([1 1],[1 1],:,:); elseif all(siz(1:2)==3), adjx = [ det2x2(x([2 3],[2 3],:,:)) -det2x2(x([1 3],[2 3],:,:)) det2x2(x([1 2],[2 3],:,:)); ... -det2x2(x([2 3],[1 3],:,:)) det2x2(x([1 3],[1 3],:,:)) -det2x2(x([1 2],[1 3],:,:)); ... det2x2(x([2 3],[1 2],:,:)) -det2x2(x([1 3],[1 2],:,:)) det2x2(x([1 2],[1 2],:,:))]; denom = det2x2(x); d = adjx./denom([1 1 1],[1 1 1],:,:); elseif numel(siz)==2, d = inv(x); else error('cannot compute slicewise inverse'); %write for loop for the higher dimensions, using normal inv end %%%%%%%%%%%%%%%%%%%%%%%%%%% % matrix multiplication 2x2 function [z] = mtimes2x2(x, y) % compute x*y % and dimensionatity is 2x2xN z = complex(zeros(size(x))); xconj = conj(x); z(1,1,:,:) = x(1,1,:,:).*y(1,1,:,:) + x(1,2,:,:).*y(2,1,:,:); z(1,2,:,:) = x(1,1,:,:).*y(1,2,:,:) + x(1,2,:,:).*y(2,2,:,:); z(2,1,:,:) = x(2,1,:,:).*y(1,1,:,:) + x(2,2,:,:).*y(2,1,:,:); z(2,2,:,:) = x(2,1,:,:).*y(1,2,:,:) + x(2,2,:,:).*y(2,2,:,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % quadratic multiplication 2x2 matrix, sandwiched matrix assumed hermitian function [z] = sandwich2x2(x, y) % compute x*y*x' provided y = hermitian % and dimensionatity is 2x2xN %FIXME build in check for hermitianity z = complex(zeros(size(x))); xconj = conj(x); xabs2 = abs(x).^2; z(1,1,:,:) = xabs2(1,1,:,:) .* y(1,1,:,:) + ... xabs2(1,2,:,:) .* y(2,2,:,:) + ... 2.*real(y(2,1,:,:).*xconj(1,1,:,:).*x(1,2,:,:)); z(2,1,:,:) = y(1,1,:,:).*xconj(1,1,:,:).*x(2,1,:,:) + ... y(2,1,:,:).*xconj(1,1,:,:).*x(2,2,:,:) + ... y(1,2,:,:).*xconj(1,2,:,:).*x(2,1,:,:) + ... y(2,2,:,:).*xconj(1,2,:,:).*x(2,2,:,:); z(1,2,:,:) = conj(z(2,1,:,:)); z(2,2,:,:) = xabs2(2,1,:,:) .* y(1,1,:,:) + ... xabs2(2,2,:,:) .* y(2,2,:,:) + ... 2.*real(y(1,2,:,:).*xconj(2,2,:,:).*x(2,1,:,:)); %b1 b2 a1 a2' b1' b3' %b3 b4 a2 a3 b2' b4' % %b1*a1+b2*a2 b1*a2'+b2*a3 b1' b3' %b3*a1+b4*a2 b3*a2'+b4*a3 b2' b4' % %b1*a1*b1'+b2*a2*b1'+b1*a2'*b2'+b2*a3*b2' b1*a1*b3'+b2*a2*b3'+b1*a2'*b4'+b2*a3*b4' %b3*a1*b1'+b4*a2*b1'+b3*a2'*b2'+b4*a3*b2' b3*a1*b3'+b4*a2*b3'+b3*a2'*b4'+b4*a3*b4' % %a1*abs(b1)^2 + a2*(b1'*b2) + a2'*(b1*b2') + a3*abs(b2)^2 a1*b1*b3' + a2*b2*b3' + a2'*b1*b4' + a3*b2*b4' %a1*b1'*b3 + a2*b1'*b4 + a2'*b2'*b3 + a3*b2'*b4 a1*abs(b3)^2 + a2*(b3'*b4) + a2'*(b3*b4') + a3*abs(b4)^2
github
philippboehmsturm/antx-master
splint.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/splint.m
6,073
utf_8
effb3e13a62ccd8d4c5ce226d6e17a2c
function [V2, L2, L1] = splint(elc1, V1, elc2) % SPLINT computes the spherical spline interpolation and the surface laplacian % of an EEG potential distribution % % Use as % [V2, L2, L1] = splint(elc1, V1, elc2) % where % elc1 electrode positions where potential is known % elc2 electrode positions where potential is not known % V1 known potential % and % V2 potential at electrode locations in elc2 % L2 laplacian of potential at electrode locations in elc2 % L1 laplacian of potential at electrode locations in elc1 % % See also LAPINT, LAPINTMAT, LAPCAL % This implements % F. Perrin, J. Pernier, O. Bertrand, and J. F. Echallier. % Spherical splines for scalp potential and curernt density mapping. % Electroencephalogr Clin Neurophysiol, 72:184-187, 1989. % including their corrections in % F. Perrin, J. Pernier, O. Bertrand, and J. F. Echallier. % Corrigenda: EEG 02274, Electroencephalography and Clinical % Neurophysiology 76:565. % Copyright (C) 2003, 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: splint.m 952 2010-04-21 18:29:51Z roboos $ N = size(elc1,1); % number of known electrodes M = size(elc2,1); % number of unknown electrodes T = size(V1,2); % number of timepoints in the potential Z = V1; % potential on known electrodes, can be matrix % remember the actual size of the sphere sphere1_scale = mean(sqrt(sum(elc1.^2,2))); sphere2_scale = mean(sqrt(sum(elc2.^2,2))); % scale all electrodes towards a unit sphere elc1 = elc1 ./ repmat(sqrt(sum(elc1.^2,2)), 1, 3); elc2 = elc2 ./ repmat(sqrt(sum(elc2.^2,2)), 1, 3); % compute cosine of angle between all known electrodes CosEii = zeros(N, N); for i=1:N for j=1:N CosEii(i,j) = 1 - sum((elc1(i,:) - elc1(j,:)).^2)/2; end end % compute matrix G of Perrin 1989 [gx, hx] = gh(CosEii); G = gx; % Note that the two simultaneous equations (2) of Perrin % G*C + T*c0 = Z % T'*C = 0 % with C = [c1 c2 c3 ...] can be rewritten into a single linear system % H * [c0 c1 c2 ... cN]' = [0 z1 z2 ... zN]' % with % H = [ 0 1 1 1 1 1 1 . ] % [ 1 g11 g12 . . . . . ] % [ 1 g21 g22 . . . . . ] % [ 1 g31 g32 . . . . . ] % [ 1 g41 g42 . . . . . ] % [ . . . . . . . . ] % that subsequently can be solved using a singular value decomposition % or another linear solver % rewrite the linear system according to the comment above and solve it for C % different from Perrin, this solution for C includes the c0 term H = ones(N+1,N+1); H(1,1) = 0; H(2:end,2:end) = G; % C = pinv(H)*[zeros(1,T); Z]; % solve with SVD C = H \ [zeros(1,T); Z]; % solve by Gaussian elimination % compute surface laplacian on all known electrodes by matrix multiplication L1 = hx * C(2:end, :); % undo the initial scaling of the sphere to get back to real units for the laplacian L1 = L1 / (sphere1_scale^2); if all(size(elc1)==size(elc2)) & all(elc1(:)==elc2(:)) warning('using shortcut for splint'); % do not recompute gx and hx else % compute cosine of angle between all known and unknown electrodes CosEji = zeros(M, N); for j=1:M for i=1:N CosEji(j,i) = 1 - sum((elc2(j,:) - elc1(i,:)).^2)/2; end end [gx, hx] = gh(CosEji); end % compute interpolated potential on all unknown electrodes by matrix multiplication V2 = [ones(M,1) gx] * C; % compute surface laplacian on all unknown electrodes by matrix multiplication L2 = hx * C(2:end, :); % undo the initial scaling of the sphere to get back to real units for the laplacian L2 = L2 / (sphere2_scale^2); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this subfunction implements equations (3) and (5b) of Perrin 1989 % for simultaneous computation of multiple values % also implemented as MEX file, but without the adaptive N %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [gx, hx] = gh(x) M = 4; % constant in denominator % N is the number of terms for series expansion % N=9 works fine for 32 electrodes, but for 128 electrodes it should be larger if max(size(x))<=32 N = 9; elseif max(size(x))<=64 N = 14; elseif max(size(x))<=128 N = 20; else N = 32; end p = zeros(1,N); gx = zeros(size(x)); hx = zeros(size(x)); x(find(x>1)) = 1; % to avoid rounding off errors x(find(x<-1)) = -1; % to avoid rounding off errors % using Matlab function to compute legendre polynomials % P = zeros(size(x,1), size(x,2), N); % for k=1:N % tmp = legendre(k,x); % P(:,:,k) = squeeze(tmp(1,:,:)); % end if (size(x,1)==size(x,2)) & all(all(x==x')) issymmetric = 1; else issymmetric = 0; end for i=1:size(x,1) if issymmetric jloop = i:size(x,2); else jloop = 1:size(x,2); end for j=jloop % using faster "Numerical Recipies in C" plgndr function (mex file) for k=1:N p(k) = plgndr(k,0,x(i,j)); end % p = squeeze(P(i, j ,:))'; gx(i,j) = sum((2*(1:N)+1) ./ ((1:N).*((1:N)+1)).^M .* p) / (4*pi); hx(i,j) = -sum((2*(1:N)+1) ./ ((1:N).*((1:N)+1)).^(M-1) .* p) / (4*pi); if issymmetric gx(j,i) = gx(i,j); hx(j,i) = hx(i,j); end % fprintf('computing laplacian %f%% done\n', 100*(((i-1)*size(x,2)+j) / prod(size(x)))); end end
github
philippboehmsturm/antx-master
find_nearest.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/find_nearest.m
5,969
utf_8
e1ece21f9a10e0702c7af8f405936b51
function [nearest, distance] = find_nearest(pnt1, pnt2, npart, gridflag) % FIND_NEAREST finds the nearest vertex in a cloud of points and % does this efficiently for many target vertices at once (by means % of partitioning). % % Use as % [nearest, distance] = find_nearest(pnt1, pnt2, npart) % Copyright (C) 2007, 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: find_nearest.m 2952 2011-02-25 11:05:36Z jansch $ global fb; if isempty(fb) fb = 0; end if nargin<4 gridflag = 0; end npnt1 = size(pnt1,1); npnt2 = size(pnt2,1); if ~gridflag % check whether pnt2 is gridded if all(pnt2(1,:)==1) % it might be gridded, test in more detail dim = max(pnt2, [], 1); [X, Y, Z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3)); gridflag = all(pnt2(:)==[X(:);Y(:);Z(:)]); end end if gridflag % it is gridded, that can be treated much faster if fb, fprintf('pnt2 is gridded\n'); end sub = round(pnt1); sub(sub(:)<1) = 1; sub(sub(:,1)>dim(1),1) = dim(1); sub(sub(:,2)>dim(2),2) = dim(2); sub(sub(:,3)>dim(3),3) = dim(3); ind = sub2ind(dim, sub(:,1), sub(:,2), sub(:,3)); nearest = ind(:); distance = sqrt(sum((pnt1-pnt2(ind,:)).^2, 2)); return end if npart<1 npart = 1; end nearest = ones(size(pnt1,1),1) * -1; distance = ones(size(pnt1,1),1) * inf; sel = find(nearest<0); while ~isempty(sel) if fb, fprintf('nsel = %d, npart = %d\n', length(sel), npart); end [pnear, pdist] = find_nearest_partition(pnt1(sel,:), pnt2, npart); better = pdist<=distance(sel); nearest(sel(better)) = pnear(better); distance(sel(better)) = distance(better); sel = find(nearest<0); npart = floor(npart/2); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nearest, distance] = find_nearest_partition(pnt1, pnt2, npart) global fb; if isempty(fb) fb = 0; end npnt1 = size(pnt1,1); npnt2 = size(pnt2,1); % this will contain the output nearest = zeros(npnt1, 1); distance = zeros(npnt1, 1); if npnt1==0 return end minpnt1 = min(pnt1,1); minpnt2 = min(pnt2,1); maxpnt1 = max(pnt1,1); maxpnt2 = max(pnt2,1); pmin = min([minpnt1; minpnt2]) - eps; pmax = max([maxpnt1; maxpnt2]) + eps; dx = (pmax(1)-pmin(1))/npart; dy = (pmax(2)-pmin(2))/npart; dz = (pmax(3)-pmin(3))/npart; % determine the lower boundaries of each partition along the x, y, and z-axis limx = pmin(1) + (0:(npart-1)) * dx; limy = pmin(2) + (0:(npart-1)) * dy; limz = pmin(3) + (0:(npart-1)) * dz; % determine the lower boundaries of each of the N^3 partitions [X, Y, Z] = ndgrid(limx, limy, limz); partlim = [X(:) Y(:) Z(:)]; % determine for each vertex to which partition it belongs binx = ceil((pnt1(:,1)- pmin(1))/dx); biny = ceil((pnt1(:,2)- pmin(2))/dy); binz = ceil((pnt1(:,3)- pmin(3))/dz); ind1 = (binx-1)*npart^0 + (biny-1)*npart^1 +(binz-1)*npart^2 + 1; binx = ceil((pnt2(:,1)- pmin(1))/dx); biny = ceil((pnt2(:,2)- pmin(2))/dy); binz = ceil((pnt2(:,3)- pmin(3))/dz); ind2 = (binx-1)*npart^0 + (biny-1)*npart^1 +(binz-1)*npart^2 + 1; % use the brute force approach within each partition for p=1:(npart^3) sel1 = (ind1==p); sel2 = (ind2==p); nsel1 = sum(sel1); nsel2 = sum(sel2); if nsel1==0 || nsel2==0 continue end pnt1s = pnt1(sel1, :); pnt2s = pnt2(sel2, :); [pnear, pdist] = find_nearest_brute_force(pnt1s, pnt2s); % determine the points that are sufficiently far from the partition edge seln = true(nsel1, 1); if npart>1 if partlim(p,1)>pmin(1), seln = seln & (pdist < (pnt1s(:,1) - partlim(p,1))); end if partlim(p,1)>pmin(2), seln = seln & (pdist < (pnt1s(:,2) - partlim(p,2))); end if partlim(p,1)>pmin(3), seln = seln & (pdist < (pnt1s(:,3) - partlim(p,3))); end if partlim(p,1)<pmin(1), seln = seln & (pdist < (partlim(p,1)) + dx - pnt1s(:,1)); end if partlim(p,2)<pmin(2), seln = seln & (pdist < (partlim(p,2)) + dx - pnt1s(:,2)); end if partlim(p,3)<pmin(3), seln = seln & (pdist < (partlim(p,3)) + dx - pnt1s(:,3)); end end % the results have to be re-indexed dum1 = find(sel1); dum2 = find(sel2); nearest(dum1( seln)) = dum2(pnear( seln)); nearest(dum1(~seln)) = -dum2(pnear(~seln)); % negative means that it is not certain distance(dum1) = pdist; end % handle the points that ly in empty target partitions sel = (nearest==0); if any(sel) if fb, fprintf('%d points in empty target partition\n', sum(sel)); end pnt1s = pnt1(sel, :); [pnear, pdist] = find_nearest_brute_force(pnt1s, pnt2); nearest(sel) = pnear; distance(sel) = pdist; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nearest, distance] = find_nearest_brute_force(pnt1, pnt2) % implementation 1 -- brute force npnt1 = size(pnt1,1); npnt2 = size(pnt2,1); nearest = zeros(npnt1, 1); distance = zeros(npnt1, 1); if npnt1==0 || npnt2==0 return end for i=1:npnt1 % compute squared distance tmp = (pnt2(:,1) - pnt1(i,1)).^2 + (pnt2(:,2) - pnt1(i,2)).^2 + (pnt2(:,3) - pnt1(i,3)).^2; [distance(i), nearest(i)] = min(tmp); end distance = sqrt(distance); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plotpnt(pnt, varargin) x = pnt(:,1); y = pnt(:,2); z = pnt(:,3); plot3(x, y, z, varargin{:});
github
philippboehmsturm/antx-master
inifile.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/inifile.m
23,578
utf_8
f647125ffa71c22e44a119c27e73d460
function readsett = inifile(fileName,operation,keys,style) %readsett = INIFILE(fileName,operation,keys,style) % Creates, reads, or writes data from/to ini (ascii) file. % % - fileName: ini file name % - operation: can be one of the following: % 'new' (rewrites an existing or creates a new, empty file), % 'deletekeys'(deletes keys and their values - if they exist), % 'read' (reads values as strings), % 'write' (writes values given as strings), % - keys: cell array of STRINGS; max 5 columns, min % 3 columns. Each row has the same number of columns. The columns are: % 'section': section name string (the root is considered if empty or not given) % 'subsection': subsection name string (the root is considered if empty or not given) % 'key': name of the field to write/read from (given as a string). % 'value': (optional) string-value to write to the ini file in case of 'write' operation % 'defaultValue': (optional) value that is returned when the key is not found when reading ('read' operation) % - style: 'tabbed' writes sections, subsections and keys in a tabbed style % to get a more readable file. The 'plain' style is the % default style. This only affects the keys that will be written/rewritten. % % - readsett: read setting in the case of the 'read' operation. If % the keys are not found, the default values are returned % as strings (if given in the 5-th column). % % EXAMPLE: % Suppose we want a new ini file, test1.ini with 3 fields. % We can write them into the file using: % % inifile('test1.ini','new'); % writeKeys = {'measurement','person','name','Primoz Cermelj';... % 'measurement','protocol','id','1';... % 'application','','description','some...'}; % inifile('test1.ini','write',writeKeys,'plain'); % % Later, you can read them out. Additionally, if any of them won't % exist, a default value will be returned (if the 5-th column is given as below). % % readKeys = {'measurement','person','name','','John Doe';... % 'measurement','protocol','id','','0';... % 'application','','description','','none'}; % readSett = inifile('test1.ini','read',readKeys); % % % NOTES: When the operation is 'new', only the first 2 parameters are % required. If the operation is 'write' and the file is empty or does not exist, % a new file is created. When writing and if any of the section or subsection or key does not exist, % it creates (adds) a new one. % Everything but value is NOT case sensitive. Given keys and values % will be trimmed (leading and trailing spaces will be removed). % Any duplicates (section, subsection, and keys) are ignored. Empty section and/or % subsection can be given as an empty string, '', but NOT as an empty matrix, []. % % This function was tested on the win32 platform only but it should % also work on Unix/Linux platforms. Since some short-circuit operators % are used, at least Matlab 6.5 should be used. % % FREE SOFTWARE - please refer the source % Copyright (c) 2003 by Primoz Cermelj % First release on 29.01.2003 % Primoz Cermelj, Slovenia % Contact: [email protected] % Download location: http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=2976&objectType=file % % Version: 1.1.0 % Last revision: 04.02.2004 % % Bug reports, questions, etc. can be sent to the e-mail given above. % % This programme is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or any later version. % % This programme is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. %-------------------------------------------------------------------------- %---------------- % INIFILE history %---------------- % % [v.1.1.0] 04.02.2004 % - FIX: 'writetext' option removed (there was a bug previously) % % [v.1.01b] 19.12.2003 % - NEW: A new concept - multiple keys can now be read, written, or deleted % ALL AT ONCE which makes this function much faster. For example, to % write 1000 keys, using previous versions it took 157 seconds on a % 1.5 GHz machine, with this new version it took only 1.83 seconds. % In general, the speed improvement is greater when larger number of % read/written keys are considered. % - NEW: The format of the input parameters has changed. See above. % % [v.0.97] 19.11.2003 % - NEW: Additional m-function, strtrim, is no longer needed % % [v.0.96] 16.10.2003 % - FIX: Detects empty keys % % [v.0.95] 04.07.2003 % - NEW: 'deletekey' option/operation added % - FIX: A major file refinement to obtain a more compact utility -> additional operations can "easily" be implemented % % [v.0.91-0.94] % - FIX: Some minor refinements % % [v.0.90] 29.01.2003 % - NEW: First release of this tool % %---------------- global NL_CHAR; % Checks the input arguments if nargin < 2 error('Not enough input arguments'); end if (strcmpi(operation,'read')) | (strcmpi(operation,'deletekeys')) if nargin < 3 error('Not enough input arguments.'); end if ~exist(fileName) error(['File ' fileName ' does not exist.']); end [m,n] = size(keys); if n > 5 error('Keys argument has too many columns'); end for ii=1:m if isempty(keys(ii,3)) | ~ischar(keys{ii,3}) error('Empty or non-char keys are not allowed.'); end end elseif (strcmpi(operation,'write')) | (strcmpi(operation,'writetext')) if nargin < 3 error('Not enough input arguments'); end [m,n] = size(keys); for ii=1:m if isempty(keys(ii,3)) | ~ischar(keys{ii,3}) error('Empty or non-char keys are not allowed.'); end end elseif (~strcmpi(operation,'new')) error(['Unknown inifile operation: ''' operation '''']); end if nargin >= 3 for ii=1:m for jj=1:n if ~ischar(keys{ii,jj}) error('All cells from keys must be given as strings, even the empty ones.'); end end end end if nargin < 4 || isempty(style) style = 'plain'; else if ~(strcmpi(style,'plain') | strcmpi(style,'tabbed')) | ~ischar(style) error('Unsupported style given or style not given as a string'); end end % Sets new-line character (string) if ispc NL_CHAR = '\r\n'; else NL_CHAR = '\n'; end %---------------------------- % CREATES a new, empty file (rewrites an existing one) %---------------------------- if strcmpi(operation,'new') fh = fopen(fileName,'w'); if fh == -1 error(['File: ''' fileName ''' can not be (re)created']); end fclose(fh); return %---------------------------- % READS key-value pairs out %---------------------------- elseif (strcmpi(operation,'read')) if n < 5 defaultValues = cellstrings(m,1); else defaultValues = keys(:,5); end readsett = defaultValues; keysIn = keys(:,1:3); [secsExist,subsecsExist,keysExist,readValues,so,eo] = findkeys(fileName,keysIn); ind = find(keysExist); if ~isempty(ind) readsett(ind) = readValues(ind); end return %---------------------------- % WRITES key-value pairs to an existing or non-existing % file (file can even be empty) %---------------------------- elseif (strcmpi(operation,'write')) if m < 1 error('At least one key is needed when writing keys'); end if ~exist(fileName) inifile(fileName,'new'); end writekeys(fileName,keys,style); return %---------------------------- % DELETES key-value pairs out %---------------------------- elseif (strcmpi(operation,'deletekeys')) deletekeys(fileName,keys); else error('Unknown operation for INIFILE.'); end %-------------------------------------------------- %%%%%%%%%%%%% SUBFUNCTIONS SECTION %%%%%%%%%%%%%%%% %-------------------------------------------------- %------------------------------------ function [secsExist,subSecsExist,keysExist,values,startOffsets,endOffsets] = findkeys(fileName,keysIn) % This function parses ini file for keys as given by keysIn. keysIn is a cell % array of strings having 3 columns; section, subsection and key in each row. % section and/or subsection can be empty (root section or root subsection) % but the key can not be empty. The startOffsets and endOffsets are start and % end bytes that each key occuppies, respectively. If any of the keys doesn't exist, % startOffset and endOffset for this key are the same. A special case is % when the key that doesn't exist also corresponds to a non-existing % section and non-existing subsection. In such a case, the startOffset and % endOffset have values of -1. nKeys = size(keysIn,1); % number of keys nKeysLocated = 0; % number of keys located secsExist = zeros(nKeys,1); % if section exists (and is non-empty) subSecsExist = zeros(nKeys,1); % if subsection... keysExist = zeros(nKeys,1); % if key that we are looking for exists keysLocated = keysExist; % if the key's position (existing or non-existing) is LOCATED values = cellstrings(nKeys,1); % read values of keys (strings) startOffsets = -ones(nKeys,1); % start byte-position of the keys endOffsets = -ones(nKeys,1); % end byte-position of the keys keyInd = find(strcmpi(keysIn(:,1),'')); % key indices having [] section (root section) line = []; currSection = ''; currSubSection = ''; fh = fopen(fileName,'r'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try %--- Searching for the keys - their values and start and end locations in bytes while 1 pos1 = ftell(fh); line = fgetl(fh); if line == -1 % end of file, exit line = []; break end [status,readValue,readKey] = processiniline(line); if (status == 1) % (new) section found % Keys that were found as belonging to any previous section % are now assumed as located (because another % section is found here which could even be a repeated one) keyInd = find( ~keysLocated & strcmpi(keysIn(:,1),currSection) ); if length(keyInd) keysLocated(keyInd) = 1; nKeysLocated = nKeysLocated + length(keyInd); end currSection = readValue; currSubSection = ''; % Indices to non-located keys belonging to current section keyInd = find( ~keysLocated & strcmpi(keysIn(:,1),currSection) ); if ~isempty(keyInd) secsExist(keyInd) = 1; end pos2 = ftell(fh); startOffsets(keyInd) = pos2+1; endOffsets(keyInd) = pos2+1; elseif (status == 2) % (new) subsection found % Keys that were found as belonging to any PREVIOUS section % and/or subsection are now assumed as located (because another % subsection is found here which could even be a repeated one) keyInd = find( ~keysLocated & strcmpi(keysIn(:,1),currSection) & ~keysLocated & strcmpi(keysIn(:,2),currSubSection)); if length(keyInd) keysLocated(keyInd) = 1; nKeysLocated = nKeysLocated + length(keyInd); end currSubSection = readValue; % Indices to non-located keys belonging to current section and subsection at the same time keyInd = find( ~keysLocated & strcmpi(keysIn(:,1),currSection) & ~keysLocated & strcmpi(keysIn(:,2),currSubSection)); if ~isempty(keyInd) subSecsExist(keyInd) = 1; end pos2 = ftell(fh); startOffsets(keyInd) = pos2+1; endOffsets(keyInd) = pos2+1; elseif (status == 3) % key found if isempty(keyInd) continue % no keys from 'keys' - from section-subsection par currently in end currKey = readValue; pos2 = ftell(fh); % the last-byte position of the read key - the total sum of chars read so far for ii=1:length(keyInd) if strcmpi( keysIn(keyInd(ii),3),readKey ) & ~keysLocated(keyInd(ii)) keysExist(keyInd(ii)) = 1; startOffsets(keyInd(ii)) = pos1+1; endOffsets(keyInd(ii)) = pos2; values{keyInd(ii)} = currKey; keysLocated(keyInd(ii)) = 1; nKeysLocated = nKeysLocated + 1; else if ~keysLocated(keyInd(ii)) startOffsets(keyInd(ii)) = pos2+1; endOffsets(keyInd(ii)) = pos2+1; end end end if nKeysLocated >= nKeys % if all the keys are located break end else % general text found (even empty line(s)) end %--- End searching end fclose(fh); catch fclose(fh); error(['Error parsing the file for keys: ' fileName ': ' lasterr]); end %------------------------------------ %------------------------------------ function writekeys(fileName,keys,style) % Writes keys to the section and subsection pair % If any of the keys doesn't exist, a new key is added to % the end of the section-subsection pair otherwise the key is updated (changed). % Keys is a 4-column cell array of strings. global NL_CHAR; RETURN = sprintf('\r'); NEWLINE = sprintf('\n'); [m,n] = size(keys); if n < 4 error('Keys to be written are given in an invalid format.'); end % Get keys position first using findkeys keysIn = keys; [secsExist,subSecsExist,keysExist,readValues,so,eo] = findkeys(fileName,keys(:,1:3)); % Read the whole file's contents out fh = fopen(fileName,'r'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try dataout = fscanf(fh,'%c'); catch fclose(fh); error(lasterr); end fclose(fh); %--- Rewriting the file -> writing the refined contents fh = fopen(fileName,'w'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try tab1 = []; if strcmpi(style,'tabbed') tab1 = sprintf('\t'); end % Proper sorting of keys is cruical at this point in order to avoid % inproper key-writing. % Find keys with -1 offsets - keys with non-existing section AND % subsection - keys that will be added to the end of the file fs = length(dataout); % file size in bytes nAddedKeys = 0; ind = find(so==-1); if ~isempty(ind) so(ind) = (fs+10); % make sure these keys will come to the end when sorting eo(ind) = (fs+10); nAddedKeys = length(ind); end % Sort keys according to start- and end-offsets [dummy,ind] = sort(so,1); so = so(ind); eo = eo(ind); keysIn = keysIn(ind,:); keysExist = keysExist(ind); secsExist = secsExist(ind); subSecsExist = subSecsExist(ind); readValues = readValues(ind); values = keysIn(:,4); % Find keys with equal start offset (so) and additionally sort them % (locally). These are non-existing keys, including the ones whose % section and subsection will also be added. nKeys = size(so,1); fullInd = 1:nKeys; ii = 1; while ii < nKeys ind = find(so==so(ii)); if ~isempty(ind) && length(ind) > 1 n = length(ind); from = ind(1); to = ind(end); tmpKeys = keysIn( ind,: ); [tmpKeys,ind2] = sortrows( lower(tmpKeys) ); fullInd(from:to) = ind(ind2); ii = ii + n; else ii = ii + 1; end end % Final (re)sorting so = so(fullInd); eo = eo(fullInd); keysIn = keysIn(fullInd,:); keysExist = keysExist(fullInd); secsExist = secsExist(fullInd); subSecsExist = subSecsExist(fullInd); readValues = readValues(fullInd); values = keysIn(:,4); % Refined data - datain datain = []; for ii=1:nKeys % go through all the keys, existing and non-existing ones if ii==1 from = 1; % from byte-offset of original data (dataout) else from = eo(ii-1); if keysExist(ii-1) from = from + 1; end end to = min(so(ii)-1,fs); % to byte-offset of original data (dataout) if ~isempty(dataout) datain = [datain dataout(from:to)]; % the lines before the key end if length(datain) & (~(datain(end)==RETURN | datain(end)==NEWLINE)) datain = [datain, sprintf(NL_CHAR)]; end tab = []; if ~keysExist(ii) if ~secsExist(ii) && ~isempty(keysIn(ii,1)) if ~isempty(keysIn{ii,1}) datain = [datain sprintf(['%s' NL_CHAR],['[' keysIn{ii,1} ']'])]; end % Key-indices with the same section as this, ii-th key (even empty sections are considered) ind = find( strcmpi( keysIn(:,1), keysIn(ii,1)) ); % This section exists at all keys corresponding to the same section from know on (even the empty ones) secsExist(ind) = 1; end if ~subSecsExist(ii) && ~isempty(keysIn(ii,2)) if ~isempty( keysIn{ii,2}) if secsExist(ii); tab = tab1; end; datain = [datain sprintf(['%s' NL_CHAR],[tab '{' keysIn{ii,2} '}'])]; end % Key-indices with the same section AND subsection as this, ii-th key (even empty sections and subsections are considered) ind = find( strcmpi( keysIn(:,1), keysIn(ii,1)) & strcmpi( keysIn(:,2), keysIn(ii,2)) ); % This subsection exists at all keys corresponding to the same section and subsection from know on (even the empty ones) subSecsExist(ind) = 1; end end if secsExist(ii) & (~isempty(keysIn{ii,1})); tab = tab1; end; if subSecsExist(ii) & (~isempty(keysIn{ii,2})); tab = [tab tab1]; end; datain = [datain sprintf(['%s' NL_CHAR],[tab keysIn{ii,3} ' = ' values{ii}])]; end from = eo(ii); if keysExist(ii) from = from + 1; end to = length(dataout); if from < to datain = [datain dataout(from:to)]; end fprintf(fh,'%c',datain); catch fclose(fh); error(['Error writing keys to file: ''' fileName ''' : ' lasterr]); end fclose(fh); %------------------------------------ %------------------------------------ function deletekeys(fileName,keys) % Deletes keys and their values out; keys must have at least 3 columns: % section, subsection, and key [m,n] = size(keys); if n < 3 error('Keys to be deleted are given in an invalid format.'); end % Get keys position first keysIn = keys; [secsExist,subSecsExist,keysExist,readValues,so,eo] = findkeys(fileName,keys(:,1:3)); % Read the whole file's contents out fh = fopen(fileName,'r'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try dataout = fscanf(fh,'%c'); catch fclose(fh); error(lasterr); end fclose(fh); %--- Rewriting the file -> writing the refined contents fh = fopen(fileName,'w'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try ind = find(keysExist); nExistingKeys = length(ind); datain = dataout; if nExistingKeys % Filtering - retain only the existing keys... fs = length(dataout); % file size in bytes so = so(ind); eo = eo(ind); keysIn = keysIn(ind,:); % ...and sorting [so,ind] = sort(so); eo = eo(ind); keysIn = keysIn(ind,:); % Refined data - datain datain = []; for ii=1:nExistingKeys % go through all the existing keys if ii==1 from = 1; % from byte-offset of original data (dataout) else from = eo(ii-1)+1; end to = so(ii)-1; % to byte-offset of original data (dataout) if ~isempty(dataout) datain = [datain dataout(from:to)]; % the lines before the key end end from = eo(ii)+1; to = length(dataout); if from < to datain = [datain dataout(from:to)]; end end fprintf(fh,'%c',datain); catch fclose(fh); error(['Error deleting keys from file: ''' fileName ''' : ' lasterr]); end fclose(fh); %------------------------------------ %------------------------------------ function [status,value,key] = processiniline(line) % Processes a line read from the ini file and % returns the following values: % - status: 0 => empty line or unknown string % 1 => section found % 2 => subsection found % 3 => key-value pair found % - value: value-string of a key, section, or subsection % - key: key-string status = 0; value = []; key = []; line = strim(line); % removes any leading and trailing spaces if isempty(line) % empty line return end if (line(1) == '[') & (line(end) == ']')... % section found & (length(line) >= 3) value = lower(line(2:end-1)); status = 1; elseif (line(1) == '{') &... % subsection found (line(end) == '}') & (length(line) >= 3) value = lower(line(2:end-1)); status = 2; else pos = findstr(line,'='); if ~isempty(pos) % key-value pair found status = 3; key = lower(line(1:pos-1)); value = line(pos+1:end); key = strim(key); % removes any leading and trailing spaces value = strim(value); % removes any leading and trailing spaces if isempty(key) % empty keys are not allowed status = 0; key = []; value = []; end end end %------------------------------------ %------------------------------------ function outstr = strim(str) % Removes leading and trailing spaces (spaces, tabs, endlines,...) % from the str string. if isnumeric(str); outstr = str; return end ind = find( ~isspace(str) ); % indices of the non-space characters in the str if isempty(ind) outstr = []; else outstr = str( ind(1):ind(end) ); end %------------------------------------ function cs = cellstrings(m,n) % Creates a m x n cell array of empty strings - '' cs = cell(m,n); for ii=1:m for jj=1:n cs{ii,jj} = ''; end end
github
philippboehmsturm/antx-master
read_besa_avr.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/read_besa_avr.m
3,929
utf_8
9e36880bf3e6eb7d211a5dea7ce2d885
function [avr] = read_besa_avr(filename) % READ_BESA_AVR reads average EEG data in BESA format % % Use as % [avr] = read_besa_avr(filename) % % This will return a structure with the header information in % avr.npnt % avr.tsb % avr.di % avr.sb % avr.sc % avr.Nchan (optional) % avr.label (optional) % and the ERP data is contained in the Nchan X Nsamples matrix % avr.data % Copyright (C) 2003-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_besa_avr.m 2885 2011-02-16 09:41:58Z roboos $ fid = fopen(filename, 'rt'); % the first line contains header information headstr = fgetl(fid); ok = 0; if ~ok try buf = sscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f Nchan= %f SegmentName= %s\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); avr.Nchan = buf(6); avr.SegmentName = buf(7); ok = 1; catch ok = 0; end end if ~ok try buf = fscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f Nchan= %f\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); avr.Nchan = buf(6); ok = 1; catch ok = 0; end end if ~ok try buf = sscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); ok = 1; catch ok = 0; end end if ~ok error('Could not interpret the header information.'); end % rewind to the beginning of the file, skip the header line fseek(fid, 0, 'bof'); fgetl(fid); % the second line may contain channel names chanstr = fgetl(fid); chanstr = deblank(fliplr(deblank(fliplr(chanstr)))); if (chanstr(1)>='A' && chanstr(1)<='Z') || (chanstr(1)>='a' && chanstr(1)<='z') haschan = 1; avr.label = str2cell(strrep(deblank(chanstr), '''', ''))'; else [root, name] = fileparts(filename); haschan = 0; elpfile = fullfile(root, [name '.elp']); elafile = fullfile(root, [name '.ela']); if exist(elpfile, 'file') % read the channel names from the accompanying ELP file lbl = importdata(elpfile); avr.label = strrep(lbl.textdata(:,2) ,'''', ''); elseif exist(elafile, 'file') % read the channel names from the accompanying ELA file lbl = importdata(elafile); lbl = strrep(lbl ,'MEG ', ''); % remove the channel type lbl = strrep(lbl ,'EEG ', ''); % remove the channel type avr.label = lbl; else warning('Could not create channels labels.'); end end % seek to the beginning of the data fseek(fid, 0, 'bof'); fgetl(fid); % skip the header line if haschan fgetl(fid); % skip the channel name line end buf = fscanf(fid, '%f'); nchan = length(buf)/avr.npnt; avr.data = reshape(buf, avr.npnt, nchan)'; fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to cut a string into pieces at the spaces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function c = str2cell(s) c = {}; [t, r] = strtok(s, ' '); while ~isempty(t) c{end+1} = t; [t, r] = strtok(r, ' '); end
github
philippboehmsturm/antx-master
sftrans.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/sftrans.m
7,947
utf_8
f64cb2e7d19bcdc6232b39d8a6d70e7c
% Copyright (C) 1999 Paul Kienzle % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop) % % Transform band edges of a generic lowpass filter (cutoff at W=1) % represented in splane zero-pole-gain form. W is the edge of the % target filter (or edges if band pass or band stop). Stop is true for % high pass and band stop filters or false for low pass and band pass % filters. Filter edges are specified in radians, from 0 to pi (the % nyquist frequency). % % Theory: Given a low pass filter represented by poles and zeros in the % splane, you can convert it to a low pass, high pass, band pass or % band stop by transforming each of the poles and zeros individually. % The following table summarizes the transformation: % % Transform Zero at x Pole at x % ---------------- ------------------------- ------------------------ % Low Pass zero: Fc x/C pole: Fc x/C % S -> C S/Fc gain: C/Fc gain: Fc/C % ---------------- ------------------------- ------------------------ % High Pass zero: Fc C/x pole: Fc C/x % S -> C Fc/S pole: 0 zero: 0 % gain: -x gain: -1/x % ---------------- ------------------------- ------------------------ % Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S^2+FhFl pole: 0 zero: 0 % S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C % S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ % Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl) % S -> C -------- gain: -x gain: -1/x % S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ % Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT) % 2 z-1 pole: -1 zero: -1 % S -> - --- gain: (2-xT)/T gain: (2-xT)/T % T z+1 % ---------------- ------------------------- ------------------------ % % where C is the cutoff frequency of the initial lowpass filter, Fc is % the edge of the target low/high pass filter and [Fl,Fh] are the edges % of the target band pass/stop filter. With abundant tedious algebra, % you can derive the above formulae yourself by substituting the % transform for S into H(S)=S-x for a zero at x or H(S)=1/(S-x) for a % pole at x, and converting the result into the form: % % H(S)=g prod(S-Xi)/prod(S-Xj) % % The transforms are from the references. The actual pole-zero-gain % changes I derived myself. % % Please note that a pole and a zero at the same place exactly cancel. % This is significant for High Pass, Band Pass and Band Stop filters % which create numerous extra poles and zeros, most of which cancel. % Those which do not cancel have a 'fill-in' effect, extending the % shorter of the sets to have the same number of as the longer of the % sets of poles and zeros (or at least split the difference in the case % of the band pass filter). There may be other opportunistic % cancellations but I will not check for them. % % Also note that any pole on the unit circle or beyond will result in % an unstable filter. Because of cancellation, this will only happen % if the number of poles is smaller than the number of zeros and the % filter is high pass or band pass. The analytic design methods all % yield more poles than zeros, so this will not be a problem. % % References: % % Proakis & Manolakis (1992). Digital Signal Processing. New York: % Macmillan Publishing Company. % Author: Paul Kienzle <[email protected]> % 2000-03-01 [email protected] % leave transformed Sg as a complex value since cheby2 blows up % otherwise (but only for odd-order low-pass filters). bilinear % will return Zg as real, so there is no visible change to the % user of the IIR filter design functions. % 2001-03-09 [email protected] % return real Sg; don't know what to do for imaginary filters function [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop) if (nargin ~= 5) usage('[Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)'); end; C = 1; p = length(Sp); z = length(Sz); if z > p || p == 0 error('sftrans: must have at least as many poles as zeros in s-plane'); end if length(W)==2 Fl = W(1); Fh = W(2); if stop % ---------------- ------------------------- ------------------------ % Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl) % S -> C -------- gain: -x gain: -1/x % S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ if (isempty(Sz)) Sg = Sg * real (1./ prod(-Sp)); elseif (isempty(Sp)) Sg = Sg * real(prod(-Sz)); else Sg = Sg * real(prod(-Sz)/prod(-Sp)); end b = (C*(Fh-Fl)/2)./Sp; Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; extend = [sqrt(-Fh*Fl), -sqrt(-Fh*Fl)]; if isempty(Sz) Sz = [extend(1+rem([1:2*p],2))]; else b = (C*(Fh-Fl)/2)./Sz; Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; if (p > z) Sz = [Sz, extend(1+rem([1:2*(p-z)],2))]; end end else % ---------------- ------------------------- ------------------------ % Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S^2+FhFl pole: 0 zero: 0 % S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C % S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ Sg = Sg * (C/(Fh-Fl))^(z-p); b = Sp*((Fh-Fl)/(2*C)); Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; if isempty(Sz) Sz = zeros(1,p); else b = Sz*((Fh-Fl)/(2*C)); Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; if (p>z) Sz = [Sz, zeros(1, (p-z))]; end end end else Fc = W; if stop % ---------------- ------------------------- ------------------------ % High Pass zero: Fc C/x pole: Fc C/x % S -> C Fc/S pole: 0 zero: 0 % gain: -x gain: -1/x % ---------------- ------------------------- ------------------------ if (isempty(Sz)) Sg = Sg * real (1./ prod(-Sp)); elseif (isempty(Sp)) Sg = Sg * real(prod(-Sz)); else Sg = Sg * real(prod(-Sz)/prod(-Sp)); end Sp = C * Fc ./ Sp; if isempty(Sz) Sz = zeros(1,p); else Sz = [C * Fc ./ Sz]; if (p > z) Sz = [Sz, zeros(1,p-z)]; end end else % ---------------- ------------------------- ------------------------ % Low Pass zero: Fc x/C pole: Fc x/C % S -> C S/Fc gain: C/Fc gain: Fc/C % ---------------- ------------------------- ------------------------ Sg = Sg * (C/Fc)^(z-p); Sp = Fc * Sp / C; Sz = Fc * Sz / C; end end
github
philippboehmsturm/antx-master
filtfilt.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/filtfilt.m
3,297
iso_8859_1
d01a26a827bc3379f05bbc57f46ac0a9
% Copyright (C) 1999 Paul Kienzle % Copyright (C) 2007 Francesco Potortì % Copyright (C) 2008 Luca Citi % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: y = filtfilt(b, a, x) % % Forward and reverse filter the signal. This corrects for phase % distortion introduced by a one-pass filter, though it does square the % magnitude response in the process. That's the theory at least. In % practice the phase correction is not perfect, and magnitude response % is distorted, particularly in the stop band. %% % Example % [b, a]=butter(3, 0.1); % 10 Hz low-pass filter % t = 0:0.01:1.0; % 1 second sample % x=sin(2*pi*t*2.3)+0.25*randn(size(t)); % 2.3 Hz sinusoid+noise % y = filtfilt(b,a,x); z = filter(b,a,x); % apply filter % plot(t,x,';data;',t,y,';filtfilt;',t,z,';filter;') % Changelog: % 2000 02 [email protected] % - pad with zeros to load up the state vector on filter reverse. % - add example % 2007 12 [email protected] % - use filtic to compute initial and final states % - work for multiple columns as well % 2008 12 [email protected] % - fixed instability issues with IIR filters and noisy inputs % - initial states computed according to Likhterov & Kopeika, 2003 % - use of a "reflection method" to reduce end effects % - added some basic tests % TODO: (pkienzle) My version seems to have similar quality to matlab, % but both are pretty bad. They do remove gross lag errors, though. function y = filtfilt(b, a, x) if (nargin ~= 3) usage('y=filtfilt(b,a,x)'); end rotate = (size(x, 1)==1); if rotate % a row vector x = x(:); % make it a column vector end lx = size(x,1); a = a(:).'; b = b(:).'; lb = length(b); la = length(a); n = max(lb, la); lrefl = 3 * (n - 1); if la < n, a(n) = 0; end if lb < n, b(n) = 0; end % Compute a the initial state taking inspiration from % Likhterov & Kopeika, 2003. "Hardware-efficient technique for % minimizing startup transients in Direct Form II digital filters" kdc = sum(b) / sum(a); if (abs(kdc) < inf) % neither NaN nor +/- Inf si = fliplr(cumsum(fliplr(b - kdc * a))); else si = zeros(size(a)); % fall back to zero initialization end si(1) = []; y = zeros(size(x)); for c = 1:size(x, 2) % filter all columns, one by one v = [2*x(1,c)-x((lrefl+1):-1:2,c); x(:,c); 2*x(end,c)-x((end-1):-1:end-lrefl,c)]; % a column vector % Do forward and reverse filtering v = filter(b,a,v,si*v(1)); % forward filter v = flipud(filter(b,a,flipud(v),si*v(end))); % reverse filter y(:,c) = v((lrefl+1):(lx+lrefl)); end if (rotate) % x was a row vector y = rot90(y); % rotate it back end
github
philippboehmsturm/antx-master
nanstd.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/nanstd.m
2,445
utf_8
5bfd7c73ce6d67e3163bdc51d464b590
% nanstd() - std, not considering NaN values % % Usage: same as std() % Author: Arnaud Delorme, CNL / Salk Institute, Sept 2003 %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 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: nanstd.m 2885 2011-02-16 09:41:58Z roboos $ function out = nanstd(in, varargin) if nargin < 1 help nanstd; return; end if nargin == 1, flag = 0; end if nargin < 3, if size(in,1) ~= 1 dim = 1; elseif size(in,2) ~= 1 dim = 2; else dim = 3; end end if nargin == 2, flag = varargin{1}; end if nargin == 3, flag = varargin{1}; dim = varargin{2}; end if isempty(flag), flag = 0; end nans = find(isnan(in)); in(nans) = 0; nonnans = ones(size(in)); nonnans(nans) = 0; nonnans = sum(nonnans, dim); nononnans = find(nonnans==0); nonnans(nononnans) = 1; out = sqrt((sum(in.^2, dim)-sum(in, dim).^2./nonnans)./(nonnans-abs(flag-1))); out(nononnans) = NaN;
github
philippboehmsturm/antx-master
avw_img_write.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/avw_img_write.m
14,014
utf_8
a7cdce842fad1e63e84c6e80be83dbcd
function avw_img_write(avw, fileprefix, IMGorient, machine, verbose) % avw_img_write - write Analyze image files (*.img) % % avw_img_write(avw,fileprefix,[IMGorient],[machine],[verbose]) % % avw.img - a 3D matrix of image data (double precision). % avw.hdr - a struct with image data parameters. If % not empty, this function calls avw_hdr_write. % % fileprefix - a string, the filename without the .img % extension. If empty, may use avw.fileprefix % % IMGorient - optional int, force writing of specified % orientation, with values: % % [], if empty, will use avw.hdr.hist.orient field % 0, transverse/axial unflipped (default, radiological) % 1, coronal unflipped % 2, sagittal unflipped % 3, transverse/axial flipped, left to right % 4, coronal flipped, anterior to posterior % 5, sagittal flipped, superior to inferior % % This function will set avw.hdr.hist.orient and write the % image data in a corresponding order. This function is % in alpha development, so it has not been exhaustively % tested (07/2003). See avw_img_read for more information % and documentation on the orientation option. % Orientations 3-5 are NOT recommended! They are part % of the Analyze format, but only used in Analyze % for faster raster graphics during movies. % % machine - a string, see machineformat in fread for details. % The default here is 'ieee-le'. % % verbose - the default is to output processing information to the command % window. If verbose = 0, this will not happen. % % Tip: to change the data type, set avw.hdr.dime.datatype to: % % 1 Binary ( 1 bit per voxel) % 2 Unsigned character ( 8 bits per voxel) % 4 Signed short ( 16 bits per voxel) % 8 Signed integer ( 32 bits per voxel) % 16 Floating point ( 32 bits per voxel) % 32 Complex, 2 floats ( 64 bits per voxel), not supported % 64 Double precision ( 64 bits per voxel) % 128 Red-Green-Blue (128 bits per voxel), not supported % % See also: avw_write, avw_hdr_write, % avw_read, avw_hdr_read, avw_img_read, avw_view % % $Revision: 2885 $ $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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %------------------------------------------------------------------------ % Check inputs if ~exist('avw','var'), doc avw_img_write; error('...no input avw.'); elseif isempty(avw), error('...empty input avw.'); elseif ~isfield(avw,'img'), error('...empty input avw.img'); end if ~exist('fileprefix','var'), if isfield(avw,'fileprefix'), if ~isempty(avw.fileprefix), fileprefix = avw.fileprefix; else fileprefix = []; end else fileprefix = []; end end if isempty(fileprefix), [fileprefix, pathname, filterindex] = uiputfile('*.hdr','Specify an output Analyze .hdr file'); if pathname, cd(pathname); end if ~fileprefix, doc avw_img_write; error('no output .hdr file specified'); end end if findstr('.hdr',fileprefix), % fprintf('AVW_IMG_WRITE: Removing .hdr extension from ''%s''\n',fileprefix); fileprefix = strrep(fileprefix,'.hdr',''); end if findstr('.img',fileprefix), % fprintf('AVW_IMG_WRITE: Removing .img extension from ''%s''\n',fileprefix); fileprefix = strrep(fileprefix,'.img',''); end 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 %------------------------------------------------------------------------ % MAIN if verbose, version = '[$Revision: 2885 $]'; fprintf('\nAVW_IMG_WRITE [v%s]\n',version(12:16)); tic; end fid = fopen(sprintf('%s.img',fileprefix),'w',machine); if fid < 0, msg = sprintf('Cannot open file %s.img\n',fileprefix); error(msg); else avw = write_image(fid,avw,fileprefix,IMGorient,machine,verbose); end if verbose, t=toc; fprintf('...done (%5.2f sec).\n\n',t); end % MUST write header after the image, to ensure any % orientation changes during image write are saved % in the header avw_hdr_write(avw,fileprefix,machine,verbose); return %----------------------------------------------------------------------------------- function avw = write_image(fid,avw,fileprefix,IMGorient,machine,verbose) % 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,2 floats (64 bits per voxel)/* % #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.datatype), case 1, avw.hdr.dime.bitpix = int16( 1); precision = 'bit1'; case 2, avw.hdr.dime.bitpix = int16( 8); precision = 'uchar'; case 4, avw.hdr.dime.bitpix = int16(16); precision = 'int16'; case 8, avw.hdr.dime.bitpix = int16(32); precision = 'int32'; case 16, avw.hdr.dime.bitpix = int16(32); precision = 'single'; case 32, error('...complex datatype not yet supported.\n'); case 64, avw.hdr.dime.bitpix = int16(64); precision = 'double'; case 128, error('...RGB datatype not yet supported.\n'); otherwise warning('...unknown datatype, using type 16 (32 bit floats).\n'); avw.hdr.dime.datatype = int16(16); avw.hdr.dime.bitpix = int16(32); precision = 'single'; end % write the .img file, depending on the .img orientation if verbose, fprintf('...writing %s precision Analyze image (%s).\n',precision,machine); end fseek(fid,0,'bof'); % The standard image orientation is axial unflipped if isempty(avw.hdr.hist.orient), msg = [ '...avw.hdr.hist.orient ~= 0.\n',... ' This function assumes the input avw.img is\n',... ' in axial unflipped orientation in memory. This is\n',... ' created by the avw_img_read function, which converts\n',... ' any input file image to axial unflipped in memory.\n']; warning(msg) end if isempty(IMGorient), if verbose, fprintf('...no IMGorient specified, using avw.hdr.hist.orient value.\n'); end IMGorient = double(avw.hdr.hist.orient); end if ~isfinite(IMGorient), if verbose, fprintf('...IMGorient is not finite!\n'); end IMGorient = 99; end switch IMGorient, case 0, % transverse/axial unflipped % 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('...writing axial unflipped\n'); end avw.hdr.hist.orient = uint8(0); SliceDim = double(avw.hdr.dime.dim(4)); % z RowDim = double(avw.hdr.dime.dim(3)); % y PixelDim = double(avw.hdr.dime.dim(2)); % x SliceSz = double(avw.hdr.dime.pixdim(4)); RowSz = double(avw.hdr.dime.pixdim(3)); PixelSz = double(avw.hdr.dime.pixdim(2)); x = 1:PixelDim; for z = 1:SliceDim, for y = 1:RowDim, fwrite(fid,avw.img(x,y,z),precision); end end case 1, % coronal unflipped % 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('...writing coronal unflipped\n'); end avw.hdr.hist.orient = uint8(1); SliceDim = double(avw.hdr.dime.dim(3)); % y RowDim = double(avw.hdr.dime.dim(4)); % z PixelDim = double(avw.hdr.dime.dim(2)); % x SliceSz = double(avw.hdr.dime.pixdim(3)); RowSz = double(avw.hdr.dime.pixdim(4)); PixelSz = double(avw.hdr.dime.pixdim(2)); x = 1:PixelDim; for y = 1:SliceDim, for z = 1:RowDim, fwrite(fid,avw.img(x,y,z),precision); end end case 2, % sagittal unflipped % 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('...writing sagittal unflipped\n'); end avw.hdr.hist.orient = uint8(2); SliceDim = double(avw.hdr.dime.dim(2)); % x RowDim = double(avw.hdr.dime.dim(4)); % z PixelDim = double(avw.hdr.dime.dim(3)); % y SliceSz = double(avw.hdr.dime.pixdim(2)); RowSz = double(avw.hdr.dime.pixdim(4)); PixelSz = double(avw.hdr.dime.pixdim(3)); y = 1:PixelDim; for x = 1:SliceDim, for z = 1:RowDim, fwrite(fid,avw.img(x,y,z),precision); end end case 3, % transverse/axial flipped % 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('...writing axial flipped (+Y from Anterior to Posterior)\n'); end avw.hdr.hist.orient = uint8(3); SliceDim = double(avw.hdr.dime.dim(4)); % z RowDim = double(avw.hdr.dime.dim(3)); % y PixelDim = double(avw.hdr.dime.dim(2)); % x SliceSz = double(avw.hdr.dime.pixdim(4)); RowSz = double(avw.hdr.dime.pixdim(3)); PixelSz = double(avw.hdr.dime.pixdim(2)); x = 1:PixelDim; for z = 1:SliceDim, for y = RowDim:-1:1, % flipped in Y fwrite(fid,avw.img(x,y,z),precision); end end case 4, % coronal flipped % 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 inferior to superior % Slices in 'y' axis - from patient anterior to posterior if verbose, fprintf('...writing coronal flipped (+Z from Superior to Inferior)\n'); end avw.hdr.hist.orient = uint8(4); SliceDim = double(avw.hdr.dime.dim(3)); % y RowDim = double(avw.hdr.dime.dim(4)); % z PixelDim = double(avw.hdr.dime.dim(2)); % x SliceSz = double(avw.hdr.dime.pixdim(3)); RowSz = double(avw.hdr.dime.pixdim(4)); PixelSz = double(avw.hdr.dime.pixdim(2)); x = 1:PixelDim; for y = 1:SliceDim, for z = RowDim:-1:1, fwrite(fid,avw.img(x,y,z),precision); end end case 5, % sagittal flipped % 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('...writing sagittal flipped (+Z from Superior to Inferior)\n'); end avw.hdr.hist.orient = uint8(5); SliceDim = double(avw.hdr.dime.dim(2)); % x RowDim = double(avw.hdr.dime.dim(4)); % z PixelDim = double(avw.hdr.dime.dim(3)); % y SliceSz = double(avw.hdr.dime.pixdim(2)); RowSz = double(avw.hdr.dime.pixdim(4)); PixelSz = double(avw.hdr.dime.pixdim(3)); y = 1:PixelDim; for x = 1:SliceDim, for z = RowDim:-1:1, % superior to inferior fwrite(fid,avw.img(x,y,z),precision); end end otherwise, % transverse/axial unflipped % 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('...unknown orientation specified, assuming default axial unflipped\n'); end avw.hdr.hist.orient = uint8(0); SliceDim = double(avw.hdr.dime.dim(4)); % z RowDim = double(avw.hdr.dime.dim(3)); % y PixelDim = double(avw.hdr.dime.dim(2)); % x SliceSz = double(avw.hdr.dime.pixdim(4)); RowSz = double(avw.hdr.dime.pixdim(3)); PixelSz = double(avw.hdr.dime.pixdim(2)); x = 1:PixelDim; for z = 1:SliceDim, for y = 1:RowDim, fwrite(fid,avw.img(x,y,z),precision); end end end fclose(fid); % Update the header avw.hdr.dime.dim(2:4) = int16([PixelDim,RowDim,SliceDim]); avw.hdr.dime.pixdim(2:4) = single([PixelSz,RowSz,SliceSz]); return
github
philippboehmsturm/antx-master
bilinear.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/bilinear.m
4,339
utf_8
17250db27826cad87fa3384823e1242f
% Copyright (C) 1999 Paul Kienzle % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T) % [Zb, Za] = bilinear(Sb, Sa, T) % % Transform a s-plane filter specification into a z-plane % specification. Filters can be specified in either zero-pole-gain or % transfer function form. The input form does not have to match the % output form. 1/T is the sampling frequency represented in the z plane. % % Note: this differs from the bilinear function in the signal processing % toolbox, which uses 1/T rather than T. % % Theory: Given a piecewise flat filter design, you can transform it % from the s-plane to the z-plane while maintaining the band edges by % means of the bilinear transform. This maps the left hand side of the % s-plane into the interior of the unit circle. The mapping is highly % non-linear, so you must design your filter with band edges in the % s-plane positioned at 2/T tan(w*T/2) so that they will be positioned % at w after the bilinear transform is complete. % % The following table summarizes the transformation: % % +---------------+-----------------------+----------------------+ % | Transform | Zero at x | Pole at x | % | H(S) | H(S) = S-x | H(S)=1/(S-x) | % +---------------+-----------------------+----------------------+ % | 2 z-1 | zero: (2+xT)/(2-xT) | zero: -1 | % | S -> - --- | pole: -1 | pole: (2+xT)/(2-xT) | % | T z+1 | gain: (2-xT)/T | gain: (2-xT)/T | % +---------------+-----------------------+----------------------+ % % With tedious algebra, you can derive the above formulae yourself by % substituting the transform for S into H(S)=S-x for a zero at x or % H(S)=1/(S-x) for a pole at x, and converting the result into the % form: % % H(Z)=g prod(Z-Xi)/prod(Z-Xj) % % Please note that a pole and a zero at the same place exactly cancel. % This is significant since the bilinear transform creates numerous % extra poles and zeros, most of which cancel. Those which do not % cancel have a 'fill-in' effect, extending the shorter of the sets to % have the same number of as the longer of the sets of poles and zeros % (or at least split the difference in the case of the band pass % filter). There may be other opportunistic cancellations but I will % not check for them. % % Also note that any pole on the unit circle or beyond will result in % an unstable filter. Because of cancellation, this will only happen % if the number of poles is smaller than the number of zeros. The % analytic design methods all yield more poles than zeros, so this will % not be a problem. % % References: % % Proakis & Manolakis (1992). Digital Signal Processing. New York: % Macmillan Publishing Company. % Author: Paul Kienzle <[email protected]> function [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T) if nargin==3 T = Sg; [Sz, Sp, Sg] = tf2zp(Sz, Sp); elseif nargin~=4 usage('[Zz, Zp, Zg]=bilinear(Sz,Sp,Sg,T) or [Zb, Za]=blinear(Sb,Sa,T)'); end; p = length(Sp); z = length(Sz); if z > p || p==0 error('bilinear: must have at least as many poles as zeros in s-plane'); end % ---------------- ------------------------- ------------------------ % Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT) % 2 z-1 pole: -1 zero: -1 % S -> - --- gain: (2-xT)/T gain: (2-xT)/T % T z+1 % ---------------- ------------------------- ------------------------ Zg = real(Sg * prod((2-Sz*T)/T) / prod((2-Sp*T)/T)); Zp = (2+Sp*T)./(2-Sp*T); if isempty(Sz) Zz = -ones(size(Zp)); else Zz = [(2+Sz*T)./(2-Sz*T)]; Zz = postpad(Zz, p, -1); end if nargout==2, [Zz, Zp] = zp2tf(Zz, Zp, Zg); end
github
philippboehmsturm/antx-master
select_channel_list.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/select_channel_list.m
5,910
utf_8
809c334eb560bace022f65305426b3a5
function [select] = select_channel_list(label, select, titlestr); % SELECT_CHANNEL_LIST presents a dialog for selecting multiple elements % from a cell array with strings, such as the labels of EEG channels. % The dialog presents two columns with an add and remove mechanism. % % select = select_channel_list(label, initial, titlestr) % % with % initial indices of channels that are initially selected % label cell array with channel labels (strings) % titlestr title for dialog (optional) % and % select indices of selected channels % % If the user presses cancel, the initial selection will be returned. % Copyright (C) 2003, 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: select_channel_list.m 2885 2011-02-16 09:41:58Z roboos $ if nargin<3 titlestr = 'Select'; end pos = get(0,'DefaultFigurePosition'); pos(3:4) = [290 300]; dlg = dialog('Name', titlestr, 'Position', pos); select = select(:)'; % ensure that it is a row array userdata.label = label; userdata.select = select; userdata.unselect = setdiff(1:length(label), select); set(dlg, 'userdata', userdata); uicontrol(dlg, 'style', 'text', 'position', [ 10 240+20 80 20], 'string', 'unselected'); uicontrol(dlg, 'style', 'text', 'position', [200 240+20 80 20], 'string', 'selected '); uicontrol(dlg, 'style', 'listbox', 'position', [ 10 40+20 80 200], 'min', 0, 'max', 2, 'tag', 'lbunsel') uicontrol(dlg, 'style', 'listbox', 'position', [200 40+20 80 200], 'min', 0, 'max', 2, 'tag', 'lbsel') uicontrol(dlg, 'style', 'pushbutton', 'position', [105 175+20 80 20], 'string', 'add all >' , 'callback', @label_addall); uicontrol(dlg, 'style', 'pushbutton', 'position', [105 145+20 80 20], 'string', 'add >' , 'callback', @label_add); uicontrol(dlg, 'style', 'pushbutton', 'position', [105 115+20 80 20], 'string', '< remove' , 'callback', @label_remove); uicontrol(dlg, 'style', 'pushbutton', 'position', [105 85+20 80 20], 'string', '< remove all', 'callback', @label_removeall); uicontrol(dlg, 'style', 'pushbutton', 'position', [ 55 10 80 20], 'string', 'Cancel', 'callback', 'close'); uicontrol(dlg, 'style', 'pushbutton', 'position', [155 10 80 20], 'string', 'OK', 'callback', 'uiresume'); label_redraw(dlg); % wait untill the dialog is closed or the user presses OK/Cancel uiwait(dlg); if ishandle(dlg) % the user pressed OK, return the selection from the dialog userdata = get(dlg, 'userdata'); select = userdata.select; close(dlg); return else % the user pressed Cancel or closed the dialog, return the initial selection return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_redraw(h); userdata = get(h, 'userdata'); set(findobj(h, 'tag', 'lbsel' ), 'string', userdata.label(userdata.select)); set(findobj(h, 'tag', 'lbunsel'), 'string', userdata.label(userdata.unselect)); % set the active element in the select listbox, based on the previous active element tmp = min(get(findobj(h, 'tag', 'lbsel'), 'value')); tmp = min(tmp, length(get(findobj(h, 'tag', 'lbsel'), 'string'))); if isempty(tmp) | tmp==0 tmp = 1; end set(findobj(h, 'tag', 'lbsel' ), 'value', tmp); % set the active element in the unselect listbox, based on the previous active element tmp = min(get(findobj(h, 'tag', 'lbunsel'), 'value')); tmp = min(tmp, length(get(findobj(h, 'tag', 'lbunsel'), 'string'))); if isempty(tmp) | tmp==0 tmp = 1; end set(findobj(h, 'tag', 'lbunsel' ), 'value', tmp); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_addall(h, eventdata, handles, varargin); h = get(h, 'parent'); userdata = get(h, 'userdata'); userdata.select = 1:length(userdata.label); userdata.unselect = []; set(findobj(h, 'tag', 'lbunsel' ), 'value', 1); set(h, 'userdata', userdata); label_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_removeall(h, eventdata, handles, varargin); h = get(h, 'parent'); userdata = get(h, 'userdata'); userdata.unselect = 1:length(userdata.label); userdata.select = []; set(findobj(h, 'tag', 'lbsel' ), 'value', 1); set(h, 'userdata', userdata); label_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_add(h, eventdata, handles, varargin); h = get(h, 'parent'); userdata = get(h, 'userdata'); if ~isempty(userdata.unselect) add = userdata.unselect(get(findobj(h, 'tag', 'lbunsel' ), 'value')); userdata.select = sort([userdata.select add]); userdata.unselect = sort(setdiff(userdata.unselect, add)); set(h, 'userdata', userdata); label_redraw(h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_remove(h, eventdata, handles, varargin); h = get(h, 'parent'); userdata = get(h, 'userdata'); if ~isempty(userdata.select) remove = userdata.select(get(findobj(h, 'tag', 'lbsel' ), 'value')); userdata.select = sort(setdiff(userdata.select, remove)); userdata.unselect = sort([userdata.unselect remove]); set(h, 'userdata', userdata); label_redraw(h); end
github
philippboehmsturm/antx-master
artifact_viewer.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/artifact_viewer.m
6,725
utf_8
291cb59d64c23a5d4b2eb22de3ac3896
function artifact_viewer(cfg, artcfg, zval, artval, zindx, inputdata); % ARTIFACT_VIEWER is a subfunction that reads a segment of data % (one channel only) and displays it together with the cummulated % z-value % Copyright (C) 2004-2006, Jan-Mathijs Schoffelen & 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: artifact_viewer.m 3323 2011-04-09 14:36:20Z crimic $ dat.cfg = cfg; dat.artcfg = artcfg; if nargin == 5 % no data is given dat.hdr = ft_read_header(cfg.headerfile); elseif nargin == 6 % data is given dat.hdr = ft_fetch_header(inputdata); % used name inputdata iso data, because data is already used later in this function dat.inputdata = inputdata; % to be able to get inputdata into h (by guidata) end dat.trlop = 1; dat.zval = zval; dat.artval = artval; dat.zindx = zindx; dat.stop = 0; dat.numtrl = size(cfg.trl,1); dat.trialok = zeros(1,dat.numtrl); for trlop=1:dat.numtrl dat.trialok(trlop) = ~any(artval{trlop}); end h = gcf; guidata(h,dat); uicontrol(gcf,'units','pixels','position',[5 5 40 18],'String','stop','Callback',@stop); uicontrol(gcf,'units','pixels','position',[50 5 25 18],'String','<','Callback',@prevtrial); uicontrol(gcf,'units','pixels','position',[75 5 25 18],'String','>','Callback',@nexttrial); uicontrol(gcf,'units','pixels','position',[105 5 25 18],'String','<<','Callback',@prev10trial); uicontrol(gcf,'units','pixels','position',[130 5 25 18],'String','>>','Callback',@next10trial); uicontrol(gcf,'units','pixels','position',[160 5 50 18],'String','<artfct','Callback',@prevartfct); uicontrol(gcf,'units','pixels','position',[210 5 50 18],'String','artfct>','Callback',@nextartfct); while ishandle(h), dat = guidata(h); if dat.stop == 0, read_and_plot(h); uiwait; else break end end if ishandle(h) close(h); end %------------ %subfunctions %------------ function read_and_plot(h) vlinecolor = [0 0 0]; dat = guidata(h); % make a local copy of the relevant variables trlop = dat.trlop; zval = dat.zval{trlop}; artval = dat.artval{trlop}; zindx = dat.zindx{trlop}; cfg = dat.cfg; artcfg = dat.artcfg; hdr = dat.hdr; trl = dat.artcfg.trl; trlpadsmp = round(artcfg.trlpadding*hdr.Fs); % determine the channel with the highest z-value [dum, indx] = max(zval); sgnind = zindx(indx); iscontinuous = 1; if isfield(dat, 'inputdata') data = ft_fetch_data(dat.inputdata, 'header', hdr, 'begsample', trl(trlop,1), 'endsample', trl(trlop,2), 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no')); else data = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1), 'endsample', trl(trlop,2), 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no')); end % data = preproc(data, channel, hdr.Fs, artfctdef, [], fltpadding, fltpadding); str = sprintf('trial %3d, channel %s', dat.trlop, hdr.label{sgnind}); fprintf('showing %s\n', str); % plot z-values in lower subplot subplot(2,1,2); cla hold on xval = trl(trlop,1):trl(trlop,2); if trlpadsmp sel = 1:trlpadsmp; h = plot(xval(sel), zval(sel)); set(h, 'color', [0.5 0.5 1]); % plot the trialpadding in another color sel = trlpadsmp:(length(data)-trlpadsmp); plot(xval(sel), zval(sel), 'b'); sel = (length(data)-trlpadsmp):length(data); h = plot(xval(sel), zval(sel)); set(h, 'color', [0.5 0.5 1]); % plot the trialpadding in another color vline(xval( 1)+trlpadsmp, 'color', vlinecolor); vline(xval(end)-trlpadsmp, 'color', vlinecolor); else plot(xval, zval, 'b'); end % draw a line at the threshold level hline(artcfg.cutoff, 'color', 'r', 'linestyle', ':'); % make the artefact part red zval(~artval) = nan; plot(xval, zval, 'r-'); hold off xlabel('samples'); ylabel('zscore'); % plot data of most aberrant channel in upper subplot subplot(2,1,1); cla hold on if trlpadsmp sel = 1:trlpadsmp; h = plot(xval(sel), data(sel)); set(h, 'color', [0.5 0.5 1]); % plot the trialpadding in another color sel = trlpadsmp:(length(data)-trlpadsmp); plot(xval(sel), data(sel), 'b'); sel = (length(data)-trlpadsmp):length(data); h = plot(xval(sel), data(sel)); set(h, 'color', [0.5 0.5 1]); % plot the trialpadding in another color vline(xval( 1)+trlpadsmp, 'color', vlinecolor); vline(xval(end)-trlpadsmp, 'color', vlinecolor); else plot(xval, data, 'b'); end data(~artval) = nan; plot(xval, data, 'r-'); hold off xlabel('samples'); ylabel('uV or Tesla'); title(str); function varargout = nexttrial(h, eventdata, handles, varargin) dat = guidata(h); if dat.trlop < dat.numtrl, dat.trlop = dat.trlop + 1; end; guidata(h,dat); uiresume; function varargout = next10trial(h, eventdata, handles, varargin) dat = guidata(h); if dat.trlop < dat.numtrl - 10, dat.trlop = dat.trlop + 10; else dat.trlop = dat.numtrl; end; guidata(h,dat); uiresume; function varargout = prevtrial(h, eventdata, handles, varargin) dat = guidata(h); if dat.trlop > 1, dat.trlop = dat.trlop - 1; else dat.trlop = 1; end; guidata(h,dat); uiresume; function varargout = prev10trial(h, eventdata, handles, varargin) dat = guidata(h); if dat.trlop > 10, dat.trlop = dat.trlop - 10; else dat.trlop = 1; end; guidata(h,dat); uiresume; function varargout = nextartfct(h, eventdata, handles, varargin) dat = guidata(h); artfctindx = find(dat.trialok == 0); sel = find(artfctindx > dat.trlop); if ~isempty(sel) dat.trlop = artfctindx(sel(1)); else dat.trlop = dat.trlop; end guidata(h,dat); uiresume; function varargout = prevartfct(h, eventdata, handles, varargin) dat = guidata(h); artfctindx = find(dat.trialok == 0); sel = find(artfctindx < dat.trlop); if ~isempty(sel) dat.trlop = artfctindx(sel(end)); else dat.trlop = dat.trlop; end guidata(h,dat); uiresume; function varargout = stop(h, eventdata, handles, varargin) dat = guidata(h); dat.stop = 1; guidata(h,dat); uiresume; function vsquare(x1, x2, c) abc = axis; y1 = abc(3); y2 = abc(4); x = [x1 x2 x2 x1 x1]; y = [y1 y1 y2 y2 y1]; z = [-1 -1 -1 -1 -1]; h = patch(x, y, z, c); set(h, 'edgecolor', c)
github
philippboehmsturm/antx-master
rejectvisual_summary.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/rejectvisual_summary.m
17,414
utf_8
2918f7fe9ab915b102683960eeabd968
function [chansel, trlsel, cfg] = rejectvisual_summary(cfg, data) % REJECTVISUAL_SUMMARY: subfunction for ft_rejectvisual % determine the initial selection of trials and channels nchan = length(data.label); ntrl = length(data.trial); cfg.channel = ft_channelselection(cfg.channel, data.label); trlsel = true(1,ntrl); chansel = false(1,nchan); chansel(match_str(data.label, cfg.channel)) = 1; % compute the sampling frequency from the first two timepoints fsample = 1/(data.time{1}(2) - data.time{1}(1)); % select the specified latency window from the data % here it is done BEFORE filtering and metric computation for i=1:ntrl begsample = nearest(data.time{i}, cfg.latency(1)); endsample = nearest(data.time{i}, cfg.latency(2)); data.time{i} = data.time{i}(begsample:endsample); data.trial{i} = data.trial{i}(:,begsample:endsample); end % compute the offset from the time axes offset = zeros(ntrl,1); for i=1:ntrl offset(i) = time2offset(data.time{i}, fsample); end % set up guidata info h = figure(); info = []; info.data = data; info.cfg = cfg; info.metric = cfg.metric; info.ntrl = ntrl; info.nchan = nchan; info.trlsel = trlsel; info.chansel = chansel; info.fsample = fsample; info.offset = offset; info.quit = 0; guidata(h,info); % set up display interactive = 1; info = guidata(h); % make the figure large enough to hold stuff set(h,'Position',[50 350 800 500]); % define three plots info.axes(1) = axes('position',[0.100 0.650 0.375 0.300]); % summary plot info.axes(2) = axes('position',[0.575 0.650 0.375 0.300]); % channels info.axes(3) = axes('position',[0.100 0.250 0.375 0.300]); % trials % callback function (for toggling trials/channels) is set later, so that % the user cannot try to toggle trials while nothing is present on the % plots % set up radio buttons for choosing metric g = uibuttongroup('Position',[0.525 0.275 0.375 0.250 ],'bordertype','none','backgroundcolor',get(h,'color')); r(1) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 7/7 0.40 0.15 ],'Style','radio','string','var','HandleVisibility','off'); r(2) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 6/7 0.40 0.15 ],'Style','radio','String','min','HandleVisibility','off'); r(3) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 5/7 0.40 0.15 ],'Style','Radio','String','max','HandleVisibility','off'); r(4) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 4/7 0.40 0.15 ],'Style','Radio','String','maxabs','HandleVisibility','off'); r(5) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 3/7 0.40 0.15 ],'Style','Radio','String','range','HandleVisibility','off'); r(6) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 2/7 0.40 0.15 ],'Style','Radio','String','kurtosis','HandleVisibility','off'); r(7) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 1/7 0.40 0.15 ],'Style','Radio','String','1/var','HandleVisibility','off'); r(8) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 0/7 0.40 0.15 ],'Style','Radio','String','zvalue','HandleVisibility','off'); % pre-select appropriate metric, if defined set(g,'SelectionChangeFcn',@change_metric); for i=1:length(r) if strcmp(get(r(i),'string'), cfg.metric) set(g,'SelectedObject',r(i)); end end % editboxes for manually specifying which channels/trials to turn off uicontrol(h,'Units','normalized','position',[0.64 0.44 0.14 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color'),'string','Toggle trial #:'); uicontrol(h,'Units','normalized','position',[0.64 0.40 0.12 0.05],'Style','edit','HorizontalAlignment','left','backgroundcolor',[1 1 1],'callback',@toggle_trials); uicontrol(h,'Units','normalized','position',[0.64 0.31 0.14 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color'),'string','Toggle channel:'); uicontrol(h,'Units','normalized','position',[0.64 0.27 0.12 0.05],'Style','edit','HorizontalAlignment','left','backgroundcolor',[1 1 1],'callback',@toggle_channels); %uicontrol(h,'Units','normalized','position',[0.65 0.34 0.20 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color'),'string','Plot trial #:'); %uicontrol(h,'Units','normalized','position',[0.65 0.30 0.15 0.05],'Style','edit','HorizontalAlignment','left','backgroundcolor',[1 1 1],'callback',@display_trial); info.badtrllbl = uicontrol(h,'Units','normalized','position',[0.795 0.44 0.195 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color'),'string',sprintf('Rejected trials: %i/%i',sum(info.trlsel==0),info.ntrl)); info.badtrltxt = uicontrol(h,'Units','normalized','position',[0.795 0.3975 0.23 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color')); info.badchanlbl = uicontrol(h,'Units','normalized','position',[0.795 0.31 0.195 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color'),'string',sprintf('Rejected channels: %i/%i',sum(info.chansel==0),info.nchan)); info.badchantxt = uicontrol(h,'Units','normalized','position',[0.795 0.2625 0.23 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color')); % instructions instructions = sprintf('Drag the mouse over the channels/trials you wish to reject.'); uicontrol(h,'Units','normalized','position',[0.625 0.50 0.35 0.065],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color'),'string',instructions,'FontWeight','bold','ForegroundColor','b'); % "show rejected" button % ui_tog = uicontrol(h,'Units','normalized','position',[0.55 0.200 0.25 0.05],'Style','checkbox','backgroundcolor',get(h,'color'),'string','Show rejected?','callback',@toggle_rejected); % if strcmp(cfg.viewmode, 'toggle') % set(ui_tog,'value',1); % end % logbox info.output_box = uicontrol(h,'Units','normalized','position',[0.00 0.00 1.00 0.15],'Style','edit','HorizontalAlignment','left','Max',3,'Min',1,'Enable','inactive','FontName',get(0,'FixedWidthFontName'),'FontSize',9,'ForegroundColor',[0 0 0],'BackgroundColor',[1 1 1]); % quit button uicontrol(h,'Units','normalized','position',[0.80 0.175 0.10 0.05],'string','quit','callback',@quit); guidata(h, info); % Compute initial metric... compute_metric(h); while interactive && ishandle(h) redraw(h); info = guidata(h); if info.quit == 0 uiwait(h); else chansel = info.chansel; trlsel = info.trlsel; cfg = info.cfg; delete(h); break; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function compute_metric(h) info = guidata(h); update_log(info.output_box,'Computing metric...'); ft_progress('init', info.cfg.feedback, 'computing metric'); level = zeros(info.nchan, info.ntrl); if strcmp(info.metric,'zvalue') % cellmean and cellstd (see ft_denoise_pca) would work instead of for-loops, % but they were too memory-intensive runsum=zeros(info.nchan, 1); runnum=0; for i=1:info.ntrl [dat] = preproc(info.data.trial{i}, info.data.label, info.fsample, info.cfg.preproc, info.offset(i)); dat(info.chansel==0,:) = nan; runsum=runsum+sum(dat,2); runnum=runnum+size(dat,2); end mval=runsum/runnum; runss=zeros(info.nchan,1); for i=1:info.ntrl [dat] = preproc(info.data.trial{i}, info.data.label, info.fsample, info.cfg.preproc, info.offset(i)); dat(info.chansel==0,:) = nan; dat=dat-repmat(mval,1,size(dat,2)); runss=runss+sum(dat.^2,2); end sd=sqrt(runss/runnum); end for i=1:info.ntrl ft_progress(i/info.ntrl, 'computing metric %d of %d\n', i, info.ntrl); [dat, label, time, info.cfg.preproc] = preproc(info.data.trial{i}, info.data.label, info.fsample, info.cfg.preproc, info.offset(i)); dat(info.chansel==0,:) = nan; switch info.metric case 'var' level(:,i) = std(dat, [], 2).^2; case 'min' level(:,i) = min(dat, [], 2); case 'max' level(:,i) = max(dat, [], 2); case 'maxabs' level(:,i) = max(abs(dat), [], 2); case 'range' level(:,i) = max(dat, [], 2) - min(dat, [], 2); case 'kurtosis' level(:,i) = kurtosis(dat, [], 2); case '1/var' level(:,i) = 1./(std(dat, [], 2).^2); case 'zvalue' level(:,i) = mean( ( dat-repmat(mval,1,size(dat,2)) )./repmat(sd,1,size(dat,2)) ,2); otherwise error('unsupported method'); end end ft_progress('close'); update_log(info.output_box,'Done.'); % if metric calculated with channels off, then turning that channel on % won't show anything. Because of this, keep track of which channels were % off when calculated, so know when to recalculate. info.metric_chansel = info.chansel; % % reinsert the data for the selected channels % dum = nan*zeros(info.nchan, info.ntrl); % dum(info.chansel,:) = level; % origlevel = dum; % clear dum % % store original levels for later % info.origlevel = origlevel; info.level = level; guidata(h,info); function redraw(h) info = guidata(h); % work with a copy of the data level = info.level; level(~info.chansel,:) = nan; level(:,~info.trlsel) = nan; [maxperchan maxpertrl maxperchan_all maxpertrl_all] = set_maxper(level, info.chansel, info.trlsel); % make the three figures if gcf~=h, figure(h); end %datacursormode on; set(h,'CurrentAxes',info.axes(1)) cla(info.axes(1)); % imagesc(level(chansel, trlsel)); imagesc(level); axis xy; % colorbar; title(info.cfg.method); ylabel('channel number'); xlabel('trial number'); set(h,'CurrentAxes',info.axes(2)) cla(info.axes(2)); set(info.axes(2),'ButtonDownFcn',@toggle_visual); plot(maxperchan(info.chansel==1), find(info.chansel==1), '.'); if strcmp(info.cfg.viewmode, 'toggle') && (sum(info.chansel==0) > 0) hold on; plot(maxperchan_all(info.chansel==0), find(info.chansel==0), 'o'); hold off; end abc = axis; axis([abc(1:2) 1 info.nchan]); set(info.axes(2),'ButtonDownFcn',@toggle_visual); % needs to be here; call to axis resets this property ylabel('channel number'); set(h,'CurrentAxes',info.axes(3)) cla(info.axes(3)); plot(find(info.trlsel==1), maxpertrl(info.trlsel==1), '.'); if strcmp(info.cfg.viewmode, 'toggle') && (sum(info.trlsel==0) > 0) hold on; plot(find(info.trlsel==0), maxpertrl_all(info.trlsel==0), 'o'); hold off; end abc = axis; axis([1 info.ntrl abc(3:4)]); set(info.axes(3),'ButtonDownFcn',@toggle_visual); % needs to be here; call to axis resets this property xlabel('trial number'); % put rejected trials/channels in their respective edit boxes set(info.badchanlbl,'string',sprintf('Rejected channels: %i/%i',sum(info.chansel==0),info.nchan)); set(info.badtrllbl, 'string',sprintf('Rejected trials: %i/%i',sum(info.trlsel==0), info.ntrl)); if ~isempty(find(info.trlsel==0, 1)) set(info.badtrltxt,'String',num2str(find(info.trlsel==0)),'FontAngle','normal'); else set(info.badtrltxt,'String','No trials rejected','FontAngle','italic'); end if ~isempty(find(info.chansel==0, 1)) if isfield(info.data,'label') chanlabels = info.data.label(info.chansel==0); badchantxt = chanlabels{1}; if length(chanlabels) > 1 for n=2:length(chanlabels) badchantxt = [badchantxt ', ' chanlabels{n}]; end end set(info.badchantxt,'String',badchantxt,'FontAngle','normal'); else set(info.badtrltxt,'String',num2str(find(info.chansel==0)),'FontAngle','normal'); end else set(info.badchantxt,'String','No channels rejected','FontAngle','italic'); end function toggle_trials(h, eventdata) info = guidata(h); % extract trials from string rawtrls = get(h,'string'); if ~isempty(rawtrls) spltrls = regexp(rawtrls,'\s+','split'); trls = []; for n = 1:length(spltrls) trls(n) = str2num(cell2mat(spltrls(n))); end else update_log(info.output_box,sprintf('Please enter one or more trials')); uiresume; return; end toggle = trls; try info.trlsel(toggle) = ~info.trlsel(toggle); catch update_log(info.output_box,sprintf('ERROR: Trial value too large!')); end guidata(h, info); uiresume; % process input from the "toggle channels" textbox function toggle_channels(h, eventdata) info = guidata(h); rawchans = get(h,'string'); if ~isempty(rawchans) splchans = regexp(rawchans,'\s+','split'); chans = zeros(1,length(splchans)); % determine whether identifying channels via number or label [~,~,~,procchans] = regexp(rawchans,'([A-Za-z]+|[0-9]{4,})'); if isempty(procchans) % if using channel numbers for n = 1:length(splchans) chans(n) = str2num(splchans{n}); end else % if using channel labels for n = 1:length(splchans) try chans(n) = find(ismember(info.data.label,splchans(n))); catch update_log(info.output_box,sprintf('ERROR: Please ensure the channel name is correct (case-sensitive)!')); uiresume; return; end end end else update_log(info.output_box,sprintf('Please enter one or more channels')); uiresume; return; end toggle = chans; try info.chansel(toggle) = ~info.chansel(toggle); catch update_log(info.output_box,sprintf('ERROR: Channel value too large!')); end guidata(h, info); % if levels data from channel being toggled was calculated from another % metric, recalculate the metric if info.metric_chansel(toggle) == 0 compute_metric(h) end uiresume; function toggle_visual(h, eventdata) % copied from select2d, without waitforbuttonpress command point1 = get(gca,'CurrentPoint'); % button down detected finalRect = rbbox; % return figure units point2 = get(gca,'CurrentPoint'); % button up detected point1 = point1(1,1:2); % extract x and y point2 = point2(1,1:2); x = sort([point1(1) point2(1)]); y = sort([point1(2) point2(2)]); g = get(gca,'Parent'); info = guidata(g); [maxperchan maxpertrl] = set_maxper(info.level, info.chansel, info.trlsel); % toggle channels if gca == info.axes(2) % if strcmp(info.cfg.viewmode, 'toggle') chanlabels = 1:info.nchan; % else % perchan = max(info.level,[],2); % maxperchan = perchan(info.chansel==1); % chanlabels = find(info.chansel==1); % end toggle = find( ... chanlabels >= y(1) & ... chanlabels <= y(2) & ... maxperchan(:)' >= x(1) & ... maxperchan(:)' <= x(2)); info.chansel(toggle) = 0; % if levels data from channel being toggled was calculated from another % metric, recalculate the metric if info.metric_chansel(toggle) == 0 compute_metric(h) end % toggle trials elseif gca == info.axes(3) % if strcmp(info.cfg.viewmode, 'toggle') trllabels = 1:info.ntrl; % else % pertrl = max(info.level,[],1); % maxpertrl = pertrl(info.trlsel==1); % trllabels = find(info.trlsel==1); % end toggle = find( ... trllabels >= x(1) & ... trllabels <= x(2) & ... maxpertrl(:)' >= y(1) & ... maxpertrl(:)' <= y(2)); info.trlsel(toggle) = 0; end guidata(h, info); uiresume; % function display_trial(h, eventdata) % info = guidata(h); % rawtrls = get(h,'string'); % if ~isempty(rawtrls) % spltrls = regexp(rawtrls,' ','split'); % trls = []; % for n = 1:length(spltrls) % trls(n) = str2num(cell2mat(spltrls(n))); % end % else % update_log(info.output_box,sprintf('Please enter one or more trials')); % uiresume; % return; % end % if all(trls==0) % % use visual selection % update_log(info.output_box,sprintf('make visual selection of trials to be plotted seperately...')); % [x, y] = select2d; % maxpertrl = max(info.origlevel,[],1); % toggle = find(1:ntrl>=x(1) & ... % 1:ntrl<=x(2) & ... % maxpertrl(:)'>=y(1) & ... % maxpertrl(:)'<=y(2)); % else % toggle = trls; % end % for i=1:length(trls) % figure % % the data being displayed here is NOT filtered % %plot(data.time{toggle(i)}, data.trial{toggle(i)}(chansel,:)); % tmp = info.data.trial{toggle(i)}(info.chansel,:); % tmp = tmp - repmat(mean(tmp,2), [1 size(tmp,2)]); % plot(info.data.time{toggle(i)}, tmp); % title(sprintf('trial %d', toggle(i))); % end function quit(h, eventdata) info = guidata(h); info.quit = 1; guidata(h, info); uiresume; function change_metric(h, eventdata) info = guidata(h); info.metric = get(eventdata.NewValue, 'string'); guidata(h, info); compute_metric(h); uiresume; function toggle_rejected(h, eventdata) info = guidata(h); toggle = get(h,'value'); if toggle == 0 info.cfg.viewmode = 'remove'; else info.cfg.viewmode = 'toggle'; end guidata(h, info); uiresume; function update_log(h, new_text) new_text = [datestr(now,13) '# ' new_text]; curr_text = get(h, 'string'); size_curr_text = size(curr_text,2); size_new_text = size(new_text,2); if size_curr_text > size_new_text new_text = [new_text blanks(size_curr_text-size_new_text)]; else curr_text = [curr_text repmat(blanks(size_new_text-size_curr_text), size(curr_text,1), 1)]; end set(h, 'String', [new_text; curr_text]); drawnow; function [maxperchan,maxpertrl,varargout] = set_maxper(level,chansel,trlsel) level_all = level; % determine the maximum value level(~chansel,:) = nan; level(:,~trlsel) = nan; maxperchan = max(level,[],2); maxpertrl = max(level,[],1); maxperchan_all = max(level_all,[],2); maxpertrl_all = max(level_all,[],1); varargout(1) = {maxperchan_all}; varargout(2) = {maxpertrl_all};
github
philippboehmsturm/antx-master
warning_once.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/warning_once.m
3,060
utf_8
f046009e4f6ffe5745af9c5e527614e8
function [ws warned] = warning_once(varargin) % % Use as % warning_once(string) % or % warning_once(string, timeout) % or % warning_once(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. The default timeout value is 60 seconds. % % Can be used instead of the MATLAB built-in function WARNING, thus as % s = warning_once(...) % or % warning_once(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. % In other words, warning_once accepts as an input the same structure it % returns as an output. This returns or restores the states of warnings to % their previous values. % % Can also be used as % [s w] = warning_once(...) % where w is a boolean that indicates whether a warning as been % thrown or not. persistent stopwatch previous if nargin < 1 error('You need to specify at least a warning message'); end warned = false; if isstruct(varargin{1}) warning(varargin{1}); return; end if nargin==3 msgid = varargin{1}; msgstr = varargin{2}; timeout = varargin{3}; elseif nargin==2 msgstr= ''; % this becomes irrelevant msgid = varargin{1}; % this becomes the real msgstr timeout = varargin{2}; elseif nargin==1 msgstr= ''; % this becomes irrelevant msgid = varargin{1}; % this becomes the real msgstr timeout = 60; % default timeout in seconds end if isempty(timeout) error('Timeout ill-specified'); end if isempty(stopwatch) stopwatch = tic; end if isempty(previous) previous = struct; end now = toc(stopwatch); % measure time since first function call fname = fixname([msgid '_' msgstr]); % make a nice string that is allowed as structure fieldname, copy the subfunction from ft_hastoolbox fname = decomma(fname); if length(fname) > 63 % MATLAB max name fname = fname(1:63); end if isfield(previous, fname) && now>previous.(fname).timeout % it has timed out, give the warning again ws = warning(msgid, msgstr); previous.(fname).timeout = now+timeout; previous.(fname).ws = ws; warned = true; elseif ~isfield(previous, fname) % the warning has not been issued before ws = warning(msgid, msgstr); previous.(fname).timeout = now+timeout; previous.(fname).ws = ws; warned = true; else % the warning has been issued before, but has not timed out yet ws = previous.(fname).ws; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out = fixname(toolbox) out = lower(toolbox); out(out=='-') = '_'; % fix dashes out(out==' ') = '_'; % fix spaces out(out=='/') = '_'; % fix forward slashes out(out=='\') = '_'; % fix backward slashes while(out(1) == '_'), out = out(2:end); end; % remove preceding underscore while(out(end) == '_'), out = out(1:end-1); end; % remove subsequent underscore end function nameout = decomma(name) nameout = name; indx = findstr(name,','); nameout(indx)=[]; end
github
philippboehmsturm/antx-master
rejectvisual_channel.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/rejectvisual_channel.m
10,295
utf_8
527466de7509f457ae5f6c892713f235
function [chansel, trlsel, cfg] = rejectvisual_channel(cfg, data); % SUBFUNCTION for rejectvisual % 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: rejectvisual_channel.m 3771 2011-07-04 13:38:23Z eelspa $ % determine the initial selection of trials and channels nchan = length(data.label); ntrl = length(data.trial); cfg.channel = ft_channelselection(cfg.channel, data.label); trlsel = logical(ones(1,ntrl)); chansel = logical(zeros(1,nchan)); chansel(match_str(data.label, cfg.channel)) = 1; % compute the sampling frequency from the first two timepoints fsample = 1/(data.time{1}(2) - data.time{1}(1)); % compute the offset from the time axes offset = zeros(ntrl,1); for i=1:ntrl offset(i) = time2offset(data.time{i}, fsample); end ft_progress('init', cfg.feedback, 'filtering data'); for i=1:ntrl ft_progress(i/ntrl, 'filtering data in trial %d of %d\n', i, ntrl); [data.trial{i}, label, time, cfg.preproc] = preproc(data.trial{i}, data.label, fsample, cfg.preproc, offset(i)); end ft_progress('close'); % select the specified latency window from the data % this is done AFTER the filtering to prevent edge artifacts for i=1:ntrl begsample = nearest(data.time{i}, cfg.latency(1)); endsample = nearest(data.time{i}, cfg.latency(2)); data.time{i} = data.time{i}(begsample:endsample); data.trial{i} = data.trial{i}(:,begsample:endsample); end h = figure; axis([0 1 0 1]); axis off % the info structure will be attached to the figure % and passed around between the callback functions if strcmp(cfg.plotlayout,'1col') % hidden config option for plotting trials differently info = []; info.ncols = 1; info.nrows = ntrl; info.trlop = 1; info.chanlop = 1; info.lchanlop= 0; info.quit = 0; info.ntrl = ntrl; info.nchan = nchan; info.data = data; info.cfg = cfg; info.offset = offset; info.chansel = chansel; info.trlsel = trlsel; % determine the position of each subplot within the axis for row=1:info.nrows for col=1:info.ncols indx = (row-1)*info.ncols + col; if indx>info.ntrl continue end info.x(indx) = (col-0.9)/info.ncols; info.y(indx) = 1 - (row-0.45)/(info.nrows+1); info.label{indx} = sprintf('trial %03d', indx); end end elseif strcmp(cfg.plotlayout,'square') info = []; info.ncols = ceil(sqrt(ntrl)); info.nrows = ceil(sqrt(ntrl)); info.trlop = 1; info.chanlop = 1; info.lchanlop= 0; info.quit = 0; info.ntrl = ntrl; info.nchan = nchan; info.data = data; info.cfg = cfg; info.offset = offset; info.chansel = chansel; info.trlsel = trlsel; % determine the position of each subplot within the axis for row=1:info.nrows for col=1:info.ncols indx = (row-1)*info.ncols + col; if indx>info.ntrl continue end info.x(indx) = (col-0.9)/info.ncols; info.y(indx) = 1 - (row-0.45)/(info.nrows+1); info.label{indx} = sprintf('trial %03d', indx); end end end info.ui.quit = uicontrol(h,'units','pixels','position',[ 5 5 40 18],'String','quit','Callback',@stop); info.ui.prev = uicontrol(h,'units','pixels','position',[ 50 5 25 18],'String','<','Callback',@prev); info.ui.next = uicontrol(h,'units','pixels','position',[ 75 5 25 18],'String','>','Callback',@next); info.ui.prev10 = uicontrol(h,'units','pixels','position',[105 5 25 18],'String','<<','Callback',@prev10); info.ui.next10 = uicontrol(h,'units','pixels','position',[130 5 25 18],'String','>>','Callback',@next10); info.ui.bad = uicontrol(h,'units','pixels','position',[160 5 50 18],'String','bad','Callback',@markbad); info.ui.good = uicontrol(h,'units','pixels','position',[210 5 50 18],'String','good','Callback',@markgood); info.ui.badnext = uicontrol(h,'units','pixels','position',[270 5 50 18],'String','bad>','Callback',@markbad_next); info.ui.goodnext = uicontrol(h,'units','pixels','position',[320 5 50 18],'String','good>','Callback',@markgood_next); set(gcf, 'WindowButtonUpFcn', @button); set(gcf, 'KeyPressFcn', @key); guidata(h,info); interactive = 1; while interactive && ishandle(h) redraw(h); info = guidata(h); if info.quit == 0, uiwait; else chansel = info.chansel; trlsel = info.trlsel; delete(h); break end end % while interactive %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function varargout = markbad_next(varargin) markbad(varargin{:}); next(varargin{:}); function varargout = markgood_next(varargin) markgood(varargin{:}); next(varargin{:}); function varargout = next(h, eventdata, handles, varargin) info = guidata(h); info.lchanlop = info.chanlop; if info.chanlop < info.nchan, info.chanlop = info.chanlop + 1; end; guidata(h,info); uiresume; function varargout = prev(h, eventdata, handles, varargin) info = guidata(h); info.lchanlop = info.chanlop; if info.chanlop > 1, info.chanlop = info.chanlop - 1; end; guidata(h,info); uiresume; function varargout = next10(h, eventdata, handles, varargin) info = guidata(h); info.lchanlop = info.chanlop; if info.chanlop < info.nchan - 10, info.chanlop = info.chanlop + 10; else info.chanlop = info.nchan; end; guidata(h,info); uiresume; function varargout = prev10(h, eventdata, handles, varargin) info = guidata(h); info.lchanlop = info.chanlop; if info.chanlop > 10, info.chanlop = info.chanlop - 10; else info.chanlop = 1; end; guidata(h,info); uiresume; function varargout = markgood(h, eventdata, handles, varargin) info = guidata(h); info.chansel(info.chanlop) = 1; fprintf(description_channel(info)); title(description_channel(info)); guidata(h,info); % uiresume; function varargout = markbad(h, eventdata, handles, varargin) info = guidata(h); info.chansel(info.chanlop) = 0; fprintf(description_channel(info)); title(description_channel(info)); guidata(h,info); % uiresume; function varargout = key(h, eventdata, handles, varargin) info = guidata(h); switch lower(eventdata.Key) case 'rightarrow' if info.chanlop ~= info.nchan next(h); else fprintf('at last channel\n'); end case 'leftarrow' if info.chanlop ~= 1 prev(h); else fprintf('at last channel\n'); end case 'g' markgood(h); case 'b' markbad(h); case 'q' stop(h); otherwise fprintf('unknown key pressed\n'); end function varargout = button(h, eventdata, handles, varargin) pos = get(gca, 'CurrentPoint'); x = pos(1,1); y = pos(1,2); info = guidata(h); dx = info.x - x; dy = info.y - y; dd = sqrt(dx.^2 + dy.^2); [d, i] = min(dd); if d<0.5/max(info.nrows, info.ncols) && i<=info.ntrl info.trlsel(i) = ~info.trlsel(i); % toggle info.trlop = i; fprintf(description_trial(info)); guidata(h,info); uiresume; else fprintf('button clicked\n'); return end function varargout = stop(h, eventdata, handles, varargin) info = guidata(h); info.quit = 1; guidata(h,info); uiresume; function str = description_channel(info); if info.chansel(info.chanlop) str = sprintf('channel %s marked as GOOD\n', info.data.label{info.chanlop}); else str = sprintf('channel %s marked as BAD\n', info.data.label{info.chanlop}); end function str = description_trial(info); if info.trlsel(info.trlop) str = sprintf('trial %d marked as GOOD\n', info.trlop); else str = sprintf('trial %d marked as BAD\n', info.trlop); end function redraw(h) if ~ishandle(h) return end info = guidata(h); fprintf(description_channel(info)); cla; title(''); drawnow hold on % determine the maximum value for this channel over all trials amax = -inf; tmin = inf; tmax = -inf; for trlindx=find(info.trlsel) tmin = min(info.data.time{trlindx}(1) , tmin); tmax = max(info.data.time{trlindx}(end), tmax); amax = max(max(abs(info.data.trial{trlindx}(info.chanlop,:))), amax); end if ~isempty(info.cfg.alim) % use fixed amplitude limits for the amplitude scaling amax = info.cfg.alim; end for row=1:info.nrows for col=1:info.ncols trlindx = (row-1)*info.ncols + col; if trlindx>info.ntrl || ~info.trlsel(trlindx) continue end % scale the time values between 0.1 and 0.9 time = info.data.time{trlindx}; time = 0.1 + 0.8*(time-tmin)/(tmax-tmin); % scale the amplitude values between -0.5 and 0.5, offset should not be removed dat = info.data.trial{trlindx}(info.chanlop,:); dat = dat ./ (2*amax); % scale the time values for this subplot tim = (col-1)/info.ncols + time/info.ncols; % scale the amplitude values for this subplot amp = dat./info.nrows + 1 - row/(info.nrows+1); plot(tim, amp, 'k') end end % enable or disable buttons as appropriate if info.chanlop == 1 set(info.ui.prev, 'Enable', 'off'); set(info.ui.prev10, 'Enable', 'off'); else set(info.ui.prev, 'Enable', 'on'); set(info.ui.prev10, 'Enable', 'on'); end if info.chanlop == info.nchan set(info.ui.next, 'Enable', 'off'); set(info.ui.next10, 'Enable', 'off'); else set(info.ui.next, 'Enable', 'on'); set(info.ui.next10, 'Enable', 'on'); end if info.lchanlop == info.chanlop && info.chanlop == info.nchan set(info.ui.badnext,'Enable', 'off'); set(info.ui.goodnext,'Enable', 'off'); else set(info.ui.badnext,'Enable', 'on'); set(info.ui.goodnext,'Enable', 'on'); end text(info.x, info.y, info.label); title(description_channel(info)); hold off
github
philippboehmsturm/antx-master
triangulate_seg.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/triangulate_seg.m
2,957
utf_8
f0ab0107b15b5d5dfd2c08dee874cb1a
function [pnt, tri] = triangulate_seg(seg, npnt, ori); % TRIANGULATE_SEG constructs a triangulation of the outer surface of a % segmented volume. It starts at the center of the volume and projects the % vertices of an evenly triangulated sphere onto the outer surface. The % resulting surface is star-shaped from the center of the volume. % % Use as % [pnt, tri] = triangulate_seg(seg, npnt) % % See also KSPHERE % 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: triangulate_seg.m 952 2010-04-21 18:29:51Z roboos $ seg = (seg~=0); dim = size(seg); len = ceil(sqrt(sum(dim.^2))/2); if nargin<3 ori(1) = dim(1)/2; ori(2) = dim(2)/2; ori(3) = dim(3)/2; end % start with a unit sphere with evenly distributed vertices [pnt, tri] = ksphere(npnt); for i=1:npnt % construct a sampled line from the center of the volume outward into the direction of the vertex lin = (0:0.5:len)' * pnt(i,:); lin(:,1) = lin(:,1) + ori(1); lin(:,2) = lin(:,2) + ori(2); lin(:,3) = lin(:,3) + ori(3); % round the sampled line towards the nearest voxel indices, which allows % a quick nearest-neighbour interpolation/lookup lin = round(lin); % exclude indices that do not ly within the volume sel = lin(:,1)<1 | lin(:,1)>dim(1) | ... lin(:,2)<1 | lin(:,2)>dim(2) | ... lin(:,3)<1 | lin(:,3)>dim(3); lin = lin(~sel,:); sel = sub2ind(dim, lin(:,1), lin(:,2), lin(:,3)); % interpolate the segmented volume along the sampled line int = seg(sel); % find the last sample along the line that is part of the segmentation try % for matlab 7 and higher sel = find(int, 1, 'last'); catch % for older matlab versions sel = find(int); sel = sel(end); end % this is a problem if sel is empty. If so, use the edge of the volume if ~isempty(sel), pnt(i,:) = lin(sel,:); else pnt(i,:) = lin(end,:); end end % undo the shift of the origin from where the projection is done % pnt(:,1) = pnt(:,1) - ori(1); % pnt(:,2) = pnt(:,2) - ori(2); % pnt(:,3) = pnt(:,3) - ori(3); % fast unconditional re-implementation of the standard Matlab function function [s] = sub2ind(dim, i, j, k) s = i + (j-1)*dim(1) + (k-1)*dim(1)*dim(2);
github
philippboehmsturm/antx-master
prepare_mesh_manual.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/prepare_mesh_manual.m
29,475
utf_8
92ba87f74299ab16b25a279092863d83
function bnd = prepare_mesh_manual(cfg, mri) % PREPARE_MESH_MANUAL is called by PREPARE_MESH and opens a GUI to manually % select points/polygons in an mri dataset. % % It allows: % Visualization of 3d data in 3 different projections % Adjustment of brightness for every slice % Storage of the data points in an external .mat file % Retrieval of previously saved data points % Slice fast scrolling with keyboard arrows % Polygons or points selection/deselection % % See also PREPARE_MESH_SEGMENTATION, PREPARE_MESH_HEADSHAPE % Copyrights (C) 2009, Cristiano Micheli & 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: prepare_mesh_manual.m 1431 2010-07-20 07:47:55Z roboos $ % FIXME: control slice's cmap referred to abs values % FIXME: clean structure slicedata % FIXME: check function assign3dpoints global obj bnd.pnt = []; bnd.tri = []; hasheadshape = isfield(cfg, 'headshape'); hasbnd = isfield(cfg, 'bnd'); % FIXME why is this in cfg? hasmri = nargin>1; % check the consistency of the input arguments if hasheadshape && hasbnd error('you should not specify cfg.headshape and cfg.bnd simultaneously'); end % check the consistency of the input arguments if ~hasmri % FIXME give a warning or so? mri.anatomy = []; mri.transform = eye(4); else % ensure that it is double precision mri.anatomy = double(mri.anatomy); end if hasheadshape if ~isempty(cfg.headshape) % 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) % read the headshape from file headshape = read_headshape(cfg.headshape); else headshape = []; end if ~isfield(headshape, 'tri') for i=1:length(headshape) % generate a closed triangulation from the surface points headshape(i).pnt = unique(headshape(i).pnt, 'rows'); headshape(i).tri = projecttri(headshape(i).pnt); end end % start with the headshape bnd = headshape; end elseif hasbnd if ~isempty(cfg.bnd) % start with the prespecified boundaries bnd = cfg.bnd; end else % start with an empty boundary if not specified bnd.pnt = []; bnd.tri = []; end % creating the GUI fig = figure; % initialize some values slicedata = []; points = bnd.pnt; axs = floor(size(mri.anatomy,1)/2); % initialize properties set(fig, 'KeyPressFcn',@keypress); set(fig, 'CloseRequestFcn', @cb_close); setappdata(fig,'data',mri.anatomy); setappdata(fig,'prop',{1,axs,0,[]}); setappdata(fig,'slicedata',slicedata); setappdata(fig,'points',points); setappdata(fig,'box',[]); % add GUI elements cb_creategui(gca); cb_redraw(gca); waitfor(fig); % close sequence global pnt try tmp = pnt; clear global pnt pnt = tmp; clear tmp [tri] = projecttri(pnt); bnd.pnt = pnt; bnd.tri = tri; catch bnd.pnt = []; bnd.tri = []; end function cb_redraw(hObject, eventdata, handles); fig = get(hObject, 'parent'); prop = getappdata(fig,'prop'); data = getappdata(fig,'data'); slicedata = getappdata(fig,'slicedata'); points = getappdata(fig,'points'); % draw image try cla % i,j,k axes if (prop{1}==1) %jk imh=imagesc(squeeze(data(prop{2},:,:))); xlabel('k'); ylabel('j'); colormap bone elseif (prop{1}==2) %ik imh=imagesc(squeeze(data(:,prop{2},:))); xlabel('k'); ylabel('i'); colormap bone elseif (prop{1}==3) %ij imh=imagesc(squeeze(data(:,:,prop{2}))); xlabel('j'); ylabel('i'); colormap bone end axis equal; axis tight brighten(prop{3}); title([ 'slice ' num2str(prop{2}) ]) catch end if ~ishold,hold on,end % draw points and lines for zz = 1:length(slicedata) if(slicedata(zz).proj==prop{1}) if(slicedata(zz).slice==prop{2}) polygon = slicedata(zz).polygon; for kk=1:length(polygon) if ~isempty(polygon{kk}) [xs,ys]=deal(polygon{kk}(:,1),polygon{kk}(:,2)); plot(xs, ys, 'g.-'); end end end end end % end for % draw other slices points points = getappdata(fig,'points'); pnts = round(points); if ~isempty(pnts) % exclude polygons inside the same slice indx = find(points(:,prop{1})==prop{2}); tmp = ones(1,size(points,1)); tmp(indx) = 0; pnts = points(find(tmp),:); % calculate indexes of other proj falling in current slice indx2 = find(round(pnts(:,prop{1}))==prop{2}); rest = setdiff([1 2 3],prop{1}); % plot the points for jj=1:length(indx2) [x,y] = deal(pnts(indx2(jj),rest(1)),pnts(indx2(jj),rest(2))); plot(y,x,'g*') end end % add blue cross markers in case of box selection box = getappdata(fig,'box'); point2mark = getappdata(fig,'point2mark'); if ~isempty(point2mark) plot(point2mark.x,point2mark.y,'marker','+') end if ~isempty(box) for kk=1:size(box,1) proj = box(kk,1); slice = box(kk,2); rowmin = box(kk,3); rowmax = box(kk,4); colmin = box(kk,5); colmax = box(kk,6); aaa = get(findobj(fig, 'color', 'g')); for ii=1:length(aaa) if ispolygon(aaa(ii)) L = length(aaa(ii).YData); for jj=1:L cond = lt(aaa(ii).YData(jj),rowmax).*gt(aaa(ii).YData(jj),rowmin).* ... lt(aaa(ii).XData(jj),colmax).*gt(aaa(ii).XData(jj),colmin); if cond plot(aaa(ii).XData(jj),aaa(ii).YData(jj),'marker','+') end end elseif ispoint(aaa(ii)) cond = lt(aaa(ii).YData,rowmax).*gt(aaa(ii).YData,rowmin).* ... lt(aaa(ii).XData,colmax).*gt(aaa(ii).XData,colmin); % the test after cond takes care the box doesnt propagate in 3D if (cond && (proj == prop{1}) && (slice == prop{2})) plot(aaa(ii).XData,aaa(ii).YData,'marker','+') end end end end end if get(findobj(fig, 'tag', 'toggle axes'), 'value') axis on else axis off end function cb_creategui(hObject, eventdata, handles) fig = get(hObject, 'parent'); % define the position of each GUI element position = { [1] % view radio [1 1] % del ins [1] % label slice [1 1] % slice [1] % brightness [1 1] % brightness [1] % axis visible [1 1] % view ij [1 1] % jk ik [1] % label mesh [1 1] % view open mesh [1 1] % save exit buttons }; % define the style of each GUI element style = { {'radiobutton'} {'radiobutton' 'radiobutton'} {'text' } {'pushbutton' 'pushbutton'} {'text'} {'pushbutton' 'pushbutton'} {'checkbox'} {'text' 'radiobutton'} {'radiobutton' 'radiobutton'} {'text' } {'pushbutton' 'pushbutton'} {'pushbutton' 'pushbutton'} }; % define the descriptive string of each GUI element string = { {'View'} {'Ins' 'Del'} {'slice'} {'<' '>'} {'brightness'} {'+' '-'} {'axes'} {'plane' 'jk'} {'ik' 'ij'} {'mesh'} {'smooth' 'view'} {'Cancel' 'OK'} }; % define the value of each GUI element prop = getappdata(fig,'prop'); value = { {1} {0 0} {[]} {[] []} {[]} {[] []} {0} {[] 1} {0 0} {[]} {1 1} {1 1} }; % define a tag for each GUI element tag = { {'view'} {'ins' 'del' } {'slice'} {'min' 'max'} {'brightness'} {'plus' 'minus'} {'toggle axes'} {'plane' 'one'} {'two' 'three'} {'mesh'} {'smoothm' 'viewm'} {'cancel' 'OK'} }; % define the callback function of each GUI element callback = { {@which_task1} {@which_task2 @which_task3} {[]} {@cb_btn @cb_btn} {[]} {@cb_btn @cb_btn} {@cb_redraw} {[] @cb_btnp1} {@cb_btnp2 @cb_btnp3} {[]} {@smooth_mesh @view_mesh} {@cancel_mesh @cb_btn} }; visible = { {'on'} {'on' 'on'} {'on'} {'on' 'on'} {'on'} {'on' 'on'} {'on'} {'on' 'on'} {'on' 'on'} {'on'} {'on' 'on'} {'on' 'on'} }; layoutgui(fig, [0.77 0.10 0.20 0.85], position, style, string, value, tag, callback,visible); function h = layoutgui(fig, geometry, position, style, string, value, tag, callback,visible); 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}, ... 'visible', visible{i}{j} ... ); end end function cb_btn(hObject, eventdata, handles) fig = get(gca, 'parent'); prop = getappdata(fig,'prop'); slice = prop{2}; br = prop{3}; datdim = size(getappdata(fig,'data')); % p1 = [];p2 = [];p3 = []; p1 = get(findobj('string','jk'),'value'); p2 = get(findobj('string','ik'),'value'); p3 = get(findobj('string','ij'),'value'); set(findobj('string','-'),'Value',prop{3}); set(findobj('string','+'),'Value',prop{3}); beta = get(findobj('string','-'),'Value'); if (p1) %jk setappdata(fig,'prop',{1,round(datdim(1)/2),br,prop{4}}); cb_redraw(gca); elseif (p2) %ik setappdata(fig,'prop',{2,round(datdim(2)/2),br,prop{4}}); cb_redraw(gca); elseif (p3) %ij setappdata(fig,'prop',{3,round(datdim(3)/2),br,prop{4}}); cb_redraw(gca); end if strcmp(get(hObject,'string'),'-') beta=beta-0.05; set(findobj('string','-'),'Value',beta); set(findobj('string','+'),'Value',beta); setappdata(fig,'prop',{prop{1},prop{2},beta,prop{4}}); cb_redraw(gca); elseif strcmp(get(hObject,'string'),'+') beta=beta+0.05; set(findobj('string','+'),'Value',beta); setappdata(fig,'prop',{prop{1},prop{2},beta,prop{4}}); cb_redraw(gca); end if strcmp(get(hObject,'string'),'<') setappdata(fig,'prop',{prop{1},slice-1,0,prop{4}}); cb_redraw(gca); end if strcmp(get(hObject,'string'),'>') setappdata(fig,'prop',{prop{1},slice+1,0,prop{4}}); cb_redraw(gca); end if strcmp(get(hObject,'string'),'OK') close(fig) end function keypress(h, eventdata, handles, varargin) fig = get(gca, 'parent'); prop = getappdata(fig,'prop'); dat = guidata(gcbf); key = get(gcbf, 'CurrentCharacter'); slice = prop{2}; if key switch key case 28 setappdata(fig,'prop',{prop{1},slice-1,0,prop{4}}); cb_redraw(gca); case 29 setappdata(fig,'prop',{prop{1},slice+1,0,prop{4}}); cb_redraw(gca); otherwise end end uiresume(h) function build_polygon fig = get(gca, 'parent'); prop = getappdata(fig,'prop'); data = getappdata(fig,'data'); ss = size(data); proj = prop{1}; slice = prop{2}; thispolygon =1; polygon{thispolygon} = zeros(0,2); maskhelp = [ ... '------------------------------------------------------------------------\n' ... 'specify polygons for masking the topographic interpolation\n' ... 'press the right mouse button to add another point to the current polygon\n' ... 'press backspace on the keyboard to remove the last point\n' ... 'press "c" on the keyboard to close this polygon and start with another\n' ... 'press "q" or ESC on the keyboard to continue\n' ... ]; again = 1; if ~ishold,hold,end fprintf(maskhelp); fprintf('\n'); while again for i=1:length(polygon) fprintf('polygon %d has %d points\n', i, size(polygon{i},1)); end [x, y, k] = ginput(1); okflag = 0; % check points do not fall out of image boundaries if get(findobj('string','Ins'),'value') if (proj == 1 && y<ss(2) && x<ss(3) && x>1 && y>1) okflag = 1; elseif (proj == 2 && y<ss(1) && x<ss(3) && x>1 && y>1) okflag = 1; elseif (proj == 3 && y<ss(1) && x<ss(2) && x>1 && y>1) okflag = 1; else okflag = 0; end end if okflag switch lower(k) case 1 polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]); % add the last line segment to the figure if size(polygon{thispolygon},1)>1 x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); end plot(x, y, 'g.-'); case 8 % backspace if size(polygon{thispolygon},1)>0 % redraw existing polygons cb_redraw(gca); % remove the last point of current polygon polygon{thispolygon} = polygon{thispolygon}(1:end-1,:); for i=1:length(polygon) x = polygon{i}(:,1); y = polygon{i}(:,2); if i~=thispolygon % close the polygon in the figure x(end) = x(1); y(end) = y(1); end set(gca,'nextplot','new') plot(x, y, 'g.-'); end end case 'c' if size(polygon{thispolygon},1)>0 % close the polygon polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:); % close the polygon in the figure x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); plot(x, y, 'g.-'); % switch to the next polygon thispolygon = thispolygon + 1; polygon{thispolygon} = zeros(0,2); slicedata = getappdata(fig,'slicedata'); m = length(slicedata); slicedata(m+1).proj = prop{1}; slicedata(m+1).slice = prop{2}; slicedata(m+1).polygon = polygon; setappdata(fig,'slicedata',slicedata); end case {'q', 27} if size(polygon{thispolygon},1)>0 % close the polygon polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:); % close the polygon in the figure x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); plot(x, y, 'g.-'); end again = 0; %set(gcf,'WindowButtonDownFcn',''); slicedata = getappdata(fig,'slicedata'); m = length(slicedata); if ~isempty(polygon{thispolygon}) slicedata(m+1).proj = prop{1}; slicedata(m+1).slice = prop{2}; slicedata(m+1).polygon = polygon; setappdata(fig,'slicedata',slicedata); end otherwise warning('invalid button (%d)', k); end end assign_points3d end function cb_btn_dwn(hObject, eventdata, handles) build_polygon uiresume function cb_btn_dwn2(hObject, eventdata, handles) global obj erase_points2d(obj) uiresume function erase_points2d (obj) fig = get(gca, 'parent'); prop = getappdata(fig,'prop'); slicedata = getappdata(fig,'slicedata'); pntsslice = []; % 2d slice selected box boundaries if strcmp(get(obj,'string'),'box') [x, y] = ft_select_box; rowmin = min(y); rowmax = max(y); colmin = min(x); colmax = max(x); box = getappdata(fig,'box'); box = [box; prop{1} prop{2} rowmin rowmax colmin colmax]; setappdata(fig,'box',box); else % converts lines to points pos = slicedata2pnts(prop{1},prop{2}); tmp = ft_select_point(pos); point2mark.x = tmp(1); point2mark.y = tmp(2); setappdata(fig,'point2mark',point2mark); end maskhelp = [ ... '------------------------------------------------------------------------\n' ... 'Delete points:\n' ... 'press "c" on the keyboard to undo all selections\n' ... 'press "d" or DEL on the keyboard to delete all selections\n' ... ]; fprintf(maskhelp); fprintf('\n'); again = 1; if ~ishold,hold,end cb_redraw(gca); % waits for a key press while again [junk1, junk2, k] = ginput(1); switch lower(k) case 'c' if strcmp(get(obj,'string'),'box') % undoes all the selections, but only in the current slice ind = []; for ii=1:size(box,1) if box(ii,1)==prop{1} && box(ii,2)==prop{2} ind = [ind,ii]; end end box(ind,:) = []; setappdata(fig,'box',box); cb_redraw(gca); again = 0; set(gcf,'WindowButtonDownFcn',''); else setappdata(fig,'point2mark',[]); cb_redraw(gca); again = 0; set(gcf,'WindowButtonDownFcn',''); end case {'d', 127} if strcmp(get(obj,'string'),'box') update_slicedata % deletes only the points selected in the current slice ind = []; for ii=1:size(box,1) if box(ii,1)==prop{1} && box(ii,2)==prop{2} ind = [ind,ii]; end end box(ind,:) = []; setappdata(fig,'box',box); cb_redraw(gca); again = 0; set(gcf,'WindowButtonDownFcn',''); else update_slicedata setappdata(fig,'point2mark',[]); cb_redraw(gca); again = 0; set(gcf,'WindowButtonDownFcn',''); end otherwise end end assign_points3d function assign_points3d fig = get(gca, 'parent'); slicedata = getappdata(fig,'slicedata'); points = []; for zz = 1:length(slicedata) slice = slicedata(zz).slice; proj = slicedata(zz).proj; polygon = slicedata(zz).polygon; for kk=1:length(polygon) if ~isempty(polygon{kk}) [xs,ys]=deal(polygon{kk}(:,1),polygon{kk}(:,2)); if (proj==1) %jk tmp = [ slice*ones(length(xs),1),ys(:),xs(:) ]; points = [points; unique(tmp,'rows')]; elseif (proj==2) %ik tmp = [ ys(:),slice*ones(length(xs),1),xs(:) ]; points = [points; unique(tmp,'rows')]; elseif (proj==3) %ij tmp = [ ys(:),xs(:),slice*ones(length(xs),1) ]; points = [points; unique(tmp,'rows')]; end end end end setappdata(fig,'points',points); function update_slicedata fig = get(gca, 'parent'); prop = getappdata(fig,'prop'); slicedata = getappdata(fig,'slicedata'); box = getappdata(fig,'box'); point2mark = getappdata(fig,'point2mark'); % case of box selection if ~isempty(box) && ~isempty(slicedata) for zz = 1:length(slicedata) slice = slicedata(zz).slice; proj = slicedata(zz).proj; polygon = slicedata(zz).polygon; for uu=1:size(box,1) if (box(uu,1)==proj) && (box(uu,2)==slice) for kk=1:length(polygon) if ~isempty(polygon{kk}) [xs,ys] = deal(polygon{kk}(:,1),polygon{kk}(:,2)); tmpind = lt(ys,ones(length(xs),1)*box(uu,4)).*gt(ys,ones(length(xs),1)*box(uu,3)).* ... lt(xs,ones(length(xs),1)*box(uu,6)).*gt(xs,ones(length(xs),1)*box(uu,5)); slicedata(zz).polygon{kk} = [ xs(find(~tmpind)),ys(find(~tmpind)) ]; end end end end end % case of point selection else if ~isempty(slicedata) for zz = 1:length(slicedata) slice = slicedata(zz).slice; proj = slicedata(zz).proj; polygon = slicedata(zz).polygon; for kk=1:length(polygon) if ~isempty(polygon{kk}) [xs,ys] = deal(polygon{kk}(:,1),polygon{kk}(:,2)); tmpind = eq(xs,point2mark.x).*eq(ys,point2mark.y); slicedata(zz).polygon{kk} = [ xs(find(~tmpind)),ys(find(~tmpind)) ]; end end end end end setappdata(fig,'slicedata',slicedata) % FIXME: obsolete: replaced by headshape at the beginning function smooth_mesh(hObject, eventdata, handles) fig = get(gca,'parent'); disp('not yet implemented') % FIXME: make it work for pre-loaded meshes function view_mesh(hObject, eventdata, handles) fig = get(gca, 'parent'); assign_points3d pnt = getappdata(fig,'points'); pnt_ = pnt; if ~isempty(pnt) tri = projecttri(pnt); bnd.pnt = pnt_; bnd.tri = tri; slicedata = getappdata(fig,'slicedata'); figure ft_plot_mesh(bnd,'vertexcolor','k'); end function cancel_mesh(hObject, eventdata, handles) fig = get(gca, 'parent'); close(fig) function cb_close(hObject, eventdata, handles) % get the points from the figure fig = hObject; global pnt pnt = getappdata(fig, 'points'); set(fig, 'CloseRequestFcn', @delete); delete(fig); function cb_btnp1(hObject, eventdata, handles) set(findobj('string','jk'),'value',1); set(findobj('string','ik'),'value',0); set(findobj('string','ij'),'value',0); cb_btn(hObject); function cb_btnp2(hObject, eventdata, handles) set(findobj('string','jk'),'value',0); set(findobj('string','ik'),'value',1); set(findobj('string','ij'),'value',0); cb_btn(hObject); function cb_btnp3(hObject, eventdata, handles) set(findobj('string','jk'),'value',0); set(findobj('string','ik'),'value',0); set(findobj('string','ij'),'value',1); cb_btn(hObject); function which_task1(hObject, eventdata, handles) set(gcf,'WindowButtonDownFcn',''); set(findobj('string','View'),'value',1); set(findobj('string','Ins'), 'value',0); set(findobj('string','Del'), 'value',0); set(gcf,'WindowButtonDownFcn',''); change_panel function which_task2(hObject, eventdata, handles) set(findobj('string','View'),'value',0); set(findobj('string','Ins'), 'value',1); set(findobj('string','Del'), 'value',0); set(gcf,'WindowButtonDownFcn',@cb_btn_dwn); change_panel function which_task3(hObject, eventdata, handles) set(gcf,'WindowButtonDownFcn',''); set(findobj('string','View'),'value',0); set(findobj('string','Ins'), 'value',0); set(findobj('string','Del'), 'value',1); change_panel function change_panel % affect panel visualization w1 = get(findobj('string','View'),'value'); w2 = get(findobj('string','Ins'), 'value'); w3 = get(findobj('string','Del'), 'value'); if w1 set(findobj('tag','slice'),'string','slice'); set(findobj('tag','min'),'string','<'); set(findobj('tag','max'),'string','>'); set(findobj('tag','min'),'style','pushbutton'); set(findobj('tag','max'),'style','pushbutton'); set(findobj('tag','min'),'callback',@cb_btn); set(findobj('tag','max'),'callback',@cb_btn); set(findobj('tag','mesh'),'visible','on'); set(findobj('tag','openm'),'visible','on'); set(findobj('tag','viewm'),'visible','on'); set(findobj('tag','brightness'),'visible','on'); set(findobj('tag','plus'),'visible','on'); set(findobj('tag','minus'),'visible','on'); set(findobj('tag','toggle axes'),'visible','on'); set(findobj('tag','plane'),'visible','on'); set(findobj('tag','one'),'visible','on'); set(findobj('tag','two'),'visible','on'); set(findobj('tag','three'),'visible','on'); elseif w2 set(findobj('tag','slice'),'string','select points'); set(findobj('tag','min'),'string','close'); set(findobj('tag','max'),'string','next'); set(findobj('tag','min'),'style','pushbutton'); set(findobj('tag','max'),'style','pushbutton'); set(findobj('tag','min'),'callback',@tins_close); set(findobj('tag','max'),'callback',@tins_next); set(findobj('tag','mesh'),'visible','off'); set(findobj('tag','openm'),'visible','off'); set(findobj('tag','viewm'),'visible','off'); set(findobj('tag','brightness'),'visible','off'); set(findobj('tag','plus'),'visible','off'); set(findobj('tag','minus'),'visible','off'); set(findobj('tag','toggle axes'),'visible','off'); set(findobj('tag','plane'),'visible','off'); set(findobj('tag','one'),'visible','off'); set(findobj('tag','two'),'visible','off'); set(findobj('tag','three'),'visible','off'); elseif w3 set(findobj('tag','slice'),'string','select points'); set(findobj('tag','min'),'string','box'); set(findobj('tag','max'),'string','point'); set(findobj('tag','min'),'style','pushbutton'); set(findobj('tag','max'),'style','pushbutton'); set(findobj('tag','min'),'callback',@tdel_box); set(findobj('tag','max'),'callback',@tdel_single); set(findobj('tag','mesh'),'visible','off'); set(findobj('tag','openm'),'visible','off'); set(findobj('tag','viewm'),'visible','off'); set(findobj('tag','brightness'),'visible','off'); set(findobj('tag','plus'),'visible','off'); set(findobj('tag','minus'),'visible','off'); set(findobj('tag','toggle axes'),'visible','off'); set(findobj('tag','plane'),'visible','off'); set(findobj('tag','one'),'visible','off'); set(findobj('tag','two'),'visible','off'); set(findobj('tag','three'),'visible','off'); end function tins_close(hObject, eventdata, handles) set(gcf,'WindowButtonDownFcn',''); function tins_next(hObject, eventdata, handles) set(gcf,'WindowButtonDownFcn',''); function tdel_box(hObject, eventdata, handles) global obj obj = gco; set(gcf,'WindowButtonDownFcn',@cb_btn_dwn2); function tdel_single(hObject, eventdata, handles) global obj obj = gco; set(gcf,'WindowButtonDownFcn',@cb_btn_dwn2); % accessory functions: function [pnts] = slicedata2pnts(proj,slice) fig = get(gca, 'parent'); slicedata = getappdata(fig,'slicedata'); pnts = []; for i=1:length(slicedata) if slicedata(i).slice==slice && slicedata(i).proj == proj for j=1:length(slicedata(i).polygon) if ~isempty(slicedata(i).polygon{j}) tmp = slicedata(i).polygon{j}; xs = tmp(:,1); ys = tmp(:,2); pnts = [pnts;[unique([xs,ys],'rows')]]; end end end end function h = ispolygon(x) h = length(x.XData)>1; function h = ispoint(x) h = length(x.XData)==1; function [T,P] = points2param(pnt) x = pnt(:,1); y = pnt(:,2); z = pnt(:,3); [phi,theta,R] = cart2sph(x,y,z); theta = theta + pi/2; phi = phi + pi; T = theta(:); P = phi(:); function [bnd2,a,Or] = spherical_harmonic_mesh(bnd, nl) % SPHERICAL_HARMONIC_MESH realizes the smoothed version of a mesh contained in the first % argument bnd. The boundary argument (bnd) contains typically 2 fields % called .pnt and .tri referring to vertices and triangulation of a mesh. % The degree of smoothing is given by the order in the second input: nl % % Use as % bnd2 = spherical_harmonic_mesh(bnd, nl); % nl = 12; % from van 't Ent paper bnd2 = []; % calculate midpoint Or = mean(bnd.pnt); % rescale all points x = bnd.pnt(:,1) - Or(1); y = bnd.pnt(:,2) - Or(2); z = bnd.pnt(:,3) - Or(3); X = [x(:), y(:), z(:)]; % convert points to parameters [T,P] = points2param(X); % basis function B = shlib_B(nl, T, P); Y = B'*X; % solve the linear system a = pinv(B'*B)*Y; % build the surface Xs = zeros(size(X)); for l = 0:nl-1 for m = -l:l if m<0 Yml = shlib_Yml(l, abs(m), T, P); Yml = (-1)^m*conj(Yml); else Yml = shlib_Yml(l, m, T, P); end indx = l^2 + l + m+1; Xs = Xs + Yml*a(indx,:); end fprintf('%d of %d\n', l, nl); end % Just take the real part Xs = real(Xs); % reconstruct the matrices for plotting. xs = reshape(Xs(:,1), size(x,1), size(x,2)); ys = reshape(Xs(:,2), size(x,1), size(x,2)); zs = reshape(Xs(:,3), size(x,1), size(x,2)); bnd2.pnt = [xs(:)+Or(1) ys(:)+Or(2) zs(:)+Or(3)]; [bnd2.tri] = projecttri(bnd.pnt); function B = shlib_B(nl, theta, phi) % function B = shlib_B(nl, theta, phi) % % Constructs the matrix of basis functions % where b(i,l^2 + l + m) = Yml(theta, phi) % % See also: shlib_Yml.m, shlib_decomp.m, shlib_gen_shfnc.m % % Dr. A. I. Hanna (2006). B = zeros(length(theta), nl^2+2*nl+1); for l = 0:nl-1 for m = -l:l if m<0 Yml = shlib_Yml(l, abs(m), theta, phi); Yml = (-1)^m*conj(Yml); else Yml = shlib_Yml(l, m, theta, phi); end indx = l^2 + l + m+1; B(:, indx) = Yml; end end return; function Yml = shlib_Yml(l, m, theta, phi) % function Yml = shlib_Yml(l, m, theta, phi) % % A matlab function that takes a given order and degree, and the matrix of % theta and phi and constructs a spherical harmonic from these. The % analogue in the 1D case would be to give a particular frequency. % % Inputs: % m - order of the spherical harmonic % l - degree of the spherical harmonic % theta - matrix of polar coordinates \theta \in [0, \pi] % phi - matrix of azimuthal cooridinates \phi \in [0, 2\pi) % % Example: % % [x, y] = meshgrid(-1:.1:1); % z = x.^2 + y.^2; % [phi,theta,R] = cart2sph(x,y,z); % Yml = spharm_aih(2,2, theta(:), phi(:)); % % See also: shlib_B.m, shlib_decomp.m, shlib_gen_shfnc.m % % Dr. A. I. Hanna (2006) Pml=legendre(l,cos(theta)); if l~=0 Pml=squeeze(Pml(m+1,:,:)); end Pml = Pml(:); % Yml = sqrt(((2*l+1)/4).*(factorial(l-m)/factorial(l+m))).*Pml.*exp(sqrt(-1).*m.*phi); % new: Yml = sqrt(((2*l+1)/(4*pi)).*(factorial(l-m)/factorial(l+m))).*Pml.*exp(sqrt(-1).*m.*phi); return;
github
philippboehmsturm/antx-master
nan_mean.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/nan_mean.m
2,258
utf_8
6b8f442f6a16b560230335ac6d8c97e6
% nan_mean() - Average, not considering NaN values % % Usage: same as mean() % Author: Arnaud Delorme, CNL / Salk Institute, 16 Oct 2002 %123456789012345678901234567890123456789012345678901234567890123456789012 % 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 % 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: nan_mean.m 2622 2011-01-20 15:32:41Z jorhor $ function out = nan_mean(in, dim) if nargin < 1 help nan_mean; return; end; if nargin < 2 if size(in,1) ~= 1 dim = 1; elseif size(in,2) ~= 1 dim = 2; else dim = 3; end; end; tmpin = in; tmpin(find(isnan(in(:)))) = 0; ws = warning('off', 'MATLAB:divideByZero'); out = sum(tmpin, dim) ./ sum(~isnan(in),dim); warning(ws);
github
philippboehmsturm/antx-master
matlabversion.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/matlabversion.m
3,375
utf_8
420300c3dc97894d63a198aa0d304dac
function [inInterval] = matlabversion(min, max) % MATLABVERSION checks if the current matlab version is within the interval % specified by min and max. % % Use, e.g., as: % if matlabversion(7.0, 7.9) % % do something % end % % Both strings and numbers, as well as infinities, are supported, eg.: % matlabversion(7.1, 7.9) % is version between 7.1 and 7.9? % matlabversion(-Inf, 7.6) % is version <= 7.6? % matlabversion(6, '7.10') % between 6 and 7.10? (note: '7.10', not 7.10) % matlabversion('2008b', '2010a') % matlabversion('2008b', Inf) % matlabversion('2009b', '2009b') % exactly 2009b % etc. % % See also VERSION, VER % Copyright (C) 2006, Robert Oostenveld; 2010, Eelke Spaak % % 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: matlabversion.m 2885 2011-02-16 09:41:58Z roboos $ curVer = version(); if ((ischar(min) && isempty(str2num(min))) || (ischar(max) && isempty(str2num(max)))) % perform comparison with respect to release string ind = strfind(curVer, '(R'); [year, ab] = parseMatlabRelease(curVer((ind + 2):(numel(curVer) - 1))); [minY, minAb] = parseMatlabRelease(min); [maxY, maxAb] = parseMatlabRelease(max); inInterval = orderedComparison(minY, minAb, maxY, maxAb, year, ab); else % perform comparison with respect to version number [major, minor] = parseMatlabVersion(curVer); [minMajor, minMinor] = parseMatlabVersion(min); [maxMajor, maxMinor] = parseMatlabVersion(max); inInterval = orderedComparison(minMajor, minMinor, maxMajor, maxMinor, major, minor); end function [year, ab] = parseMatlabRelease(str) if (str == Inf) year = Inf; ab = Inf; elseif (str == -Inf) year = -Inf; ab = -Inf; else year = str2num(str(1:4)); ab = str(5); end end function [major, minor] = parseMatlabVersion(ver) if (ver == Inf) major = Inf; minor = Inf; elseif (ver == -Inf) major = -Inf; minor = -Inf; elseif (isnumeric(ver)) major = floor(ver); minor = int8((ver - floor(ver)) * 10); else % ver is string (e.g. '7.10'), parse accordingly [major, rest] = strtok(ver, '.'); major = str2num(major); minor = str2num(strtok(rest, '.')); end end % checks if testA is in interval (lowerA,upperA); if at edges, checks if testB is in interval (lowerB,upperB). function inInterval = orderedComparison(lowerA, lowerB, upperA, upperB, testA, testB) if (testA < lowerA || testA > upperA) inInterval = false; else inInterval = true; if (testA == lowerA) inInterval = inInterval && (testB >= lowerB); end if (testA == upperA) inInterval = inInterval && (testB <= upperB); end end end end
github
philippboehmsturm/antx-master
nanmean.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/nanmean.m
2,121
utf_8
7e0ebd9ca56f2cd79f89031bbccebb9a
% nanmean() - Average, not considering NaN values % % Usage: same as mean() % Author: Arnaud Delorme, CNL / Salk Institute, 16 Oct 2002 %123456789012345678901234567890123456789012345678901234567890123456789012 % 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 % 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: nanmean.m 2885 2011-02-16 09:41:58Z roboos $ function out = nanmean(in, dim) if nargin < 1 help nanmean; return; end; if nargin < 2 if size(in,1) ~= 1 dim = 1; elseif size(in,2) ~= 1 dim = 2; else dim = 3; end; end; tmpin = in; tmpin(find(isnan(in(:)))) = 0; out = sum(tmpin, dim) ./ sum(~isnan(in),dim);
github
philippboehmsturm/antx-master
nanvar.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/nanvar.m
2,439
utf_8
201826aeefbd74374df411fca75bb78f
% nanvar() - var, not considering NaN values % % Usage: same as var() % Author: Arnaud Delorme, CNL / Salk Institute, Sept 2003 %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 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: nanvar.m 2885 2011-02-16 09:41:58Z roboos $ function out = nanvar(in, varargin) if nargin < 1 help nanvar; return; end if nargin == 1, flag = 0; end if nargin < 3, if size(in,1) ~= 1 dim = 1; elseif size(in,2) ~= 1 dim = 2; else dim = 3; end end if nargin == 2, flag = varargin{1}; end if nargin == 3, flag = varargin{1}; dim = varargin{2}; end if isempty(flag), flag = 0; end nans = find(isnan(in)); in(nans) = 0; nonnans = ones(size(in)); nonnans(nans) = 0; nonnans = sum(nonnans, dim); nononnans = find(nonnans==0); nonnans(nononnans) = 1; out = (sum(in.^2, dim)-sum(in, dim).^2./nonnans)./(nonnans-abs(flag-1)); out(nononnans) = NaN;
github
philippboehmsturm/antx-master
tinv.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/tinv.m
7,634
utf_8
8fe66ec125f91e1a7ac5f8d3cb2ac51a
function x = tinv(p,v); % TINV Inverse of Student's T cumulative distribution function (cdf). % X=TINV(P,V) returns the inverse of Student's T cdf with V degrees % of freedom, at the values in P. % % The size of X is the common size of P and V. A scalar input % functions as a constant matrix of the same size as the other input. % % This is an open source function that was assembled by Eric Maris using % open source subfunctions found on the web. % Subversion does not use the Log keyword, use 'svn log <filename>' or 'svn -v log | less' to get detailled information if nargin < 2, error('Requires two input arguments.'); end [errorcode p v] = distchck(2,p,v); if errorcode > 0 error('Requires non-scalar arguments to match in size.'); end % Initialize X to zero. x=zeros(size(p)); k = find(v < 0 | v ~= round(v)); if any(k) tmp = NaN; x(k) = tmp(ones(size(k))); end k = find(v == 1); if any(k) x(k) = tan(pi * (p(k) - 0.5)); end % The inverse cdf of 0 is -Inf, and the inverse cdf of 1 is Inf. k0 = find(p == 0); if any(k0) tmp = Inf; x(k0) = -tmp(ones(size(k0))); end k1 = find(p ==1); if any(k1) tmp = Inf; x(k1) = tmp(ones(size(k1))); end k = find(p >= 0.5 & p < 1); if any(k) z = betainv(2*(1-p(k)),v(k)/2,0.5); x(k) = sqrt(v(k) ./ z - v(k)); end k = find(p < 0.5 & p > 0); if any(k) z = betainv(2*(p(k)),v(k)/2,0.5); x(k) = -sqrt(v(k) ./ z - v(k)); end %%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION distchck %%%%%%%%%%%%%%%%%%%%%%%%% function [errorcode,varargout] = distchck(nparms,varargin) %DISTCHCK Checks the argument list for the probability functions. errorcode = 0; varargout = varargin; if nparms == 1 return; end % Get size of each input, check for scalars, copy to output isscalar = (cellfun('prodofsize',varargin) == 1); % Done if all inputs are scalars. Otherwise fetch their common size. if (all(isscalar)), return; end n = nparms; for j=1:n sz{j} = size(varargin{j}); end t = sz(~isscalar); size1 = t{1}; % Scalars receive this size. Other arrays must have the proper size. for j=1:n sizej = sz{j}; if (isscalar(j)) t = zeros(size1); t(:) = varargin{j}; varargout{j} = t; elseif (~isequal(sizej,size1)) errorcode = 1; return; end end %%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION betainv %%%%%%%%%%%%%%%%%%%%%%%%%%% function x = betainv(p,a,b); %BETAINV Inverse of the beta cumulative distribution function (cdf). % X = BETAINV(P,A,B) returns the inverse of the beta cdf with % parameters A and B at the values in P. % % The size of X is the common size of the input arguments. A scalar input % functions as a constant matrix of the same size as the other inputs. % % BETAINV uses Newton's method to converge to the solution. % Reference: % [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical % Functions", Government Printing Office, 1964. % B.A. Jones 1-12-93 if nargin < 3, error('Requires three input arguments.'); end [errorcode p a b] = distchck(3,p,a,b); if errorcode > 0 error('Requires non-scalar arguments to match in size.'); end % Initialize x to zero. x = zeros(size(p)); % Return NaN if the arguments are outside their respective limits. k = find(p < 0 | p > 1 | a <= 0 | b <= 0); if any(k), tmp = NaN; x(k) = tmp(ones(size(k))); end % The inverse cdf of 0 is 0, and the inverse cdf of 1 is 1. k0 = find(p == 0 & a > 0 & b > 0); if any(k0), x(k0) = zeros(size(k0)); end k1 = find(p==1); if any(k1), x(k1) = ones(size(k1)); end % Newton's Method. % Permit no more than count_limit interations. count_limit = 100; count = 0; k = find(p > 0 & p < 1 & a > 0 & b > 0); pk = p(k); % Use the mean as a starting guess. xk = a(k) ./ (a(k) + b(k)); % Move starting values away from the boundaries. if xk == 0, xk = sqrt(eps); end if xk == 1, xk = 1 - sqrt(eps); end h = ones(size(pk)); crit = sqrt(eps); % Break out of the iteration loop for the following: % 1) The last update is very small (compared to x). % 2) The last update is very small (compared to 100*eps). % 3) There are more than 100 iterations. This should NEVER happen. while(any(abs(h) > crit * abs(xk)) & max(abs(h)) > crit ... & count < count_limit), count = count+1; h = (betacdf(xk,a(k),b(k)) - pk) ./ betapdf(xk,a(k),b(k)); xnew = xk - h; % Make sure that the values stay inside the bounds. % Initially, Newton's Method may take big steps. ksmall = find(xnew < 0); klarge = find(xnew > 1); if any(ksmall) | any(klarge) xnew(ksmall) = xk(ksmall) /10; xnew(klarge) = 1 - (1 - xk(klarge))/10; end xk = xnew; end % Return the converged value(s). x(k) = xk; if count==count_limit, fprintf('\nWarning: BETAINV did not converge.\n'); str = 'The last step was: '; outstr = sprintf([str,'%13.8f'],h); fprintf(outstr); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION betapdf %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = betapdf(x,a,b) %BETAPDF Beta probability density function. % Y = BETAPDF(X,A,B) returns the beta probability density % function with parameters A and B at the values in X. % % The size of Y is the common size of the input arguments. A scalar input % functions as a constant matrix of the same size as the other inputs. % References: % [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical % Functions", Government Printing Office, 1964, 26.1.33. if nargin < 3, error('Requires three input arguments.'); end [errorcode x a b] = distchck(3,x,a,b); if errorcode > 0 error('Requires non-scalar arguments to match in size.'); end % Initialize Y to zero. y = zeros(size(x)); % Return NaN for parameter values outside their respective limits. k1 = find(a <= 0 | b <= 0 | x < 0 | x > 1); if any(k1) tmp = NaN; y(k1) = tmp(ones(size(k1))); end % Return Inf for x = 0 and a < 1 or x = 1 and b < 1. % Required for non-IEEE machines. k2 = find((x == 0 & a < 1) | (x == 1 & b < 1)); if any(k2) tmp = Inf; y(k2) = tmp(ones(size(k2))); end % Return the beta density function for valid parameters. k = find(~(a <= 0 | b <= 0 | x <= 0 | x >= 1)); if any(k) y(k) = x(k) .^ (a(k) - 1) .* (1 - x(k)) .^ (b(k) - 1) ./ beta(a(k),b(k)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION betacdf %%%%%%%%%%%%%%%%%%%%%%%%%%%% function p = betacdf(x,a,b); %BETACDF Beta cumulative distribution function. % P = BETACDF(X,A,B) returns the beta cumulative distribution % function with parameters A and B at the values in X. % % The size of P is the common size of the input arguments. A scalar input % functions as a constant matrix of the same size as the other inputs. % % BETAINC does the computational work. % Reference: % [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical % Functions", Government Printing Office, 1964, 26.5. if nargin < 3, error('Requires three input arguments.'); end [errorcode x a b] = distchck(3,x,a,b); if errorcode > 0 error('Requires non-scalar arguments to match in size.'); end % Initialize P to 0. p = zeros(size(x)); k1 = find(a<=0 | b<=0); if any(k1) tmp = NaN; p(k1) = tmp(ones(size(k1))); end % If is X >= 1 the cdf of X is 1. k2 = find(x >= 1); if any(k2) p(k2) = ones(size(k2)); end k = find(x > 0 & x < 1 & a > 0 & b > 0); if any(k) p(k) = betainc(x(k),a(k),b(k)); end % Make sure that round-off errors never make P greater than 1. k = find(p > 1); p(k) = ones(size(k));
github
philippboehmsturm/antx-master
prepare_timefreq_data.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/prepare_timefreq_data.m
23,749
utf_8
3ad7647541444236bdea168c9c52ffc5
function [cfg, data] = prepare_timefreq_data(cfg, varargin); % PREPARE_TIMEFREQ_DATA collects the overlapping data from multiple ERPs % or ERFs according to the channel/time/freq-selection in the configuration % and returns it with a dimord of 'repl_chan_freq_time'. % % Supported input data is from TIMELOCKANALYSIS, TIMELOCKGRANDAVERAGE, % FREQANALYSIS or FREQDESCRIPTIVES. % % Use as % [cfg, data] = prepare_timefreq_data(cfg, varargin) % where the configuration can contain % cfg.channel = cell-array of size Nx1, see CHANNELSELECTION, or % cfg.channelcmb = cell-array of size Nx2, see CHANNELCOMBINATION % cfg.latency = [begin end], can be 'all' (default) % cfg.frequency = [begin end], can be 'all' (default) % cfg.avgoverchan = 'yes' or 'no' (default) % cfg.avgovertime = 'yes' or 'no' (default) % cfg.avgoverfreq = 'yes' or 'no' (default) % cfg.datarepresentation = 'cell-array' or 'concatenated' % cfg.precision = 'single' or 'double' (default) % % If the data contains both power- and cross-spectra, they will be concatenated % and treated together. In that case you should specify cfg.channelcmb instead % of cfg.channel. % % This function can serve as a subfunction for TIMEFREQRANDOMIZATION, % TIMEFREQCLUSTER and other statistical functions, so that those functions % do not have to do the bookkeeping themselves. % KNOWN BUGS AND LIMITATIONS % copying of data is not memory efficient for cell-array output % cfg.precision is not used for cell-array output % Copyright (C) 2004, 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: prepare_timefreq_data.m 2097 2010-11-10 09:20:18Z roboos $ % set the defaults if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end if ~isfield(cfg, 'channelcmb'), cfg.channelcmb = []; end if ~isfield(cfg, 'latency'), cfg.latency = 'all'; end if ~isfield(cfg, 'frequency'), cfg.frequency = 'all'; end if ~isfield(cfg, 'avgoverchan'), cfg.avgoverchan = 'no'; end if ~isfield(cfg, 'avgovertime'), cfg.avgovertime = 'no'; end if ~isfield(cfg, 'avgoverfreq'), cfg.avgoverfreq = 'no'; end if ~isfield(cfg, 'datarepresentation'), cfg.datarepresentation = 'cell-array'; end if ~isfield(cfg, 'precision'), cfg.precision = 'double'; end % initialize containsdof = false; % count the number of input datasets Nvarargin = length(varargin); remember = {}; % initialize swapmemfile; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % collect information over all data sets required for a consistent selection % this is the first time that the data will be swapped from file into memory %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for c=1:Nvarargin % swap the data into memory varargin{c} = swapmemfile(varargin{c}); % for backward compatibility with old data structures varargin{c} = fixdimord(varargin{c}); % reformat the data, and combine cross and power spectra [remember{c}, hascrsspctrm] = forcedimord(varargin{c}); % keep a small part of the data in memory if hascrsspctrm remember{c} = rmfield(remember{c}, 'dat'); remember{c} = rmfield(remember{c}, 'crs'); else remember{c} = rmfield(remember{c}, 'dat'); end % swap the data out of memory varargin{c} = swapmemfile(varargin{c}); end if hascrsspctrm % by default this should be empty cfg.channel = []; if isempty(cfg.channelcmb) % default is to copy the channelcombinations from the first dataset % and these have been concatenated by forcedimord -> tear them apart cfg.channelcmb = label2cmb(remember{1}.label); end % instead of matching channelcombinations, we will match channels that % consist of the concatenated labels of the channelcombinations cfg.channel = cmb2label(cfg.channelcmb); cfg.channelcmb = []; % this will be reconstructed at the end else % by default this should be empty cfg.channelcmb = []; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % adjust the selection of channels, latency and frequency so that it % matches with all datasets %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for c=1:Nvarargin % match the channel selection with this dataset cfg.channel = ft_channelselection(cfg.channel, remember{c}.label); % match the selected latency with this dataset if isempty(findstr(remember{c}.dimord, 'time')) || all(isnan(remember{c}.time)) cfg.latency = []; elseif ischar(cfg.latency) && strcmp(cfg.latency, 'all') cfg.latency = []; cfg.latency(1) = min(remember{c}.time); cfg.latency(2) = max(remember{c}.time); else cfg.latency(1) = max(cfg.latency(1), min(remember{c}.time)); cfg.latency(2) = min(cfg.latency(2), max(remember{c}.time)); end % match the selected frequency with this dataset if isempty(findstr(remember{c}.dimord, 'freq')) || all(isnan(remember{c}.freq)) cfg.frequency = []; elseif ischar(cfg.frequency) && strcmp(cfg.frequency, 'all') cfg.frequency = []; cfg.frequency(1) = min(remember{c}.freq); cfg.frequency(2) = max(remember{c}.freq); else cfg.frequency(1) = max(cfg.frequency(1), min(remember{c}.freq)); cfg.frequency(2) = min(cfg.frequency(2), max(remember{c}.freq)); end % keep track of the number of replications Nrepl(c) = length(remember{c}.repl); end % count the number of channels, time bins and frequency bins dimord = remember{c}.dimord; if ~isempty(cfg.latency) && ~all(isnan(cfg.latency)) timesel = nearest(remember{1}.time, cfg.latency(1)):nearest(remember{1}.time, cfg.latency(2)); else timesel = 1; end if ~isempty(cfg.frequency) && ~all(isnan(cfg.frequency)) freqsel = nearest(remember{1}.freq, cfg.frequency(1)):nearest(remember{1}.freq, cfg.frequency(2)); else freqsel = 1; end Nchan = length(cfg.channel); Ntime = length(timesel); Nfreq = length(freqsel); if ~hascrsspctrm % print the information for channels if Nchan<1 error('channel selection is empty') elseif strcmp(cfg.avgoverchan, 'yes') fprintf('averaging over %d channels\n', Nchan); Nchan = 1; % after averaging else fprintf('selected %d channels\n', Nchan); end else % print the (same) information for channelcombinations if Nchan<1 error('channelcombination selection is empty') elseif strcmp(cfg.avgoverchan, 'yes') fprintf('averaging over %d channelcombinations\n', Nchan); Nchan = 1; % after averaging else fprintf('selected %d channelcombinations\n', Nchan); end end if Ntime<1 error('latency selection is empty') elseif strcmp(cfg.avgovertime, 'yes') fprintf('averaging over %d time bins\n', Ntime); Ntime = 1; % after averaging else fprintf('selected %d time bins\n', Ntime); end if Nfreq<1 error('latency selection is empty') elseif strcmp(cfg.avgoverfreq, 'yes') fprintf('averaging over %d frequency bins\n', Nfreq); Nfreq = 1; % after averaging else fprintf('selected %d frequency bins\n', Nfreq); end % determine whether, and over which dimensions the data should be averaged tok = tokenize(dimord, '_'); chandim = find(strcmp(tok, 'chan')); timedim = find(strcmp(tok, 'time')); freqdim = find(strcmp(tok, 'freq')); avgdim = []; if strcmp(cfg.avgoverchan, 'yes') && ~isempty(chandim) avgdim = [avgdim chandim]; end if strcmp(cfg.avgovertime, 'yes') && ~isempty(timedim) avgdim = [avgdim timedim]; end if strcmp(cfg.avgoverfreq, 'yes') && ~isempty(freqdim) avgdim = [avgdim freqdim]; end % this will hold the output data if strcmp(cfg.datarepresentation, 'cell-array') dat = {}; dof = {}; elseif strcmp(cfg.datarepresentation, 'concatenated') % preallocate memory to hold all the data if hascrsspctrm if str2num(version('-release'))>=14 dat = complex(zeros(sum(Nrepl), Nchan, Nfreq, Ntime, cfg.precision)); else % use double precision for default and Matlab versions prior to release 14 if ~strcmp(cfg.precision, 'double') warning('Matlab versions prior to release 14 only support double precision'); end dat = complex(zeros(sum(Nrepl), Nchan, Nfreq, Ntime)); end else if str2num(version('-release'))>=14 dat = zeros(sum(Nrepl), Nchan, Nfreq, Ntime, cfg.precision); else % use double precision for default and Matlab versions prior to release 14 if ~strcmp(cfg.precision, 'double') warning('Matlab versions prior to release 14 only support double precision'); end dat = zeros(sum(Nrepl), Nchan, Nfreq, Ntime); end end if isempty(avgdim) dof = zeros(sum(Nrepl), Nfreq, Ntime); end; else error('unsupported output data representation'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % select the desired channels, latency and frequency bins from each dataset % this is the second time that the data will be swapped from file into memory %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for c=1:Nvarargin % swap the data into memory varargin{c} = swapmemfile(varargin{c}); % reformat the data, and combine cross and power spectra [varargin{c}, hascrsspctrm] = forcedimord(varargin{c}); % select the channels, sorted according to the order in the configuration [dum, chansel] = match_str(cfg.channel, varargin{c}.label); if ~isempty(cfg.latency) timesel = nearest(varargin{c}.time, cfg.latency(1)):nearest(varargin{c}.time, cfg.latency(2)); end if ~isempty(cfg.frequency) freqsel = nearest(varargin{c}.freq, cfg.frequency(1)):nearest(varargin{c}.freq, cfg.frequency(2)); end if hascrsspctrm Nfreq = size(varargin{c}.crs, 3); Ntime = size(varargin{c}.crs, 4); % separate selection for the auto-spectra and cross-spectra Ndat = size(varargin{c}.dat, 2); % count the total number of auto-spectra Ncrs = size(varargin{c}.crs, 2); % count the total number of cross-spectra [dum, chansel_dat] = ismember(chansel, 1:Ndat); % selection of auto-spectra chansel_dat=chansel_dat(chansel_dat~=0)'; [dum, chansel_crs] = ismember(chansel, (1:Ncrs)+Ndat); % selection of cross-spectra chansel_crs=chansel_crs(chansel_crs~=0)'; Ndatsel = length(chansel_dat); % count the number of selected auto-spectra Ncrssel = length(chansel_crs); % count the number of selected cross-spectra else Nfreq = size(varargin{c}.dat, 3); Ntime = size(varargin{c}.dat, 4); end % collect the data, average if required if strcmp(cfg.datarepresentation, 'cell-array') if hascrsspctrm dat{c} = cat(2, avgoverdim(varargin{c}.dat(:, chansel_dat, freqsel, timesel), avgdim), avgoverdim(varargin{c}.crs(:, chansel_crs, freqsel, timesel), avgdim)); else dat{c} = avgoverdim(varargin{c}.dat(:, chansel, freqsel, timesel), avgdim); end if isfield(varargin{c},'dof') containsdof = isempty(avgdim); if containsdof dof{c} = varargin{c}.dof(:,freqsel,timesel); else warning('Degrees of freedom cannot be calculated if averaging over channels, frequencies, or time bins is requested.'); end; end; elseif strcmp(cfg.datarepresentation, 'concatenated') if c==1 trialsel = 1:Nrepl(1); else trialsel = (1+sum(Nrepl(1:(c-1)))):sum(Nrepl(1:c)); end % THIS IS IMPLEMENTED WITH STRICT MEMORY CONSIDERATIONS % handle cross-spectrum and auto-spectrum separately % first copy complex part (crs) then real part (pow), otherwise dat first will be made real and then complex again % copy selection of "all" as complete matrix and not as selection % copy selection with for loops (not yet implemented below) if isempty(avgdim) && hascrsspctrm if length(chansel_crs)==Ncrs && length(freqsel)==Nfreq && length(timesel)==Ntime && all(chansel_crs==(1:Ncrs)) && all(freqsel==(1:Nfreq)) && all(timesel==(1:Ntime)) % copy everything into the output data array % this is more memory efficient than selecting everything dat(trialsel,(1:Ncrssel)+Ndatsel,:,:) = varargin{c}.crs; else % copy only a selection into the output data array % this could be made more memory efficient using for-loops dat(trialsel,(1:Ncrssel)+Ndatsel,:,:) = varargin{c}.crs(:, chansel_crs, freqsel, timesel); end dat(trialsel,1:Ndatsel,:,:) = varargin{c}.dat(:, chansel_dat, freqsel, timesel); elseif ~isempty(avgdim) && hascrsspctrm if length(chansel_crs)==Ncrs && length(freqsel)==Nfreq && length(timesel)==Ntime && all(chansel_crs==(1:Ncrs)) && all(freqsel==(1:Nfreq)) && all(timesel==(1:Ntime)) % copy everything into the output data array % this is more memory efficient than selecting everything dat(trialsel,(1:Ncrssel)+Ndatsel,:,:) = avgoverdim(varargin{c}.crs, avgdim); else % copy only a selection into the output data array % this could be made more memory efficient using for-loops dat(trialsel,(1:Ncrssel)+Ndatsel,:,:) = avgoverdim(varargin{c}.crs(:, chansel_crs, freqsel, timesel), avgdim); end dat(trialsel,1:Ndatsel,:,:) = avgoverdim(varargin{c}.dat(:, chansel_dat, freqsel, timesel), avgdim); elseif isempty(avgdim) && ~hascrsspctrm dat(trialsel,:,:,:) = varargin{c}.dat(:, chansel, freqsel, timesel); elseif ~isempty(avgdim) && ~hascrsspctrm dat(trialsel,:,:,:) = avgoverdim(varargin{c}.dat(:, chansel, freqsel, timesel), avgdim); end if isfield(varargin{c},'dof') containsdof = isempty(avgdim); if containsdof dof(trialsel,:,:) = varargin{c}.dof(:,freqsel,timesel); else warning('Degrees of freedom cannot be calculated if averaging over channels, frequencies, or time bins is requested.'); end; end; end % swap the data out of memory varargin{c} = swapmemfile(varargin{c}); end % collect the output data data.biol = dat; data.dimord = dimord; if containsdof data.dof = dof; end; if strcmp(cfg.datarepresentation, 'concatenated') % all trials are combined together, construct a design matrix to ensure % that they can be identified afterwards data.design(:,1) = 1:sum(Nrepl); for c=1:Nvarargin if c==1 trialsel = 1:Nrepl(1); else trialsel = (1+sum(Nrepl(1:(c-1)))):sum(Nrepl(1:c)); end data.design(trialsel,2) = 1:length(trialsel); data.design(trialsel,3) = c; end end if ~hascrsspctrm if strcmp(cfg.avgoverchan, 'yes') concatlabel = sprintf('%s+', remember{end}.label{chansel}); % concatenate the labels with a '+' in between concatlabel(end) = []; % remove the last '+' data.label = {concatlabel}; % this should be a cell-array else data.label = remember{end}.label(chansel); end else % specify the correct dimord and channelcombinations labelcmb = label2cmb(remember{end}.label(chansel)); if strcmp(cfg.avgoverchan, 'yes') % the cross-spectra have been averaged, therefore there is only one combination left str1 = sprintf('%s+', labelcmb{:,1}); str1(end) = []; str2 = sprintf('%s+', labelcmb{:,2}); str2(end) = []; data.labelcmb = {str1, str2}; else data.labelcmb = labelcmb; end % the dimord should specify chancmb instead of chan s = strfind(dimord, 'chan'); data.dimord = [data.dimord(1:(s-1)) 'chancmb' data.dimord((s+4):end)]; end if ~all(isnan(cfg.latency)) if strcmp(cfg.avgovertime, 'yes') data.time = mean(remember{end}.time(timesel)); else data.time = remember{end}.time(timesel); end else % the output data contains a time dimension, but the input data did not contain a time axis data.time = nan; cfg.latency = []; end if ~all(isnan(cfg.frequency)) if strcmp(cfg.avgoverfreq, 'yes') data.freq = mean(remember{end}.freq(freqsel)); else data.freq = remember{end}.freq(freqsel); end else % the output data contains a freq dimension, but the input data did not contain a freq axis data.freq = nan; cfg.frequency = []; end % add version information to the configuration cfg.version.name = mfilename('fullpath'); cfg.version.id = '$Id: prepare_timefreq_data.m 2097 2010-11-10 09:20:18Z roboos $'; cfg.previous = []; % remember the configuration details from the input data for c=1:Nvarargin try, cfg.previous{c} = remember{c}.cfg; end end % remember the full configuration details data.cfg = cfg; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to help with the averaging over multiple dimensions at the % same time. Furthermore, the output data will have the same NUMBER of % dimensions as the input data (i.e. no squeezing) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dat] = avgoverdim(dat, dim); siz = size(dat); siz((end+1):4) = 1; % this should work at least up to 4 dimensions, also if not present in the data for i=dim siz(i) = 1; dat = mean(dat, i); % compute the mean over this dimension dat = reshape(dat, siz); % ensure that the number of dimenstions remains the same end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that reformats the data into a consistent struct with a fixed % dimord and that combines power and cross-spectra %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [output, hascrsspctrm] = forcedimord(input); % for backward compatibility with old timelockanalysis data that does not contain a dimord if ~isfield(input, 'dimord') && isfield(input, 'avg') && isfield(input, 'var') && isfield(input, 'trial') input.dimord = 'repl_chan_time'; elseif ~isfield(input, 'dimord') && isfield(input, 'avg') && isfield(input, 'var') && ~isfield(input, 'trial') input.dimord = 'chan_time'; end outputdim = tokenize('repl_chan_freq_time', '_'); inputdim = tokenize(input.dimord, '_'); % ensure consistent names of the dimensions try, inputdim{strcmp(inputdim, 'rpt')} = 'repl'; end; try, inputdim{strcmp(inputdim, 'rpttap')} = 'repl'; end; try, inputdim{strcmp(inputdim, 'trial')} = 'repl'; end; try, inputdim{strcmp(inputdim, 'subj')} = 'repl'; end; try, inputdim{strcmp(inputdim, 'sgncmb')} = 'chan'; end; try, inputdim{strcmp(inputdim, 'sgn')} = 'chan'; end; try, inputdim{strcmp(inputdim, 'frq')} = 'freq'; end; try, inputdim{strcmp(inputdim, 'tim')} = 'time'; end; try, output.cfg = input.cfg; end; % general try, output.time = input.time; end; % for ERPs and TFRs try, output.freq = input.freq; end; % for frequency data if isfield(input, 'powspctrm') && isfield(input, 'crsspctrm') hascrsspctrm = 1; chandim = find(strcmp(inputdim, 'chan')); % concatenate powspctrm and crsspctrm % output.dat = cat(chandim, input.powspctrm, input.crsspctrm); % seperate output for auto and cross-spectra output.dat = input.powspctrm; output.crs = input.crsspctrm; % concatenate the labels of the channelcombinations into one Nx1 cell-array output.label = cmb2label([[input.label(:) input.label(:)]; input.labelcmb]); elseif isfield(input, 'powspctrm') hascrsspctrm = 0; % output only power spectrum output.dat = input.powspctrm; output.label = input.label; elseif isfield(input, 'fourierspctrm') hascrsspctrm = 0; % output only fourier spectrum output.dat = input.fourierspctrm; output.label = input.label; else hascrsspctrm = 0; try, output.dat = input.avg; end; % for average ERP try, output.dat = input.trial; end; % for average ERP with keeptrial try, output.dat = input.individual; end; % for grandaverage ERP with keepsubject output.label = input.label; end % determine the size of each dimension repldim = find(strcmp(inputdim, 'repl')); chandim = find(strcmp(inputdim, 'chan')); freqdim = find(strcmp(inputdim, 'freq')); timedim = find(strcmp(inputdim, 'time')); if isempty(repldim) Nrepl = 1; else Nrepl = size(output.dat, repldim); end if isempty(chandim) error('data must contain channels'); else if hascrsspctrm Nchan = size(output.dat, chandim) + size(output.crs, chandim); Ncrs = size(output.crs, chandim); else Nchan = size(output.dat, chandim); end end if isempty(freqdim) Nfreq = 1; else Nfreq = size(output.dat, freqdim); end if isempty(timedim) Ntime = 1; else Ntime = size(output.dat, timedim); end % find the overlapping dimensions in the input and output [dum, inputorder, outputorder] = intersect(inputdim, outputdim); % sort them according to the specified output dimensions [outputorder, indx] = sort(outputorder); inputorder = inputorder(indx); % rearrange the input dimensions in the same order as the desired output if ~all(inputorder==sort(inputorder)) if hascrsspctrm output.dat = permute(output.dat, inputorder); output.crs = permute(output.crs, inputorder); else output.dat = permute(output.dat, inputorder); end end % reshape the data so that it contains the (optional) singleton dimensions if ~(size(output.dat,1)==Nrepl && size(output.dat,2)==Nchan && size(output.dat,3)==Nfreq && size(output.dat,4)==Ntime) if hascrsspctrm output.dat = reshape(output.dat, Nrepl, Nchan-Ncrs, Nfreq, Ntime); output.crs = reshape(output.crs, Nrepl, Ncrs , Nfreq, Ntime); else output.dat = reshape(output.dat, Nrepl, Nchan, Nfreq, Ntime); end end if isfield(input,'dof') && numel(input.dof)==Nrepl*Nfreq*Ntime output.dof=reshape(input.dof, Nrepl, Nfreq, Ntime); end; % add the fields that describe the axes of the data if ~isfield(output, 'time') output.time = nan; end if ~isfield(output, 'freq') output.freq = nan; end % create replication axis, analogous to time and frequency axis output.repl = 1:Nrepl; output.dimord = 'repl_chan_freq_time'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION convert Nx2 cell array with channel combinations into Nx1 cell array with labels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label = cmb2label(labelcmb); label = {}; for i=1:size(labelcmb) label{i,1} = [labelcmb{i,1} '&' labelcmb{i,2}]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION convert Nx1 cell array with labels into N2x cell array with channel combinations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function labelcmb = label2cmb(label); labelcmb = {}; for i=1:length(label) labelcmb(i,1:2) = tokenize(label{i}, '&'); end
github
philippboehmsturm/antx-master
nan_std.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/nan_std.m
2,136
utf_8
52c60ccd6100ec10ad7c0acccd93c4d7
% nan_std() - std, not considering NaN values % % Usage: std across the first dimension % Author: Arnaud Delorme, CNL / Salk Institute, Sept 2003 %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA % 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: nan_std.m 952 2010-04-21 18:29:51Z roboos $ function out = nan_std(in) nans = find(isnan(in)); in(nans) = 0; nonnans = ones(size(in)); nonnans(nans) = 0; nonnans = sum(nonnans); nononnans = find(nonnans==0); nonnans(nononnans) = 1; out = sqrt((sum(in.^2)-sum(in).^2./nonnans)./(nonnans-1)); out(nononnans) = NaN;
github
philippboehmsturm/antx-master
inside_contour.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/inside_contour.m
1,106
utf_8
37d10e5d9a05c79551aac24c328e34aa
function bool = inside_contour(pos, contour); npos = size(pos,1); ncnt = size(contour,1); x = pos(:,1); y = pos(:,2); minx = min(x); miny = min(y); maxx = max(x); maxy = max(y); bool = true(npos,1); bool(x<minx) = false; bool(y<miny) = false; bool(x>maxx) = false; bool(y>maxy) = false; % the summed angle over the contour is zero if the point is outside, and 2*pi if the point is inside the contour % leave some room for inaccurate f critval = 0.1; % the remaining points have to be investigated with more attention sel = find(bool); for i=1:length(sel) contourx = contour(:,1) - pos(sel(i),1); contoury = contour(:,2) - pos(sel(i),2); angle = atan2(contoury, contourx); % angle = unwrap(angle); angle = my_unwrap(angle); total = sum(diff(angle)); bool(sel(i)) = (abs(total)>critval); end function x = my_unwrap(x) % this is a faster implementation of the MATLAB unwrap function % with hopefully the same functionality d = diff(x); indx = find(abs(d)>pi); for i=indx(:)' if d(i)>0 x((i+1):end) = x((i+1):end) - 2*pi; else x((i+1):end) = x((i+1):end) + 2*pi; end end
github
philippboehmsturm/antx-master
smudge.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/smudge.m
1,813
utf_8
1849e7e0cc093f5c7572cfa9de7fa8c8
function [datout, S] = smudge(datin, tri, niter) % SMUDGE(DATIN, TRI) computes a smudged version of the input data datain, % given a triangulation tri. The algorithm is according to what is in % MNE-Suite, documented in chapter 8.3 if nargin<3, niter = 1; end for k = 1:niter [tmp, Stmp] = do_smudge(datin, tri); if k==1, S = Stmp; else S = Stmp*S; end datout = tmp; datin = tmp; end function [datout, S] = do_smudge(datin, tri) % number of points npnt = numel(datin); % non-zero points nz = find(datin); % triangles containing non-zero points nzt = ismember(tri, nz); tnz = sum(nzt, 2)>0 & sum(nzt,2)<3; % points with non-zero neighbours nzn = tri(tnz, :); nzt = nzt(tnz, :); vec1 = zeros(size(nzn,1)*2,1); vec2 = zeros(size(nzn,1)*2,1); for k = 1:size(nzn,1) indx0 = (k-1)*2+(1:2); indx1 = nzn(k, nzt(k,:)); indx2 = nzn(k,~nzt(k,:)); vec1(indx0) = indx1; vec2(indx0) = indx2; end vecx = sortrows([vec1 vec2]); vecy = sortrows([vec2 vec1]); clear vec1 vec2; % in a closed surface the edges occur in doubles vecx = vecx(1:2:end,:); vecy = vecy(1:2:end,:); tmp = diff([0;vecx(:,1)])>0; begix = find([tmp;1]==1); uvecy = unique(vecy(:,1)); tmp = diff([0;vecy(:,1)])>0; nix = diff(find([tmp;1]==1)); nix(end+1:numel(uvecy)) = 1; tmpval = zeros(npnt,1); for k = 1:numel(uvecy) tmpval(uvecy(k)) = nix(k); end val = zeros(size(vecx,1),1); for k = 1:numel(val) val(k) = 1./tmpval(vecx(k,2)); end % allocate memory S = spalloc(npnt, npnt, numel(val)+numel(nz)); for k = 1:numel(begix)-1 indx1 = vecx(begix(k),1); indx2 = begix(k):(begix(k+1)-1); indx3 = vecx(indx2, 2); S(indx3, indx1) = val(indx2); %FIXME this can be speeded up by using the sparse command end S = S + spdiags(datin(:)>0, 0, npnt, npnt); datout = S*datin(:);
github
philippboehmsturm/antx-master
butter.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/butter.m
3,559
utf_8
ad82b4c04911a5ea11fd6bd2cc5fd590
% Copyright (C) 1999 Paul Kienzle % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % Generate a butterworth filter. % Default is a discrete space (Z) filter. % % [b,a] = butter(n, Wc) % low pass filter with cutoff pi*Wc radians % % [b,a] = butter(n, Wc, 'high') % high pass filter with cutoff pi*Wc radians % % [b,a] = butter(n, [Wl, Wh]) % band pass filter with edges pi*Wl and pi*Wh radians % % [b,a] = butter(n, [Wl, Wh], 'stop') % band reject filter with edges pi*Wl and pi*Wh radians % % [z,p,g] = butter(...) % return filter as zero-pole-gain rather than coefficients of the % numerator and denominator polynomials. % % [...] = butter(...,'s') % return a Laplace space filter, W can be larger than 1. % % [a,b,c,d] = butter(...) % return state-space matrices % % References: % % Proakis & Manolakis (1992). Digital Signal Processing. New York: % Macmillan Publishing Company. % Author: Paul Kienzle <[email protected]> % Modified by: Doug Stewart <[email protected]> Feb, 2003 function [a, b, c, d] = butter (n, W, varargin) if (nargin>4 || nargin<2) || (nargout>4 || nargout<2) usage ('[b, a] or [z, p, g] or [a,b,c,d] = butter (n, W [, "ftype"][,"s"])'); end % interpret the input parameters if (~(length(n)==1 && n == round(n) && n > 0)) error ('butter: filter order n must be a positive integer'); end stop = 0; digital = 1; for i=1:length(varargin) switch varargin{i} case 's', digital = 0; case 'z', digital = 1; case { 'high', 'stop' }, stop = 1; case { 'low', 'pass' }, stop = 0; otherwise, error ('butter: expected [high|stop] or [s|z]'); end end [r, c]=size(W); if (~(length(W)<=2 && (r==1 || c==1))) error ('butter: frequency must be given as w0 or [w0, w1]'); elseif (~(length(W)==1 || length(W) == 2)) error ('butter: only one filter band allowed'); elseif (length(W)==2 && ~(W(1) < W(2))) error ('butter: first band edge must be smaller than second'); end if ( digital && ~all(W >= 0 & W <= 1)) error ('butter: critical frequencies must be in (0 1)'); elseif ( ~digital && ~all(W >= 0 )) error ('butter: critical frequencies must be in (0 inf)'); end % Prewarp to the band edges to s plane if digital T = 2; % sampling frequency of 2 Hz W = 2/T*tan(pi*W/T); end % Generate splane poles for the prototype butterworth filter % source: Kuc C = 1; % default cutoff frequency pole = C*exp(1i*pi*(2*[1:n] + n - 1)/(2*n)); if mod(n,2) == 1, pole((n+1)/2) = -1; end % pure real value at exp(i*pi) zero = []; gain = C^n; % splane frequency transform [zero, pole, gain] = sftrans(zero, pole, gain, W, stop); % Use bilinear transform to convert poles to the z plane if digital [zero, pole, gain] = bilinear(zero, pole, gain, T); end % convert to the correct output form if nargout==2, a = real(gain*poly(zero)); b = real(poly(pole)); elseif nargout==3, a = zero; b = pole; c = gain; else % output ss results [a, b, c, d] = zp2ss (zero, pole, gain); end
github
philippboehmsturm/antx-master
convert_event.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/convert_event.m
7,799
utf_8
085ea530f797f7d529ce94b743fd110a
function [obj] = convert_event(obj, target, varargin) % CONVERT_EVENT converts between the different representations of events, % which can be % 1) event structure, see FT_READ_EVENT % 2) matrix representation as in trl (Nx3), see FT_DEFINETRIAL % 3) matrix representation as in artifact (Nx2), see FT_ARTIFACT_xxx % 4) boolean vector representation with 1 for samples containing trial/artifact % % Use as % [object] = convert_event(object, target, ....) % % Possible input objects types are % event structure % Nx3 trl matrix, or cell array of multiple trl definitions % Nx2 artifact matrix, or cell array of multiple artifact definitions % boolean vector, or matrix with multiple vectors as rows % % Possible targets are 'event', 'trl', 'artifact', 'boolvec' % % Additional options should be specified in key-value pairs and can be % 'endsample' = % 'typenames' = % % See READ_EVENT, DEFINETRIAL, REJECTARTIFACT, ARTIFACT_xxx % Copyright (C) 2009, Ingrid Nieuwenhuis % % 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: convert_event.m 3659 2011-06-09 12:57:09Z roboos $ % Check if target is specified correctly if sum(strcmp(target, {'event', 'trl', 'artifact', 'boolvec'})) < 1 error('target has to be ''event'', ''trl'', ''artifact'', or ''boolvec''.') end % Get the options endsample = keyval('endsample', varargin); typenames = keyval('typenames', varargin); % Determine what the input object is if isempty(obj) input_obj = 'empty'; elseif isstruct(obj) input_obj = 'event'; elseif iscell(obj) if isempty(obj{1}) input_obj = 'empty'; elseif size(obj{1},2) == 3 input_obj = 'trl'; elseif size(obj{1},2) == 2 input_obj = 'artifact'; elseif size(obj{1},2) > 3 % could be a strange trl-matrix with multiple columns input_obj = 'trl'; for i = 1:length(obj) obj{i} = obj{i}(:,1:3); end else error('incorrect input object, see help for what is allowed.') end elseif islogical(obj) input_obj = 'boolvec'; elseif size(obj,2) == 3 input_obj = 'trl'; elseif size(obj,2) == 2 input_obj = 'artifact'; elseif size(obj,2) > 3 tmp = unique(obj); if isempty(find(tmp>2, 1)) input_obj = 'boolvec'; obj = logical(obj); else %it is at least not boolean but could be a strange %trl-matrix with multiple columns input_obj = 'trl'; obj = obj(:,1:3); end else error('incorrect input object, see help for what is allowed.') end % do conversion if (strcmp(input_obj, 'trl') || strcmp(input_obj, 'artifact') || strcmp(input_obj, 'empty')) && strcmp(target, 'boolvec') if ~isempty(endsample) obj = artifact2artvec(obj,endsample); else obj = artifact2artvec(obj); end elseif strcmp(input_obj, 'boolvec') && strcmp(target,'artifact' ) obj = artvec2artifact(obj); elseif strcmp(input_obj, 'boolvec') && strcmp(target,'trl' ) obj = artvec2artifact(obj); if iscell(obj) for i=1:length(obj) obj{i}(:,3) = 0; end else obj(:,3) = 0; end elseif (strcmp(input_obj, 'trl') || strcmp(input_obj, 'artifact')) && strcmp(target, 'event') obj = artifact2event(obj, typenames); elseif strcmp(input_obj, 'artifact') && strcmp(target,'trl') if iscell(obj) for i=1:length(obj) obj{i}(:,3) = 0; end else obj(:,3) = 0; end elseif strcmp(input_obj, 'trl') && strcmp(target,'artifact') if iscell(obj) for i=1:length(obj) obj{i}(:,3:end) = []; end else obj(:,3:end) = []; end elseif strcmp(input_obj, 'empty') obj = []; else warning('conversion not supported yet') %FIXME end %%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function artvec = artifact2artvec(varargin) % ARTIFACT2ARTVEC makes boolian vector (or matrix when artifact is % cell array of multiple artifact definitions) with 0 for artifact free % sample and 1 for sample containing an artifact according to artifact % specification. Length of vector is (from sample 1) last sample as % defined in the artifact definition, or when datendsample is speciefied % vector is length datendsample. artifact = varargin{1}; if length(varargin) == 1 if ~iscell(artifact) % assume only one artifact is given if isempty(artifact) error('When input object is empty ''endsample'' must be specified to convert into boolvec') else endsample = max(artifact(:,2)); end elseif length(artifact) == 1 if isempty(artifact{1}) error('When input object is empty ''endsample'' must be specified to convert into boolvec') else endsample = max(artifact{1}(:,2)); end else error('when giving multiple artifact definitions, endsample should be specified to assure all output vectors are of the same length') end elseif length(varargin) == 2 endsample = varargin{2}; elseif length(varargin) > 2 error('too many input arguments') end if ~iscell(artifact) artifact = {artifact}; end % make artvec artvec = zeros(length(artifact), endsample); breakflag = 0; for i=1:length(artifact) for j=1:size(artifact{i},1) artbegsample = artifact{i}(j,1); artendsample = artifact{i}(j,2); if artbegsample > endsample warning('artifact definition contains later samples than endsample, these samples are ignored') break elseif artendsample > endsample warning('artifact definition contains later samples than endsample, these samples are ignored') artendsample = endsample; breakflag = 1; end artvec(i, artbegsample:artendsample) = 1; if breakflag break end end end %%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function artifact = artvec2artifact(artvec) % ARTVEC2ARTIFACT makes artifact definition (or cell array of artifact % definitions) from boolian vector (or matrix) with [artbegsample % artendsample]. Assumed is that the artvec starts with sample 1. for i=1:size(artvec,1) tmp = diff([0 artvec(i,:) 0]); artbeg = find(tmp==+1); artend = find(tmp==-1) - 1; artifact{i} = [artbeg' artend']; end if length(artifact) == 1 artifact = artifact{1}; end %%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function event = artifact2event(artifact, typenames) % ARTIFACT2EVENT makes event structure from artifact definition (or cell % array of artifact definitions). event.type is always 'artifact', but % incase of cellarays of artifacts is is also possible to hand 'typenames' % with length(artifact) if ~iscell(artifact) artifact = {artifact}; end if ~isempty(typenames) if length(artifact) ~= length(typenames) error('length typenames should be the same as length artifact') end end event = []; for i=1:length(artifact) for j=1:size(artifact{i},1) event(end+1).sample = artifact{i}(j,1); event(end ).duration = artifact{i}(j,2)-artifact{i}(j,1)+1; if ~isempty(typenames) event(end).type = typenames{i}; elseif size(artifact{i},2) == 2 event(end).type = 'artifact'; elseif size(artifact{i},2) == 3 event(end).type = 'trial'; end event(end ).value = []; event(end ).offset = []; end end
github
philippboehmsturm/antx-master
fdr.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/fdr.m
1,986
utf_8
31fd6bf82e890dc9f35f19d8b7e7e216
function [h] = fdr(p, q); % FDR false discovery rate % % Use as % h = fdr(p, q) % % This implements % Genovese CR, Lazar NA, Nichols T. % Thresholding of statistical maps in functional neuroimaging using the false discovery rate. % Neuroimage. 2002 Apr;15(4):870-8. % 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: fdr.m 952 2010-04-21 18:29:51Z roboos $ % convert the input into a row vector dim = size(p); p = reshape(p, 1, numel(p)); % sort the observed uncorrected probabilities [ps, indx] = sort(p); % count the number of voxels V = length(p); % compute the threshold probability for each voxel pi = ((1:V)/V) * q / c(V); h = (ps<=pi); % undo the sorting [dum, unsort] = sort(indx); h = h(unsort); % convert the output back into the original format h = reshape(h, dim); function s = c(V) % See Genovese, Lazar and Holmes (2002) page 872, second column, first paragraph if V<1000 % compute it exactly s = sum(1./(1:V)); else % approximate it s = log(V) + 0.57721566490153286060651209008240243104215933593992359880576723488486772677766467093694706329174674951463144724980708248096050401448654283622417399764492353625350033374293733773767394279259525824709491600873520394816567; end
github
philippboehmsturm/antx-master
sensortype.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/sensortype.m
6,228
utf_8
57b1d940539a84b81ad94d5a1f07a8d7
function [type] = sensortype(grad) % SENSORTYPE returns a string that describes the type of sensors (EEG or MEG) % and the manufacturer of the MEG system. The heuristic approach is to test % the input sensor definition on a few features (like number of channels, % number of coils, etc.) and score points for each of them. The system that % is most "similar" wins. % % Use as % [str] = sensortype(sens) % where the input is a electrode or gradiometer structure, or % [str] = sensortype(data) % where the input data structure should contain either a data.grad % or a data.elec field. % % The output will be a string % 'electrode' % 'ctf151' % 'ctf275' % 'ctf151_planar' % 'ctf275_planar' % 'neuromag122' % 'neuromag306' % 'magnetometer' % 'bti148' % 'yokogawa160' % Copyright (C) 2004-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: sensortype.m 952 2010-04-21 18:29:51Z roboos $ % the input may be a data structure which then contains a grad/elec structure if isfield(grad, 'grad') grad = grad.grad; elseif isfield(grad, 'elec') grad = grad.elec; end if isfield(grad, 'label') && isfield(grad, 'pnt') && ~isfield(grad, 'ori') % the input looks like an electrode system type = 'electrode'; return; end % detect the different MEG sensor types description = { 'ctf151' % 1 'ctf275' % 2 'ctf151_planar' % 3 'ctf275_planar' % 4 'neuromag122' % 5 'neuromag306' % 6 'magnetometer' % 7 'bti148' % 8 'yokogawa160' % 9 }; % start with an empty counter for each system similar = zeros(size(description)); % look at the number of channels Nchan = length(grad.label); similar(1) = similar(1) + (abs(Nchan-151) < 20); similar(2) = similar(2) + (abs(Nchan-275) < 20); similar(3) = similar(3) + (abs(Nchan-151*2) < 20); similar(4) = similar(4) + (abs(Nchan-275*2) < 20); similar(5) = similar(5) + (abs(Nchan-122) < 20); similar(6) = similar(6) + (abs(Nchan-306) < 20); similar(8) = similar(8) + (abs(Nchan-148) < 20); similar(9) = similar(9) + (abs(Nchan-160) < 20); similar(1) = similar(1) + (abs(Nchan-151) <= abs(Nchan-275)); similar(2) = similar(2) + (abs(Nchan-275) <= abs(Nchan-151)); similar(3) = similar(3) + (abs(Nchan-151*2) <= abs(Nchan-2*275)); similar(4) = similar(4) + (abs(Nchan-275*2) <= abs(Nchan-2*151)); similar(5) = similar(5) + (abs(Nchan-122) <= abs(Nchan-306)); similar(6) = similar(6) + (abs(Nchan-306) <= abs(Nchan-122)); % look at the beginning of BTi channel names similar(8) = similar(8) + length(find(strmatch('A', grad.label))); similar(8) = similar(8) - length(find(~strmatch('A', grad.label))); % penalty % look at the beginning of Neuromag channel names similar(5) = similar(5) + length(find(strmatch('MEG', grad.label))); similar(6) = similar(6) + length(find(strmatch('MEG', grad.label))); similar(7) = similar(7) + length(find(strmatch('MEG', grad.label))); similar(5) = similar(5) - length(find(~strmatch('MEG', grad.label))); % penalty similar(6) = similar(6) - length(find(~strmatch('MEG', grad.label))); % penalty similar(7) = similar(7) - length(find(~strmatch('MEG', grad.label))); % penalty % look at the beginning of CTF channel names similar(1) = similar(1) + length(find(strmatch('MZ', grad.label))); similar(2) = similar(2) + length(find(strmatch('MZ', grad.label))); similar(3) = similar(3) + length(find(strmatch('MZ', grad.label))); similar(4) = similar(4) + length(find(strmatch('MZ', grad.label))); similar(5) = similar(5) - length(find(strmatch('MZ', grad.label))); % penalty similar(6) = similar(6) - length(find(strmatch('MZ', grad.label))); % penalty similar(7) = similar(7) - length(find(strmatch('MZ', grad.label))); % penalty similar(8) = similar(8) - length(find(strmatch('MZ', grad.label))); % penalty % look at whether the names contain _dH and _dV similar(3) = similar(3) + length(find(a_strmatch('_dH', grad.label))); similar(3) = similar(3) + length(find(a_strmatch('_dV', grad.label))); similar(4) = similar(4) + length(find(a_strmatch('_dH', grad.label))); similar(4) = similar(4) + length(find(a_strmatch('_dV', grad.label))); % if they do not contain any _dH or _dV, the planar CTF systems is less likely that their axial counterpart similar(3) = similar(3) - (length(find(a_strmatch('_dH', grad.label)))==0); similar(3) = similar(3) - (length(find(a_strmatch('_dV', grad.label)))==0); similar(4) = similar(4) - (length(find(a_strmatch('_dH', grad.label)))==0); similar(4) = similar(4) - (length(find(a_strmatch('_dV', grad.label)))==0); try % a magnetometer or a BTi system must have the same number of coils as labels similar(7) = similar(7) * (length(grad.label)==length(grad.pnt)); similar(8) = similar(8) * (length(grad.label)==length(grad.pnt)); end % determine to which MEG ssytem the input data is the most similar [m, i] = max(similar); if m==0 || length(find(similar==m))>1 warning('could not determine the type of MEG system'); type = 'unknown'; else type = description{i}; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION search for substring in each element of a cell-array %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function a = a_strmatch(str, strs) a = zeros(length(strs),1); for i=1:length(strs) a(i) = ~isempty(strfind(strs{i}, str)); end a = find(a);
github
philippboehmsturm/antx-master
read_labview_dtlg.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/read_labview_dtlg.m
5,153
utf_8
2e41342bc1812c6740bf980c358c923b
function [dat] = read_labview_dtlg(filename, datatype); % READ_LABVIEW_DTLG % % Use as % dat = read_labview_dtlg(filename, datatype) % where datatype can be 'int32' or 'int16' % % The output of this function is a structure. % Copyright (C) 2007, 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_labview_dtlg.m 2885 2011-02-16 09:41:58Z roboos $ fid = fopen(filename, 'r', 'ieee-be'); header = fread(fid, 4, 'uint8=>char')'; if ~strcmp(header, 'DTLG') error('unsupported file, header should start with DTLG'); end version = fread(fid, 4, 'char')'; % clear version nd = fread(fid, 1, 'int32'); p = fread(fid, 1, 'int32'); % the following seems to work for files with version [7 0 128 0] % but in files files with version [8 0 128 0] the length of the descriptor is not correct ld = fread(fid, 1, 'int16'); descriptor = fread(fid, ld, 'uint8=>char')'; % ROBOOS: the descriptor should ideally be decoded, since it contains the variable % name, type and size % The first offset block always starts immediately after the data descriptor (at offset p, which should ideally be equal to 16+ld) if nd<=128 % The first offset block contains the offsets for all data sets. % In this case P points to the start of the offset block. fseek(fid, p, 'bof'); offset = fread(fid, 128, 'uint32')'; else % The first offset block contains the offsets for the first 128 data sets. % The entries for the remaining data sets are stored in additional offset blocks. % The locations of those blocks are contained in a block table starting at P. offset = []; fseek(fid, p, 'bof'); additional = fread(fid, 128, 'uint32'); for i=1:sum(additional>0) fseek(fid, additional(i), 'bof'); tmp = fread(fid, 128, 'uint32')'; offset = cat(2, offset, tmp); end clear additional i tmp end % ROBOOS: remove the zeros in the offset array for non-existing datasets offset = offset(1:nd); % ROBOOS: how to determine the data datatype? switch datatype case 'uint32' datasize = 4; case 'int32' datasize = 4; case 'uint16' datasize = 2; case 'int16' datasize = 2; otherwise error('unsupported datatype'); end % If the data sets are n-dimensional arrays, the first n u32 longwords in each data % set contain the array dimensions, imediately followed by the data values. % ROBOOS: how to determine whether they are n-dimensional arrays? % determine the number of dimensions by looking at the first array % assume that all subsequent arrays have the same number of dimensions if nd>1 estimate = (offset(2)-offset(1)); % initial estimate for the number of datasize in the array fseek(fid, offset(1), 'bof'); n = fread(fid, 1, 'int32'); while mod(estimate-4*length(n), (datasize*prod(n)))~=0 % determine the number and size of additional array dimensions n = cat(1, n, fread(fid, 1, 'int32')); if datasize*prod(n)>estimate error('could not determine array size'); end end ndim = length(n); clear estimate n else estimate = filesize(fid)-offset; fseek(fid, offset(1), 'bof'); n = fread(fid, 1, 'int32'); while mod(estimate-4*length(n), (datasize*prod(n)))~=0 % determine the number and size of additional array dimensions n = cat(1, n, fread(fid, 1, 'int32')); if datasize*prod(n)>estimate error('could not determine array size'); end end ndim = length(n); clear estimate n end % read the dimensions and the data from each array for i=1:nd fseek(fid, offset(i), 'bof'); n = fread(fid, ndim, 'int32')'; % Labview uses the C-convention for storing data, and Matlab uses the Fortran convention n = fliplr(n); data{i} = fread(fid, n, datatype); end clear i n ndim fclose(fid); % put all local variables into a structure, this is a bit unusual programming style % the output structure is messy, but contains all relevant information tmp = whos; dat = []; for i=1:length(tmp) if isempty(strmatch(tmp(i).name, {'tmp', 'fid', 'ans', 'handles'})) dat = setfield(dat, tmp(i).name, eval(tmp(i).name)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % local helper function to determine the size of the file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function siz = filesize(fid) fp = ftell(fid); fseek(fid, 0, 'eof'); siz = ftell(fid); fseek(fid, fp, 'bof');
github
philippboehmsturm/antx-master
clusterstat.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/private/clusterstat.m
34,032
utf_8
2b7ff73fc26dcb327eb4fe0c3863fc0f
function [stat, cfg] = clusterstat(cfg, statrnd, statobs, varargin) % SUBFUNCTION for computing cluster statistic for N-D volumetric source data % or for channel-freq-time data % % This function uses % cfg.dim % cfg.inside (only for source data) % cfg.tail = -1, 0, 1 % cfg.multivariate = no, yes % cfg.orderedstats = no, yes % cfg.clusterstatistic = max, maxsize, maxsum, wcm % cfg.clusterthreshold = parametric, nonparametric_individual, nonparametric_common % cfg.clusteralpha % cfg.clustercritval % cfg.wcm_weight % cfg.feedback % Copyright (C) 2005-2007, 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: clusterstat.m 3876 2011-07-20 08:04:29Z jorhor $ % set the defaults if ~isfield(cfg,'orderedstats'), cfg.orderedstats = 'no'; end if ~isfield(cfg,'multivariate'), cfg.multivariate = 'no'; end if ~isfield(cfg,'minnbchan'), cfg.minnbchan=0; end % if ~isfield(cfg,'channeighbstructmat'), cfg.channeighbstructmat=[]; end % if ~isfield(cfg,'chancmbneighbstructmat'), cfg.chancmbneighbstructmat=[]; end % if ~isfield(cfg,'chancmbneighbselmat'), cfg.chancmbneighbselmat=[]; end % get issource from varargin, to determine source-data-specific options and allow the proper usage of cfg.neighbours % (cfg.neighbours was previously used in determining wheter source-data was source data or not) set to zero by default % note, this may cause problems when functions call clusterstat without giving issource, as issource was previously % set in clusterstat.m but has now been transfered to the function that calls clusterstat.m (but only implemented in statistics_montecarlo) issource = keyval('issource', varargin); if isempty(issource), issource = 0; end if cfg.tail~=cfg.clustertail error('cfg.tail and cfg.clustertail should be identical') end % create neighbour structure (but only when not using source data) if isfield(cfg, 'neighbours') && ~issource channeighbstructmat = makechanneighbstructmat(cfg); end % perform fixinside fix if input data is source data if issource % cfg contains dim and inside that are needed for reshaping the data to a volume, and inside should behave as a index vector cfg = fixinside(cfg, 'index'); end needpos = cfg.tail==0 || cfg.tail== 1; needneg = cfg.tail==0 || cfg.tail==-1; Nsample = size(statrnd,1); Nrand = size(statrnd,2); prb_pos = ones(Nsample, 1); prb_neg = ones(Nsample, 1); postailobs = false(Nsample, 1); % this holds the thresholded values negtailobs = false(Nsample, 1); % this holds the thresholded values postailrnd = false(Nsample,Nrand); % this holds the thresholded values negtailrnd = false(Nsample,Nrand); % this holds the thresholded values Nobspos = 0; % number of positive clusters in observed data Nobsneg = 0; % number of negative clusters in observed data if strcmp(cfg.clusterthreshold, 'parametric') % threshold based on the critical value from parametric distribution siz = size(cfg.clustercritval); if all(siz==1) && cfg.clustertail==0 % it only specifies one critical value, assume that the left and right tail are symmetric around zero negtailcritval = -cfg.clustercritval; postailcritval = cfg.clustercritval; elseif all(siz==1) && cfg.clustertail==-1 % it only specifies one critical value corresponding to the left tail negtailcritval = cfg.clustercritval; postailcritval = +inf * ones(size(negtailcritval)); elseif all(siz==1) && cfg.clustertail==1 % it only specifies one critical value corresponding to the right tail postailcritval = cfg.clustercritval; negtailcritval = -inf * ones(size(postailcritval)); elseif siz(1)==Nsample && siz(2)==1 && cfg.clustertail==0 % it specifies a single critical value for each sample, assume that the left and right tail are symmetric around zero negtailcritval = -cfg.clustercritval; postailcritval = cfg.clustercritval; elseif siz(1)==Nsample && siz(2)==1 && cfg.clustertail==-1 % it specifies a critical value for the left tail % which is different for each sample (samples have a different df) negtailcritval = cfg.clustercritval; postailcritval = +inf * ones(size(negtailcritval)); elseif siz(1)==Nsample && siz(2)==1 && cfg.clustertail==1 % it specifies a critical value for the right tail % which is different for each sample (samples have a different df) postailcritval = cfg.clustercritval; negtailcritval = +inf * ones(size(postailcritval)); elseif siz(1)==Nsample && siz(2)==2 && cfg.clustertail==0 % it specifies a critical value for the left and for the right tail of the distribution % which is different for each sample (samples have a different df) negtailcritval = cfg.clustercritval(:,1); postailcritval = cfg.clustercritval(:,2); elseif prod(siz)==2 && cfg.clustertail==0 % it specifies a critical value for the left and for the right tail of the distribution % which is the same for each sample (samples have the same df) negtailcritval = cfg.clustercritval(1); postailcritval = cfg.clustercritval(2); else error('cannot make sense out of the specified parametric critical values'); end elseif strcmp(cfg.clusterthreshold, 'nonparametric_individual') % threshold based on bootstrap using all other randomizations % each voxel will get an individual threshold [srt, ind] = sort(statrnd,2); if cfg.clustertail==0 % both tails are needed negtailcritval = srt(:,round(( cfg.clusteralpha/2)*size(statrnd,2))); postailcritval = srt(:,round((1-cfg.clusteralpha/2)*size(statrnd,2))); elseif cfg.clustertail==1 % only positive tail is needed postailcritval = srt(:,round((1-cfg.clusteralpha)*size(statrnd,2))); negtailcritval = -inf * ones(size(postailcritval)); elseif cfg.clustertail==1 % only negative tail is needed negtailcritval = srt(:,round(( cfg.clusteralpha)*size(statrnd,2))); postailcritval = +inf * ones(size(negtailcritval)); end elseif strcmp(cfg.clusterthreshold, 'nonparametric_common') % threshold based on bootstrap using all other randomizations % all voxels will get a common threshold [srt, ind] = sort(statrnd(:)); if cfg.clustertail==0 % both tails are needed negtailcritval = srt(round(( cfg.clusteralpha/2)*prod(size(statrnd)))); postailcritval = srt(round((1-cfg.clusteralpha/2)*prod(size(statrnd)))); elseif cfg.clustertail==1 % only positive tail is needed postailcritval = srt(round((1-cfg.clusteralpha)*prod(size(statrnd)))); negtailcritval = -inf * ones(size(postailcritval)); elseif cfg.clustertail==1 % only negative tail is needed negtailcritval = srt(round(( cfg.clusteralpha)*prod(size(statrnd)))); postailcritval = +inf * ones(size(negtailcritval)); end else error('no valid threshold for clustering was given') end % determine clusterthreshold % these should be scalars or column vectors negtailcritval = negtailcritval(:); postailcritval = postailcritval(:); % remember the critical values cfg.clustercritval = [negtailcritval postailcritval]; % test whether the observed and the random statistics exceed the threshold postailobs = (statobs >= postailcritval); negtailobs = (statobs <= negtailcritval); for i=1:Nrand postailrnd(:,i) = (statrnd(:,i) >= postailcritval); negtailrnd(:,i) = (statrnd(:,i) <= negtailcritval); end % first do the clustering on the observed data if needpos, if issource if isfield(cfg, 'origdim'), cfg.dim = cfg.origdim; end %this snippet is to support correct clustering of N-dimensional data, not fully tested yet tmp = zeros(cfg.dim); tmp(cfg.inside) = postailobs; if length(cfg.dim) == 3 % if source data (3D) ft_hastoolbox('spm8',1); [posclusobs, posnum] = spm_bwlabel(tmp, 6); % use spm_bwlabel for source data to avoid usage of image toolbox else posclusobs = bwlabeln(tmp, conndef(length(cfg.dim),'min')); % spm_bwlabel yet (feb 2011) supports only up to 3-D data end posclusobs = posclusobs(cfg.inside); else if 0 posclusobs = findcluster(reshape(postailobs, [cfg.dim,1]),cfg.chancmbneighbstructmat,cfg.chancmbneighbselmat,cfg.minnbchan); else posclusobs = findcluster(reshape(postailobs, [cfg.dim,1]),channeighbstructmat,cfg.minnbchan); end posclusobs = posclusobs(:); end Nobspos = max(posclusobs); % number of clusters exceeding the threshold fprintf('found %d positive clusters in observed data\n', Nobspos); end if needneg, if issource tmp = zeros(cfg.dim); tmp(cfg.inside) = negtailobs; if length(cfg.dim) == 3 % if source data (3D) ft_hastoolbox('spm8',1); [negclusobs, negnum] = spm_bwlabel(tmp, 6); % use spm_bwlabel for source data to avoid usage of image toolbox else negclusobs = bwlabeln(tmp, conndef(length(cfg.dim),'min')); % spm_bwlabel yet (feb 2011) supports only up to 3D data end negclusobs = negclusobs(cfg.inside); else if 0 negclusobs = findcluster(reshape(negtailobs, [cfg.dim,1]),cfg.chancmbneighbstructmat,cfg.chancmbneighbselmat,cfg.minnbchan); else negclusobs = findcluster(reshape(negtailobs, [cfg.dim,1]),channeighbstructmat,cfg.minnbchan); end negclusobs = negclusobs(:); end Nobsneg = max(negclusobs); fprintf('found %d negative clusters in observed data\n', Nobsneg); end stat = []; stat.stat = statobs; % catch situation where no clustering of the random data is needed if (Nobspos+Nobsneg)==0 warning('no clusters were found in the observed data'); stat.prob = ones(Nsample, 1); return end % allocate space to hold the randomization distributions of the cluster statistic if strcmp(cfg.multivariate, 'yes') || strcmp(cfg.orderedstats, 'yes') fprintf('allocating space for a %d-multivariate distribution of the positive clusters\n', Nobspos); fprintf('allocating space for a %d-multivariate distribution of the negative clusters\n', Nobsneg); posdistribution = zeros(Nobspos,Nrand); % this holds the multivariate randomization distribution of the positive cluster statistics negdistribution = zeros(Nobsneg,Nrand); % this holds the multivariate randomization distribution of the negative cluster statistics else posdistribution = zeros(1,Nrand); % this holds the statistic of the largest positive cluster in each randomization negdistribution = zeros(1,Nrand); % this holds the statistic of the largest negative cluster in each randomization end % do the clustering on the randomized data ft_progress('init', cfg.feedback, 'computing clusters in randomization'); for i=1:Nrand ft_progress(i/Nrand, 'computing clusters in randomization %d from %d\n', i, Nrand); if needpos, if issource tmp = zeros(cfg.dim); tmp(cfg.inside) = postailrnd(:,i); if length(cfg.dim) == 3 % if source data (3D) [posclusrnd, posrndnum] = spm_bwlabel(tmp, 6); % use spm_bwlabel for source data to avoid usage of image toolbox else posclusrnd = bwlabeln(tmp, conndef(length(cfg.dim),'min')); % spm_bwlabel yet (feb 2011) supports only up to 3D data end posclusrnd = posclusrnd(cfg.inside); else if 0 posclusrnd = findcluster(reshape(postailrnd(:,i), [cfg.dim,1]),cfg.chancmbneighbstructmat,cfg.chancmbneighbselmat,cfg.minnbchan); else posclusrnd = findcluster(reshape(postailrnd(:,i), [cfg.dim,1]),channeighbstructmat,cfg.minnbchan); end posclusrnd = posclusrnd(:); end Nrndpos = max(posclusrnd); % number of clusters exceeding the threshold stat = zeros(1,Nrndpos); % this will hold the statistic for each cluster % fprintf('found %d positive clusters in this randomization\n', Nrndpos); for j = 1:Nrndpos if strcmp(cfg.clusterstatistic, 'max'), stat(j) = max(statrnd(find(posclusrnd==j),i)); elseif strcmp(cfg.clusterstatistic, 'maxsize'), stat(j) = length(find(posclusrnd==j)); elseif strcmp(cfg.clusterstatistic, 'maxsum'), stat(j) = sum(statrnd(find(posclusrnd==j),i)); elseif strcmp(cfg.clusterstatistic, 'wcm'), stat(j) = sum((statrnd(find(posclusrnd==j),i)-postailcritval).^cfg.wcm_weight); else error('unknown clusterstatistic'); end end % for 1:Nrdnpos if strcmp(cfg.multivariate, 'yes') || strcmp(cfg.orderedstats, 'yes') stat = sort(stat, 'descend'); % sort them from most positive to most negative if Nrndpos>Nobspos posdistribution(:,i) = stat(1:Nobspos); % remember the largest N clusters else posdistribution(1:Nrndpos,i) = stat; % remember the largest N clusters end else % univariate -> remember the most extreme cluster if ~isempty(stat), posdistribution(i) = max(stat); end end end % needpos if needneg, if issource tmp = zeros(cfg.dim); tmp(cfg.inside) = negtailrnd(:,i); if length(cfg.dim) == 3 % if source data (3D) [negclusrnd, negrndnum] = spm_bwlabel(tmp, 6); % use spm_bwlabel for source data to avoid usage of image toolbox else negclusrnd = bwlabeln(tmp, conndef(length(cfg.dim),'min')); % spm_bwlabel yet (feb 2011) supports only up to 3D data end negclusrnd = negclusrnd(cfg.inside); else if 0 negclusrnd = findcluster(reshape(negtailrnd(:,i), [cfg.dim,1]),cfg.chancmbneighbstructmat,cfg.chancmbneighbselmat,cfg.minnbchan); else negclusrnd = findcluster(reshape(negtailrnd(:,i), [cfg.dim,1]),channeighbstructmat,cfg.minnbchan); end negclusrnd = negclusrnd(:); end Nrndneg = max(negclusrnd); % number of clusters exceeding the threshold stat = zeros(1,Nrndneg); % this will hold the statistic for each cluster % fprintf('found %d negative clusters in this randomization\n', Nrndneg); for j = 1:Nrndneg if strcmp(cfg.clusterstatistic, 'max'), stat(j) = min(statrnd(find(negclusrnd==j),i)); elseif strcmp(cfg.clusterstatistic, 'maxsize'), stat(j) = -length(find(negclusrnd==j)); % encode the size of a negative cluster as a negative value elseif strcmp(cfg.clusterstatistic, 'maxsum'), stat(j) = sum(statrnd(find(negclusrnd==j),i)); elseif strcmp(cfg.clusterstatistic, 'wcm'), stat(j) = -sum((abs(statrnd(find(negclusrnd==j),i)-negtailcritval)).^cfg.wcm_weight); % encoded as a negative value else error('unknown clusterstatistic'); end end % for 1:Nrndneg if strcmp(cfg.multivariate, 'yes') || strcmp(cfg.orderedstats, 'yes') stat = sort(stat, 'ascend'); % sort them from most negative to most positive if Nrndneg>Nobsneg negdistribution(:,i) = stat(1:Nobsneg); % remember the most extreme clusters, i.e. the most negative else negdistribution(1:Nrndneg,i) = stat; % remember the most extreme clusters, i.e. the most negative end else % univariate -> remember the most extreme cluster, which is the most negative if ~isempty(stat), negdistribution(i) = min(stat); end end end % needneg end % for 1:Nrand ft_progress('close'); % compare the values for the observed clusters with the randomization distribution if needpos, posclusters = []; stat = zeros(1,Nobspos); for j = 1:Nobspos if strcmp(cfg.clusterstatistic, 'max'), stat(j) = max(statobs(find(posclusobs==j))); elseif strcmp(cfg.clusterstatistic, 'maxsize'), stat(j) = length(find(posclusobs==j)); elseif strcmp(cfg.clusterstatistic, 'maxsum'), stat(j) = sum(statobs(find(posclusobs==j))); elseif strcmp(cfg.clusterstatistic, 'wcm'), stat(j) = sum((statobs(find(posclusobs==j))-postailcritval).^cfg.wcm_weight); else error('unknown clusterstatistic'); end end % sort the clusters based on their statistical value [stat, indx] = sort(stat,'descend'); % reorder the cluster indices in the data tmp = zeros(size(posclusobs)); for j=1:Nobspos tmp(find(posclusobs==indx(j))) = j; end posclusobs = tmp; if strcmp(cfg.multivariate, 'yes') % estimate the probability of the mutivariate tail, i.e. one p-value for all clusters prob = 0; for i=1:Nrand % compare all clusters simultaneosuly prob = prob + any(posdistribution(:,i)>stat(:)); end prob = prob/Nrand; for j = 1:Nobspos % collect a summary of the cluster properties posclusters(j).prob = prob; posclusters(j).clusterstat = stat(j); end % collect the probabilities in one large array prb_pos(find(posclusobs~=0)) = prob; elseif strcmp(cfg.orderedstats, 'yes') % compare the Nth ovbserved cluster against the randomization distribution of the Nth cluster prob = zeros(1,Nobspos); for j = 1:Nobspos prob(j) = sum(posdistribution(j,:)>stat(j))/Nrand; % collect a summary of the cluster properties posclusters(j).prob = prob(j); posclusters(j).clusterstat = stat(j); % collect the probabilities in one large array prb_pos(find(posclusobs==j)) = prob(j); end else % univariate -> each cluster has it's own probability prob = zeros(1,Nobspos); for j = 1:Nobspos prob(j) = sum(posdistribution>stat(j))/Nrand; % collect a summary of the cluster properties posclusters(j).prob = prob(j); posclusters(j).clusterstat = stat(j); % collect the probabilities in one large array prb_pos(find(posclusobs==j)) = prob(j); end end end if needneg, negclusters = []; stat = zeros(1,Nobsneg); for j = 1:Nobsneg if strcmp(cfg.clusterstatistic, 'max'), stat(j) = min(statobs(find(negclusobs==j))); elseif strcmp(cfg.clusterstatistic, 'maxsize'), stat(j) = -length(find(negclusobs==j)); % encode the size of a negative cluster as a negative value elseif strcmp(cfg.clusterstatistic, 'maxsum'), stat(j) = sum(statobs(find(negclusobs==j))); elseif strcmp(cfg.clusterstatistic, 'wcm'), stat(j) = -sum((abs(statobs(find(negclusobs==j))-negtailcritval)).^cfg.wcm_weight); % encoded as a negative value else error('unknown clusterstatistic'); end end % sort the clusters based on their statistical value [stat, indx] = sort(stat,'ascend'); % reorder the cluster indices in the observed data tmp = zeros(size(negclusobs)); for j=1:Nobsneg tmp(find(negclusobs==indx(j))) = j; end negclusobs = tmp; if strcmp(cfg.multivariate, 'yes') % estimate the probability of the mutivariate tail, i.e. one p-value for all clusters prob = 0; for i=1:Nrand % compare all clusters simultaneosuly prob = prob + any(negdistribution(:,i)<stat(:)); end prob = prob/Nrand; for j = 1:Nobsneg % collect a summary of the cluster properties negclusters(j).prob = prob; negclusters(j).clusterstat = stat(j); end % collect the probabilities in one large array prb_neg(find(negclusobs~=0)) = prob; elseif strcmp(cfg.orderedstats, 'yes') % compare the Nth ovbserved cluster against the randomization distribution of the Nth cluster prob = zeros(1,Nobsneg); for j = 1:Nobsneg prob(j) = sum(negdistribution(j,:)<stat(j))/Nrand; % collect a summary of the cluster properties negclusters(j).prob = prob(j); negclusters(j).clusterstat = stat(j); % collect the probabilities in one large array prb_neg(find(negclusobs==j)) = prob(j); end else % univariate -> each cluster has it's own probability prob = zeros(1,Nobsneg); for j = 1:Nobsneg prob(j) = sum(negdistribution<stat(j))/Nrand; % collect a summary of the cluster properties negclusters(j).prob = prob(j); negclusters(j).clusterstat = stat(j); % collect the probabilities in one large array prb_neg(find(negclusobs==j)) = prob(j); end end end if cfg.tail==0 % consider both tails prob = min(prb_neg, prb_pos); % this is the probability for the most unlikely tail elseif cfg.tail==1 % only consider the positive tail prob = prb_pos; elseif cfg.tail==-1 % only consider the negative tail prob = prb_neg; end % collect the remaining details in the output structure stat.prob = prob; if needpos, stat.posclusters = posclusters; stat.posclusterslabelmat = posclusobs; stat.posdistribution = posdistribution; end if needneg, stat.negclusters = negclusters; stat.negclusterslabelmat = negclusobs; stat.negdistribution = negdistribution; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % BEGIN SUBFUNCTION MAKECHANNEIGHBSTRUCTMAT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function channeighbstructmat = makechanneighbstructmat(cfg); % MAKECHANNEIGHBSTRUCTMAT makes the makes the matrix containing the channel % neighbourhood structure. % because clusterstat has no access to the actual data (containing data.label), this workaround is required % cfg.neighbours is cleared here because it is not done where avgoverchan is effectuated (it should actually be changed there) if strcmp(cfg.avgoverchan, 'no') nchan=length(cfg.channel); elseif strcmp(cfg.avgoverchan, 'yes') nchan = 1; cfg.neighbours = []; end channeighbstructmat = false(nchan,nchan); for chan=1:length(cfg.neighbours) [seld] = match_str(cfg.channel, cfg.neighbours(chan).label); [seln] = match_str(cfg.channel, cfg.neighbours(chan).neighblabel); if isempty(seld) % this channel was not present in the data continue; else % add the neighbours of this channel to the matrix channeighbstructmat(seld, seln) = true; end end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % BEGIN SUBFUNCTION MAKECHANCMBNEIGHBMATS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [chancmbneighbstructmat, chancmbneighbselmat] = makechancmbneighbmats(channeighbstructmat,labelcmb,label,orderedchancmbs,original); % compute CHANCMBNEIGHBSTRUCTMAT and CHANCMBNEIGHBSELMAT, which will be % used for clustering channel combinations. nchan=length(label); nchansqr=nchan^2; % Construct an array labelcmbnrs from labelcmb by replacing the label pairs % in labelcmb by numbers that correspond to the order of the labels in label. nchancmb = size(labelcmb,1); labelcmbnrs=zeros(nchancmb,2); for chanindx=1:nchan [chansel1] = match_str(labelcmb(:,1),label(chanindx)); labelcmbnrs(chansel1,1)=chanindx; [chansel2] = match_str(labelcmb(:,2),label(chanindx)); labelcmbnrs(chansel2,2)=chanindx; end; % Calculate the row and column indices (which are identical) of the % channel combinations that are present in the data. chancmbindcs=zeros(nchancmb,1); for indx=1:nchancmb chancmbindcs(indx)=(labelcmbnrs(indx,1)-1)*nchan + labelcmbnrs(indx,2); end; % put all elements on the diagonal of CHANNEIGHBSTRUCTMAT equal to one channeighbstructmat=channeighbstructmat | logical(eye(nchan)); % Compute CHANCMBNEIGHBSTRUCTMAT % First compute the complete CHANCMBNEIGHBSTRUCTMAT (containing all % ORDERED channel combinations that can be formed with all channels present in % the data) and later select and reorder the channel combinations actually % present in data). In the complete CHANCMBNEIGHBSTRUCTMAT, the row and the % column pairs are ordered lexicographically. chancmbneighbstructmat = false(nchansqr); if original % two channel pairs are neighbours if their first elements are % neighbours chancmbneighbstructmat = logical(kron(channeighbstructmat,ones(nchan))); % or if their second elements are neighbours chancmbneighbstructmat = chancmbneighbstructmat | logical(kron(ones(nchan),channeighbstructmat)); else % version that consumes less memory for chanindx=1:nchan % two channel pairs are neighbours if their first elements are neighbours % or if their second elements are neighbours chancmbneighbstructmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) = ... logical(kron(channeighbstructmat(:,chanindx),ones(nchan))) | ... logical(kron(ones(nchan,1),channeighbstructmat)); end; end; if ~orderedchancmbs if original % or if the first element of the row channel pair is a neighbour of the % second element of the column channel pair chancmbneighbstructmat = chancmbneighbstructmat | logical(repmat(kron(channeighbstructmat,ones(nchan,1)), [1 nchan])); % or if the first element of the column channel pair is a neighbour of the % second element of the row channel pair chancmbneighbstructmat = chancmbneighbstructmat | logical(repmat(kron(channeighbstructmat,ones(1,nchan)),[nchan 1])); else for chanindx=1:nchan % two channel pairs are neighbours if % the first element of the row channel pair is a neighbour of the % second element of the column channel pair % or if the first element of the column channel pair is a neighbour of the % second element of the row channel pair chancmbneighbstructmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) = ... chancmbneighbstructmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) | ... logical(kron(channeighbstructmat,ones(nchan,1))) | ... logical(repmat(kron(channeighbstructmat(:,chanindx),ones(1,nchan)),[nchan 1])); end; end; end; % reorder and select the entries in chancmbneighbstructmat such that they correspond to labelcmb. chancmbneighbstructmat = sparse(chancmbneighbstructmat); chancmbneighbstructmat = chancmbneighbstructmat(chancmbindcs,chancmbindcs); % compute CHANCMBNEIGHBSELMAT % CHANCMBNEIGHBSELMAT identifies so-called parallel pairs. A channel pair % is parallel if (a) all four sensors are different and (b) all elements (of the first % and the second pair) are neighbours of an element of the other pair. % if orderedpairs is true, then condition (b) is as follows: the first % elements of the two pairs are neighbours, and the second elements of the % two pairs are neighbours. % put all elements on the diagonal of CHANNEIGHBSTRUCTMAT equal to zero channeighbstructmat = logical(channeighbstructmat.*(ones(nchan)-diag(ones(nchan,1)))); chancmbneighbselmat = false(nchansqr); if orderedchancmbs if original % if the first element of the row pair is a neighbour of the % first element of the column pair chancmbneighbselmat = logical(kron(channeighbstructmat,ones(nchan))); % and the second element of the row pair is a neighbour of the % second element of the column pair chancmbneighbselmat = chancmbneighbselmat & logical(kron(ones(nchan),channeighbstructmat)); else % version that consumes less memory for chanindx=1:nchan % if the first element of the row pair is a neighbour of the % first element of the column pair % and the second element of the row pair is a neighbour of the % second element of the column pair chancmbneighbselmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) = ... logical(kron(channeighbstructmat(:,chanindx),ones(nchan))) & logical(kron(ones(nchan,1),channeighbstructmat)); end; end; else % unordered channel combinations if original % if the first element of the row pair is a neighbour of one of the % two elements of the column pair chancmbneighbselmat = logical(kron(channeighbstructmat,ones(nchan))) | logical(repmat(kron(channeighbstructmat,ones(nchan,1)), [1 nchan])); % and the second element of the row pair is a neighbour of one of the % two elements of the column pair chancmbneighbselmat = chancmbneighbselmat & (logical(kron(ones(nchan),channeighbstructmat)) | ... logical(repmat(kron(channeighbstructmat,ones(1,nchan)), [nchan 1]))); else % version that consumes less memory for chanindx=1:nchan % if the first element of the row pair is a neighbour of one of the % two elements of the column pair % and the second element of the row pair is a neighbour of one of the % two elements of the column pair chancmbneighbselmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) = ... (logical(kron(channeighbstructmat(:,chanindx),ones(nchan))) | logical(kron(channeighbstructmat,ones(nchan,1)))) ... & (logical(kron(ones(nchan,1),channeighbstructmat)) | ... logical(repmat(kron(channeighbstructmat(:,chanindx),ones(1,nchan)), [nchan 1]))); end; end; end; if original % remove all pairs of channel combinations that have one channel in common. % common channel in the first elements of the two pairs. chancmbneighbselmat = chancmbneighbselmat & kron(~eye(nchan),ones(nchan)); % common channel in the second elements of the two pairs. chancmbneighbselmat = chancmbneighbselmat & kron(ones(nchan),~eye(nchan)); % common channel in the first element of the row pair and the second % element of the column pair. tempselmat=logical(zeros(nchansqr)); tempselmat(:)= ~repmat([repmat([ones(nchan,1); zeros(nchansqr,1)],[(nchan-1) 1]); ones(nchan,1)],[nchan 1]); chancmbneighbselmat = chancmbneighbselmat & tempselmat; % common channel in the second element of the row pair and the first % element of the column pair. chancmbneighbselmat = chancmbneighbselmat & tempselmat'; else noteye=~eye(nchan); tempselmat=logical(zeros(nchansqr,nchan)); tempselmat(:)= ~[repmat([ones(nchan,1); zeros(nchansqr,1)],[(nchan-1) 1]); ones(nchan,1)]; for chanindx=1:nchan % remove all pairs of channel combinations that have one channel in common. % common channel in the first elements of the two pairs. % common channel in the second elements of the two pairs. % common channel in the first element of the row pair and the second % element of the column pair. chancmbneighbselmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) = ... chancmbneighbselmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) ... & logical(kron(noteye(:,chanindx),ones(nchan))) ... & logical(kron(ones(nchan,1),noteye)) ... & tempselmat; end; for chanindx=1:nchan % remove all pairs of channel combinations that have one % common channel in the second element of the row pair and the first % element of the column pair. chancmbneighbselmat(((chanindx-1)*nchan + 1):(chanindx*nchan),:) = ... chancmbneighbselmat(((chanindx-1)*nchan + 1):(chanindx*nchan),:) & tempselmat'; end; end; % reorder and select the entries in chancmbneighbselmat such that they correspond to labelcmb. chancmbneighbselmat = sparse(chancmbneighbselmat); chancmbneighbselmat = chancmbneighbselmat(chancmbindcs,chancmbindcs); % put all elements below and on the diagonal equal to zero nchancmbindcs = length(chancmbindcs); for chancmbindx=1:nchancmbindcs selvec=[true(chancmbindx-1,1);false(nchancmbindcs-chancmbindx+1,1)]; chancmbneighbstructmat(:,chancmbindx) = chancmbneighbstructmat(:,chancmbindx) & selvec; chancmbneighbselmat(:,chancmbindx) = chancmbneighbselmat(:,chancmbindx) & selvec; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION convert Nx2 cell array with channel combinations into Nx1 cell array with labels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label = cmb2label(labelcmb); label = {}; for i=1:size(labelcmb) label{i,1} = [labelcmb{i,1} '&' labelcmb{i,2}]; end
github
philippboehmsturm/antx-master
ft_chantype.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/ft_chantype.m
16,027
utf_8
7bceb8d238631a586cda73a2d74ef6c4
function type = ft_chantype(input, desired) % FT_CHANTYPE determines for each channel what type it is, e.g. planar/axial gradiometer or magnetometer % % 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) % Copyright (C) 2008-2011, 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 3530 2011-05-12 14:15:17Z roboos $ % this is to avoid a recursion loop persistent recursion if isempty(recursion) recursion = false; end % determine the type of input isheader = isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'Fs'); isgrad = isa(input, 'struct') && isfield(input, 'pnt') && isfield(input, 'ori'); islabel = isa(input, 'cell') && isa(input{1}, 'char'); hdr = input; grad = input; label = input; if isheader numchan = length(hdr.label); if isfield(hdr, 'grad') grad = hdr.grad; end label = hdr.label; elseif isgrad label = grad.label; numchan = length(label); elseif islabel numchan = length(label); else error('the input that was provided to this function cannot be deciphered'); end % start with unknown type type = cell(numchan,1); for i=1:length(type) type{i} = 'unknown'; end if ft_senstype(input, 'neuromag') % channames-KI is the channel kind, 1=meg, 202=eog, 2=eeg, 3=trigger (I am nut sure, but have inferred this from a single test file) % chaninfo-TY is the Coil type (0=magnetometer, 1=planar gradiometer) if isfield(hdr, 'orig') && isfield(hdr.orig, 'channames') for sel=find(hdr.orig.channames.KI(:)==202)' type{sel} = 'eog'; end for sel=find(hdr.orig.channames.KI(:)==2)' type{sel} = 'eeg'; end for sel=find(hdr.orig.channames.KI(:)==3)' type{sel} = 'digital trigger'; end % determinge the MEG channel subtype selmeg=find(hdr.orig.channames.KI(:)==1)'; for i=1:length(selmeg) if hdr.orig.chaninfo.TY(i)==0 type{selmeg(i)} = 'megmag'; elseif hdr.orig.chaninfo.TY(i)==1 type{selmeg(i)} = 'megplanar'; end end elseif isfield(hdr, 'orig') && isfield(hdr.orig, 'chs') && isfield(hdr.orig.chs, 'coil_type') %all the chs.kinds and chs.coil_types are obtained from the MNE %manual, p.210-211 for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==2)' %planar gradiometers type(sel) = {'megplanar'}; %Neuromag-122 planar gradiometer end for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==3012)' %planar gradiometers type(sel) = {'megplanar'}; %Type T1 planar grad end for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==3013)' %planar gradiometers type(sel) = {'megplanar'}; %Type T2 planar grad end for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==3014)' %planar gradiometers type(sel) = {'megplanar'}; %Type T3 planar grad end for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==3022)' %magnetometers type(sel) = {'megmag'}; %Type T1 magenetometer end for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==3023)' %magnetometers type(sel) = {'megmag'}; %Type T2 magenetometer end for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==3024)' %magnetometers type(sel) = {'megmag'}; %Type T3 magenetometer end for sel=find([hdr.orig.chs.kind]==301)' %MEG reference channel, located far from head type(sel) = {'ref'}; end for sel=find([hdr.orig.chs.kind]==2)' %EEG channels type(sel) = {'eeg'}; end for sel=find([hdr.orig.chs.kind]==201)' %MCG channels type(sel) = {'mcg'}; end for sel=find([hdr.orig.chs.kind]==3)' %Stim channels if any([hdr.orig.chs(sel).logno] == 101) %new systems: 101 (and 102, if enabled) are digital; %low numbers are 'pseudo-analog' (if enabled) type(sel([hdr.orig.chs(sel).logno] == 101)) = {'digital trigger'}; type(sel([hdr.orig.chs(sel).logno] == 102)) = {'digital trigger'}; type(sel([hdr.orig.chs(sel).logno] <= 32)) = {'analog trigger'}; others = [hdr.orig.chs(sel).logno] > 32 & [hdr.orig.chs(sel).logno] ~= 101 & ... [hdr.orig.chs(sel).logno] ~= 102; type(sel(others)) = {'other trigger'}; elseif any([hdr.orig.chs(sel).logno] == 14) %older systems: STI 014/015/016 are digital; %lower numbers 'pseudo-analog'(if enabled) type(sel([hdr.orig.chs(sel).logno] == 14)) = {'digital trigger'}; type(sel([hdr.orig.chs(sel).logno] == 15)) = {'digital trigger'}; type(sel([hdr.orig.chs(sel).logno] == 16)) = {'digital trigger'}; type(sel([hdr.orig.chs(sel).logno] <= 13)) = {'analog trigger'}; others = [hdr.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([hdr.orig.chs.kind]==202)' %EOG type(sel) = {'eog'}; end for sel=find([hdr.orig.chs.kind]==302)' %EMG type(sel) = {'emg'}; end for sel=find([hdr.orig.chs.kind]==402)' %ECG type(sel) = {'ecg'}; end for sel=find([hdr.orig.chs.kind]==502)' %MISC type(sel) = {'misc'}; end for sel=find([hdr.orig.chs.kind]==602)' %Resp type(sel) = {'respiration'}; end end elseif ft_senstype(input, 'ctf') && isheader % meg channels are 5, refmag 0, refgrad 1, adcs 18, trigger 11, eeg 9 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 warning('could not determine channel type from the CTF header'); origSensType = []; 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(:)==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]$', grad.label); type(sel) = {'meggrad'}; % normal gradiometer channels sel = myregexp('^B[GPR][0-9]$', grad.label); type(sel) = {'refmag'}; % reference magnetometers sel = myregexp('^[GPQR][0-9][0-9]$', grad.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('^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') % all 4D-BTi MEG channels start with "A" % all 4D-BTi reference channels start with M or G % all 4D-BTi EEG channels start with E type(strncmp('A', label, 1)) = {'meg'}; type(strncmp('M', label, 1)) = {'refmag'}; type(strncmp('G', label, 1)) = {'refgrad'}; if isfield(grad, 'tra') selchan = find(strcmp('mag', type)); for k = 1:length(selchan) ncoils = length(find(grad.tra(selchan(k),:)==1)); if ncoils==1, type{selchan(k)} = 'megmag'; elseif ncoils==2, type{selchan(k)} = 'meggrad'; end end end % This is to allow setting additional channel types based on the names if isheader && issubfield(hdr, 'orig.channel_data.chan_label') tmplabel = {hdr.orig.channel_data.chan_label}; tmplabel = tmplabel(:); else tmplabel = label; % might work end sel = strmatch('unknown', type, 'exact'); if ~isempty(sel) type(sel)= ft_chantype(tmplabel(sel)); sel = strmatch('unknown', type, 'exact'); if ~isempty(sel) type(sel(strncmp('E', label(sel), 1))) = {'eeg'}; 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; sel = (hdr.orig.channel_info(:, 2) == NullChannel); type(sel) = {'null'}; sel = (hdr.orig.channel_info(:, 2) == MagnetoMeter); type(sel) = {'megmag'}; sel = (hdr.orig.channel_info(:, 2) == AxialGradioMeter); type(sel) = {'meggrad'}; sel = (hdr.orig.channel_info(:, 2) == PlannerGradioMeter); type(sel) = {'megplanar'}; sel = (hdr.orig.channel_info(:, 2) == RefferenceMagnetoMeter); type(sel) = {'refmag'}; sel = (hdr.orig.channel_info(:, 2) == RefferenceAxialGradioMeter); type(sel) = {'refgrad'}; sel = (hdr.orig.channel_info(:, 2) == RefferencePlannerGradioMeter); type(sel) = {'refplanar'}; sel = (hdr.orig.channel_info(:, 2) == TriggerChannel); type(sel) = {'trigger'}; sel = (hdr.orig.channel_info(:, 2) == EegChannel); type(sel) = {'eeg'}; sel = (hdr.orig.channel_info(:, 2) == EcgChannel); type(sel) = {'ecg'}; sel = (hdr.orig.channel_info(:, 2) == EtcChannel); type(sel) = {'etc'}; elseif ft_senstype(input, 'yokogawa') && isgrad % all channels in the gradiometer definition are meg type(1:end) = {'meg'}; elseif ft_senstype(input, 'yokogawa') && islabel % the yokogawa channel labels are a mess, so autodetection is not possible type(1:end) = {'meg'}; elseif ft_senstype(input, 'itab') && isheader sel = ([hdr.orig.ch.type]==0); type(sel) = {'unknown'}; sel = ([hdr.orig.ch.type]==1); type(sel) = {'unknown'}; sel = ([hdr.orig.ch.type]==2); type(sel) = {'megmag'}; sel = ([hdr.orig.ch.type]==8); type(sel) = {'megref'}; sel = ([hdr.orig.ch.type]==16); type(sel) = {'aux'}; sel = ([hdr.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(hdr.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('^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(ft_senstype(label)))) = {'eeg'}; elseif ft_senstype(input, 'eeg') && isheader % use an external helper function to define the list with EEG channel names type(match_str(hdr.label, ft_senslabel(ft_senstype(hdr)))) = {'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 hdr.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'}; }; for i = 1:numel(label2type) for j = 1:numel(label2type{i}) type(intersect(strmatch(label2type{i}{j}, lower(label)),... strmatch('unknown', type, 'exact'))) = 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') type = strncmp(desired, type, 3); else type = strcmp(desired, type); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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
philippboehmsturm/antx-master
ft_read_event.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/ft_read_event.m
61,782
utf_8
b0442e5476b7f5a3d4674ab9a1d61929
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 'up', 'down', 'both' or 'auto' (default is system specific) % '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) % '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) % % 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)) % % See also: % FT_READ_HEADER, FT_READ_DATA, FT_WRITE_DATA, FT_WRITE_EVENT, FT_FILTER_EVENT % Copyright (C) 2004-2010 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 3709 2011-06-16 12:07:11Z roboos $ 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) % use recursion to read from multiple event sources event = []; for i=1:numel(filename) tmp = ft_read_event(filename{i}, varargin{:}); event = appendevent(event(:), tmp(:)); end return end % get the options eventformat = ft_getopt(varargin, 'eventformat'); hdr = ft_getopt(varargin, 'header'); detectflank = ft_getopt(varargin, 'detectflank'); % 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 headerformat = ft_getopt(varargin, 'headerformat'); dataformat = ft_getopt(varargin, 'dataformat'); threshold = ft_getopt(varargin, 'threshold'); % this is used for analog channels % 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); % determine the filetype if isempty(eventformat) eventformat = ft_filetype(filename); end % default is to search only for rising or up-going flanks if isempty(detectflank) detectflank = 'up'; end 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'), trigger = read_trigger(filename, 'header', hdr, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trgindx, 'detectflank', detectflank, 'trigshift', trigshift,'fix4dglasgow',1, 'dataformat', '4d'); else trigger = read_trigger(filename, 'header', hdr, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trgindx, 'detectflank', detectflank, 'trigshift', trigshift,'fix4dglasgow',0, 'dataformat', '4d'); end event = appendevent(event, trigger); respindx = match_str(hdr.label, 'RESPONSE'); if ~isempty(respindx) response = read_trigger(filename, 'header', hdr, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', respindx, 'detectflank', detectflank, 'trigshift', trigshift, 'dataformat', '4d'); 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); % 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); 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)); % 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 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, 'chanindx', statusindx, 'detectflank', 'up', 'fixbiosemi', true); else warning('BIOSIG does not have a consistent event representation, skipping events') event = []; end 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 seperator 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 seperator 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 trigchanindx = find(origSensType==11); if ~isempty(trigchanindx) % read the trigger channel and do flank detection trigger = read_trigger(filename, 'header', hdr, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trigchanindx, 'dataformat', dataformat, 'detectflank', detectflank, 'trigshift', trigshift, 'fixctf', 1); 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); 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 seperate bytes evt = typecast(int16(evt), 'uint8'); % construct the Time-stamped Annotations Lists (TAL) tal = tokenize(evt, char(0), true); event = []; for i=1:length(tal) tok = tokenize(tal{i}, char(20)); time = str2double(char(tok{1})); % 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; event(end ).duration = 0; 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 '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' % check that the required low-level toolbox is available ft_hastoolbox('eeprobe', 1); % try to read external trigger file in EEP format trgfile = [filename(1:(end-3)), 'trg']; if exist(trgfile, 'file') if isempty(hdr) hdr = ft_read_header(filename); end tmp = read_eep_trg(trgfile); % translate the EEProbe trigger codes to events for i=1:length(tmp) event(i).type = 'trigger'; event(i).sample = round((tmp(i).time/1000) * hdr.Fs) + 1; % convert from ms to samples event(i).value = tmp(i).code; event(i).offset = 0; event(i).duration = 0; end else warning('no triggerfile was found'); 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' if isempty(hdr) hdr = ft_read_header(filename); end % get event info from xml files ft_hastoolbox('XML4MAT', 1, 0); 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') 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,'epoch') && length(hdr.orig.xml.epoch) > 1 Msamp2offset = zeros(2,size(hdr.orig.epochdef,1),1+max(hdr.orig.epochdef(:,2)-hdr.orig.epochdef(:,1))); Msamp2offset(:) = NaN; 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) 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 eventCount = eventCount+1; % calculate eventSample, relative to start of epoch if isfield(hdr.orig.xml,'epoch') && length(hdr.orig.xml.epoch) > 1 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 eventSample = Msamp2offset(1,EpochNum,SampIndex); else eventSample = eventOffset+1; end 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; 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 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' [path, file, ext] = fileparts(filename); if isempty(hdr) headerfile = fullfile(path, [file '/header']); hdr = read_buffer_offline_header(headerfile); end eventfile = fullfile(path, [file '/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); system(sprintf('mkfifo -m 0666 %s',fifo)); end fid = fopen(fifo, 'r'); 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 seperate file event = read_serial_event(filename); case 'fcdc_mysql' % 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 {'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)'); trigsel = find(ft_chantype(hdr, 'flag')); trigger = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trigsel, '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 {'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_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); 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', 0); 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', 1); event = appendevent(event, trigger); 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 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 seperate 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 seperate 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 seperate *.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 seperate *.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_cds' % this is a combined Neuralynx dataset with seperate 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')); % seperate file with original TimeStampLow %hastsh = any(filetype_check_extension({dirlist.name}, 'tsh')); % seperate file with original TimeStampHi hasttl = any(filetype_check_extension({dirlist.name}, 'ttl')); % seperate 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'} tmp = np_readmarker (filename, 0, inf, 'samples'); event = []; for i = 1:numel(tmp.marker) if isempty(tmp.marker{i}) break; end event = [event struct('type', tmp.markernames(i),... 'sample', num2cell(tmp.marker{i}),... 'value', {tmp.markertyp(i)})]; 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 ft_hastoolbox('yokogawa', 1); % 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 '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.hdr.eventinfo) 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 otherwise error('unsupported event format (%s)', eventformat); 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 [dum, indx] = sort([event.sample]); event = event(indx); % else % warning('no events found in %s', filename); end % apply the optional filters event = ft_filter_event(event, varargin{:}); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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
philippboehmsturm/antx-master
ft_read_header.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/ft_read_header.m
61,504
utf_8
d1cf4542f365c1add40b70a2846ce4ec
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 = []) % % 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.FirstTimeStamp integer, only available for some subformats (mainly animal electrophisiology systems) % hdr.TimeStampPerSample integer, only available for some subformats (mainly animal electrophisiology systems) % % For continuous data, nSamplesPre=0 and nTrials=1. % % 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) % % The following EEG dataformats are supported % ANT - Advanced Neuro Technology, EEProbe (*.avr, *.eeg, *.cnt) % Biosemi (*.bdf) % CED - Cambridge Electronic Design (*. smr) % Electrical Geodesics, Inc. (*.egis, *.ave, *.gave, *.ses, *.raw, *.sbin, MFF fileformat) % Megis/BESA (*.avr, *.swf) % NeuroScan (*.eeg, *.cnt, *.avg) % Nexstim (*.nxe) % BrainVision (*.eeg, *.seg, *.dat, *.vhdr, *.vmrk) % % The following spike and LFP dataformats are supported (with some limitations) % Plextor (*.nex, *.plx, *.ddt) % Neuralynx (*.ncs, *.nse, *.nts, *.nev, DMA log files) % CED - Cambridge Electronic Design (*.smr) % MPI - Max Planck Institute (*.dap) % % See also FT_READ_DATA, FT_READ_EVENT, FT_WRITE_DATA, FT_WRITE_EVENT % Copyright (C) 2003-2010 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 3461 2011-05-06 21:35:40Z ingnie $ % TODO channel renaming should be made a general option (see bham_bdf) persistent cacheheader % for caching persistent db_blob % for fcdc_mysql persistent fakechannelwarning % this warning should be given only once if isempty(db_blob) db_blob = 0; end % test whether the file or directory exists if ~exist(filename, 'file') && ~strcmp(ft_filetype(filename), 'ctf_shm') && ~strcmp(ft_filetype(filename), 'fcdc_mysql') && ~strcmp(ft_filetype(filename), 'fcdc_buffer') error('FILEIO:InvalidFileName', 'file or directory ''%s'' does not exist', filename); end % get the options headerformat = keyval('headerformat', varargin); fallback = keyval('fallback', varargin); cache = keyval('cache', varargin); retry = keyval('retry', varargin); if isempty(retry), retry = false; end % for fcdc_buffer % SK: I added this as a temporary fix to prevent 1000000 voxel names % to be checked for uniqueness. fMRI users will probably never use % channel names for anything. checkUniqueLabels = true; % determine the filetype if isempty(headerformat) headerformat = ft_filetype(filename); end if isempty(cache), if strcmp(headerformat, 'bci2000_dat') || strcmp(headerformat, 'eyelink_asc') cache = true; else cache = false; end end % start with an empty header hdr = []; % 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') filename = headerfile; % this function will read the header headerformat = ft_filetype(filename); % update the filetype end % 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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the data with the low-level reading function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch headerformat 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 = bti2grad(orig); % 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 = bti2grad(orig); % 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 if isempty(fakechannelwarning) || ~fakechannelwarning % give this warning only once warning('creating fake channel names'); fakechannelwarning = true; end 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 if isempty(fakechannelwarning) || ~fakechannelwarning % give this warning only once warning('creating fake channel names'); fakechannelwarning = true; end 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' 'gdf'} % use the biosig toolbox if available ft_hastoolbox('BIOSIG', 1); hdr = read_biosig_header(filename); % gdf always represents continuous data hdr.nSamples = hdr.nSamples*hdr.nTrials; hdr.nTrials = 1; hdr.nSamplesPre = 0; 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_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 I copied from the EEGLAB toolbox 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 seperate 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; 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); 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, 'G1AR'))) 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); 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(filename, 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' % contact Robert Oostenveld if you are interested in real-time acquisition on the CTF system % 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 'edf' % this reader is largely similar to the bdf reader hdr = read_edf(filename); 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 = rmfield(hdr, 'data'); try, hdr = rmfield(hdr, 'variance'); end case 'eeglab_set' hdr = read_eeglabheader(filename); 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.Fs = 1000/median(diff(asc.dat(1,:))); % these timestamps are in miliseconds hdr.FirstTimeStamp = asc.dat(1,1); hdr.TimeStampPerSample = median(diff(asc.dat(1,:))); if isempty(fakechannelwarning) || ~fakechannelwarning % give this warning only once warning('creating fake channel names'); fakechannelwarning = true; end 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 'eep_cnt' % check that the required low-level toolbox is available ft_hastoolbox('eeprobe', 1); % read the first sample from the continous data, which will also return the header hdr = read_eep_cnt(filename, 1, 1); hdr.Fs = hdr.rate; hdr.nSamples = hdr.nsample; hdr.nSamplesPre = 0; hdr.nChans = hdr.nchan; hdr.nTrials = 1; % it can always be interpreted as continuous data 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' % segmented type only [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' orig = []; % 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 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 ft_hastoolbox('XML4MAT', 1, 0); 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') %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, 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 strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '0') %EEG chans % 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; hdr.label{iSens} = ['E' num2str(iSens)]; % to be consistent with other egi formats 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) == orig.signal(1).blockhdr(1).nsignals %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,'epoch') && length(orig.xml.epoch) > 1 % 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.epoch),3); for iEpoch = 1:length(orig.xml.epoch) if iEpoch == 1 epochdef(iEpoch,1) = round(str2double(orig.xml.epoch(iEpoch).epoch.beginTime)./1000./hdr.Fs)+1; epochdef(iEpoch,2) = round(str2double(orig.xml.epoch(iEpoch).epoch.endTime)./1000./hdr.Fs); epochdef(iEpoch,3) = round(str2double(orig.xml.epoch(iEpoch).epoch.beginTime)./1000./hdr.Fs); %offset corresponds to timing else NbSampEpoch = round(str2double(orig.xml.epoch(iEpoch).epoch.endTime)./1000./hdr.Fs - str2double(orig.xml.epoch(iEpoch).epoch.beginTime)./1000./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.epoch(iEpoch).epoch.beginTime)./1000./hdr.Fs); %offset corresponds to timing end end warning('the data contains multiple epochs with possibly discontinuous boundaries. Added ''epochdef'' to hdr.orig defining begin and end sample of each epoch. See hdr.orig.xml.epoch for epoch details, use ft_read_header to obtain header or look in data.dhr.') % sanity check if epochdef(end,2) ~= hdr.nSamples error('number of samples in all epochs do not add up to total number of samples') end orig.epochdef = epochdef; end hdr.orig = orig; 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 hdr.Fs = orig.fsample; hdr.nChans = orig.nchans; hdr.nSamples = orig.nsamples; hdr.nSamplesPre = 0; % since continuous hdr.nTrials = 1; % since continuous hdr.orig = []; % add chunks if present % add the contents of attached .res4 file to the .orig field similar to offline data if isfield(orig, 'ctf_res4') if 0 % using READ_CTF_RES4 -- this does not produce a proper .grad structure % TODO: remove this code, and possibly read_ctf_res4 as well tmp_name = tempname; F = fopen(tmp_name, 'wb'); fwrite(F, orig.ctf_res4, 'uint8'); fclose(F); R4F = read_ctf_res4(tmp_name); delete(tmp_name); else % using FT_READ_HEADER recursively, and then readCTFds in the second call % this will also call ctf2grad and yield correct gradiometer information tmp_name = tempname; [dirname, fname] = fileparts(tmp_name); res4fn = [tmp_name '.ds/' fname '.res4']; meg4fn = [tmp_name '.ds/' fname '.meg4']; dsname = [tmp_name '.ds']; mkdir(dsname); F = fopen(res4fn, 'wb'); fwrite(F, orig.ctf_res4, 'uint8'); fclose(F); F = fopen(meg4fn, 'wb'); fwrite(F, 'MEG42CP'); fclose(F); %R4F = read_ctf_res4(tmp_name); R4F = ft_read_header(dsname); delete(res4fn); delete(meg4fn); rmdir(dsname); end % copy over the labels hdr.label = R4F.label; % copy over the 'original' header hdr.orig = R4F; if isfield(R4F,'grad') hdr.grad = R4F.grad; 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 if isempty(fakechannelwarning) || ~fakechannelwarning % give this warning only once warning('creating fake channel names'); fakechannelwarning = true; end hdr.label = cell(hdr.nChans,1); if hdr.nChans < 2000 % don't do this for fMRI etc. for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end else checkUniqueLabels = false; end 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 % hase generated fake channels if isempty(fakechannelwarning) || ~fakechannelwarning % give this warning only once warning('creating fake channel names'); fakechannelwarning = true; end 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' % 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 {'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 '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); if isempty(fakechannelwarning) || ~fakechannelwarning % give this warning only once warning('creating fake channel names'); fakechannelwarning = true; end for i=1:hdr.nChans hdr.label{i} = sprintf('%3d', 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 '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); orig = fiff_read_meas_info(filename); % convert to fieldtrip format header hdr.label = orig.ch_names(:); hdr.nChans = orig.nchan; hdr.Fs = orig.sfreq; % add a gradiometer structure for forward and inverse modelling try [hdr.grad, elec] = mne2grad(orig); if ~isempty(elec) hdr.elec = elec; end catch disp(lasterr); end for i = 1:hdr.nChans % make a cell array of units for each channel switch orig.chs(i).unit case 201 % defined as constants by MNE, see p. 217 of MNE manual hdr.unit{i} = 'T/m'; case 112 hdr.unit{i} = 'T'; case 107 hdr.unit{i} = 'V'; case 202 hdr.unit{i} = 'Am'; otherwise hdr.unit{i} = 'unknown'; end end iscontinuous = 0; isaverage = 0; isepoched = 0; % FIXME don't know how to determine this, or whether epoched .fif data exists! if isempty(fiff_find_evoked(filename)) % true if file contains no evoked responses iscontinuous = 1; 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: error(['Maxshield data has not had maxfilter applied to it - cannot be read by fieldtrip. ' ... 'Apply Neuromag maxfilter before converting to fieldtrip format.']); 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; orig.raw = raw; % keep all the details elseif isaverage 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; orig.evoked = evoked_data.evoked; % this is used by read_data to get the actual data, i.e. to prevent re-reading orig.info = evoked_data.info; % keep all the details orig.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); orig.evoked = evoked_data.evoked; % this is used by read_data to get the actual data, i.e. to prevent re-reading orig.info = evoked_data.info; % keep all the details orig.vartriallength = 0; end elseif isepoched error('Support for epoched *.fif data is not yet implemented.') end % remember the original header details hdr.orig = orig; % these are useful to know in read_event 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 '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'} if strcmp(headerformat, 'ns_cnt') orig = loadcnt(filename, 'ldnsamples', 1); elseif strcmp(headerformat, 'ns_cnt16') orig = loadcnt(filename, 'ldnsamples', 1, 'dataformat', 'int16'); elseif strcmp(headerformat, 'ns_cnt32') orig = loadcnt(filename, 'ldnsamples', 1, 'dataformat', 'int32'); end orig = rmfield(orig, {'data', 'ldnsamples'}); % do some reformatting/renaming of the header items hdr.Fs = orig.header.rate; hdr.nChans = orig.header.nchannels; hdr.nSamples = orig.header.nums; 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 '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); if isempty(fakechannelwarning) || ~fakechannelwarning % give this warning only once warning('creating fake channel names'); fakechannelwarning = true; end 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'} 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 = [tsq.code]==code(j); % 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 % the above code is not complete error('not yet implemented'); case {'yokogawa_ave', 'yokogawa_con', 'yokogawa_raw', 'yokogawa_mrk'} % chek that the required low-level toolbox is available ft_hastoolbox('yokogawa', 1); hdr = read_yokogawa_header(filename); % add a gradiometer structure for forward and inverse modelling hdr.grad = yokogawa2grad(hdr); 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.seginfo(1).SampleRate; % take the sampling freq from the first channel (assuming this is the same for all chans) hdr.nChans = tmp.hdr.fileinfo.EntityCount; hdr.nSamples = max([tmp.hdr.entityinfo.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.EntityLabel}; %%% contains non-unique chans hdr.orig = tmp; % remember the original header otherwise if strcmp(fallback, 'biosig') && ft_hastoolbox('BIOSIG', 1) hdr = read_biosig_header(filename); else error('unsupported header format (%s)', headerformat); end 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'); for i=1:hdr.nChans sel = find(strcmp(hdr.label{i}, hdr.label)); if length(sel)>1 for j=1:length(sel) hdr.label{sel(j)} = sprintf('%s-%d', hdr.label{sel(j)}, j); end end end end 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(sprintf('"%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;
github
philippboehmsturm/antx-master
ft_filetype.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/ft_filetype.m
45,872
utf_8
c37debc76f5f54e82527bde5fea74be6
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 % - BrainVision % - Curry % - Dataq % - EDF % - EEProbe % - Elektra/Neuromag % - LORETA % - FreeSurfer % - MINC % - Neuralynx % - Neuroscan % - Plexon % - SR Research Eyelink % - Tucker Davis Technology % - VSM-Medtech/CTF % - Yokogawa % - nifti, gifti % Copyright (C) 2003-2011 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 4143 2011-09-11 17:07:31Z crimic $ % 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 strcmp(class(filename), 'memmapfile'), filename = filename.Filename; end % % get the optional arguments % checkheader = keyval('checkheader', varargin); if isempty(checkheader), checkheader=1; end % % 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 [p, f, x] = fileparts(filename); % 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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % these are some streams for asynchronous BCI if 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')) type = 'ctf_res4'; manufacturer = 'CTF'; content = 'MEG/EEG header information'; elseif filetype_check_extension(filename, '.meg4') && filetype_check_header(filename, 'MEG41CP') 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'; % 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'; % 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 length(filename)<=4 && exist(fullfile(p,'config'), 'file') %&& exist(fullfile(p,'hs_file'), 'file') % this could be a 4D file with non-standard/processed name type = '4d'; manufacturer = '4D/BTi'; content = ''; % known EEProbe file types elseif filetype_check_extension(filename, '.cnt') && filetype_check_header(filename, 'RIFF') 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') type = 'nifti'; 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) && exist(fullfile(filename, 'header'), 'file') && exist(fullfile(filename, '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 a directory representing a dataset: it contains multiple xml files and one or more signalN.bin files 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) && any(ft_filetype({ls.name}, 'neuralynx_ds')) % a downsampled Neuralynx DMA file can be split into three seperate lfp/mua/spike directories % treat them as one combined dataset type = 'neuralynx_cds'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'dataset containing seperate 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 seperate generic ascii header'; % 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') 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'; % 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_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'; % 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') 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, '.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, '.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'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % finished determining the filetype %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(type, 'unknown') warning('could not determine filetype of %s', filename); 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; 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;
github
philippboehmsturm/antx-master
read_mff_bin.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/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
philippboehmsturm/antx-master
avw_img_read.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/avw_img_read.m
29,199
utf_8
95b0159897c31a2026a67ee3e54787a7
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: 3197 $ $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: 3197 $]'; 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
philippboehmsturm/antx-master
read_yokogawa_event.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_yokogawa_event.m
5,370
utf_8
55b961f29b8780d52b938417cfb5064b
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 3376 2011-04-22 12:45:14Z roboos $ % ensure that the required toolbox is on the path ft_hastoolbox('yokogawa', 1); event = []; handles = definehandles; % get the options, the default is set below trigindx = keyval('trigindx', varargin); threshold = keyval('threshold', varargin); detectflank = keyval('detectflank', varargin); % 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 % 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
philippboehmsturm/antx-master
read_4d_hdr.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_4d_hdr.m
24,610
utf_8
cad6b4858a59c73cbe1a5187692d794d
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 3328 2011-04-11 11:56:57Z 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 positions tmpfp = ftell(fid); Npoints = user_space_size./40; for k = 1:Npoints tmp = fread(fid, 16, 'uchar'); tmplabel = char(tmp(tmp>0)'); 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 tmp = fread(fid, 3, 'double'); pnt(k,:) = tmp(:)'; end 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.Format = header.header_data.Format; 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
philippboehmsturm/antx-master
decode_nifti1.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/decode_nifti1.m
2,915
utf_8
32b6ac0b0549062ef13624ad21eb55e2
function H = decode_nifti1(blob) % function 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 !!! % (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
philippboehmsturm/antx-master
read_edf.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_edf.m
14,984
utf_8
fb40441970f49fe560181defe88145de
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 .bdf 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 % % Or use as % [dat] = read_edf(filename, hdr, begsample, endsample, chanindx); % where % filename name of the datafile, including the .bdf 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 % 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 2076 2010-11-05 12:05:19Z roboos $ needhdr = (nargin==1); needevt = (nargin==2); needdat = (nargin>3); 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; 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; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert the header to Fieldtrip-style %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if all(EDF.SampleRate==EDF.SampleRate(1)) hdr.Fs = EDF.SampleRate(1); hdr.nChans = EDF.NS; hdr.label = cellstr(EDF.Label); % it is continuous data, therefore append all records in one trial hdr.nSamples = EDF.Dur * EDF.SampleRate(1); hdr.nSamplesPre = 0; hdr.nTrials = EDF.NRec; hdr.orig = EDF; 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.Dur * EDF.SampleRate(chansel(1)); hdr.nSamplesPre = 0; hdr.nTrials = EDF.NRec; 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.Dur * EDF.SampleRate(chansel(1)); hdr.nSamplesPre = 0; hdr.nTrials = EDF.NRec; 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); 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; if nargin<5 chanindx = 1:nchans; end % 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 % using a sparse matrix speeds up the multiplication calib = sparse(diag(EDF.Cal(EDF.chansel(chanindx)))); dat = full(calib * dat); elseif length(chanindx)==1 % in case of one channel the calibration would result in a sparse array calib = EDF.Cal(chanindx); dat = calib * dat; else % using a sparse matrix speeds up the multiplication calib = sparse(diag(EDF.Cal(chanindx))); 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
philippboehmsturm/antx-master
yokogawa2grad.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/yokogawa2grad.m
7,091
utf_8
2eb35dae79944c725b9f16079738501e
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. % % See also FT_READ_HEADER, CTF2GRAD, BTI2GRAD, FIF2GRAD % 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 3802 2011-07-07 15:57:28Z 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 | 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.pnt = hdr.channel_info(isgrad,3:5)*100; % 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.ori = 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.pnt(i+sum(isgrad),:) = [grad.pnt(i,:)+ori_1st(i,:)*baseline(i)*100]; grad.ori(i+sum(isgrad),:) = -ori_1st(i,:); elseif (info(i) == handles.PlannerGradioMeter || info(i) == handles.RefferencePlannerGradioMeter) grad.pnt(i+sum(isgrad),:) = [grad.pnt(i,:)+ori_1st_to_2nd(i,:)*baseline(i)*100]; grad.ori(i+sum(isgrad),:) = -ori_1st(i,:); else grad.pnt(i+sum(isgrad),:) = [0 0 0]; grad.ori(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.pnt,1)/2),0),1,2); % for mangetometers change tra as there is no second coil if any(ismag) sz_pnt = size(grad.pnt,1)/2; % create logical variable not_2nd_coil = ([diag(zeros(sz_pnt),0)' ismag']~=0); grad.tra(ismag,not_2nd_coil) = 0; end % Make the matrix sparse to speed up the multiplication in the forward % computation with the coil-leadfield matrix to get the channel leadfield grad.tra = sparse(grad.tra); % 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 = [];
github
philippboehmsturm/antx-master
write_plexon_nex.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/write_plexon_nex.m
9,540
utf_8
8fa4e7bd71496152f676bff2c34faaa4
function write_plexon_nex(filename, nex) % WRITE_PLEXON_NEX writes a Plexon *.nex file, which is a file % containing action-potential (spike) timestamps and waveforms (spike % channels), event timestamps (event channels), and continuous variable % data (continuous A/D channels). % % Use as % write_plexon_nex(filename, nex); % % The data structure should contain % nex.hdr.FileHeader.Frequency = TimeStampFreq % nex.hdr.VarHeader.Type = type, 5 for continuous % nex.hdr.VarHeader.Name = label, padded to length 64 % nex.hdr.VarHeader.WFrequency = sampling rate of continuous channel % nex.var.dat = data % nex.var.ts = timestamps % % See also READ_PLEXON_NEX, READ_PLEXON_PLX, READ_PLEXON_DDT % Copyright (C) 2007, 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: write_plexon_nex.m 2885 2011-02-16 09:41:58Z roboos $ % get the optional arguments, these are all required % FirstTimeStamp = keyval('FirstTimeStamp', varargin); % TimeStampFreq = keyval('TimeStampFreq', varargin); hdr = nex.hdr; UVtoMV = 1/1000; switch hdr.VarHeader.Type case 5 dat = nex.var.dat; % this is in microVolt buf = zeros(size(dat), 'int16'); nchans = size(dat,1); nsamples = size(dat,2); nwaves = 1; % only one continuous datasegment is supported if length(hdr.VarHeader)~=nchans error('incorrect number of channels'); end % convert the data from floating point into int16 values % each channel gets its own optimal calibration factor for varlop=1:nchans ADMaxValue = double(intmax('int16')); ADMaxUV = max(abs(dat(varlop,:))); % this is in microVolt ADMaxMV = ADMaxUV/1000; % this is in miliVolt if isa(dat, 'int16') % do not rescale data that is already 16 bit MVtoAD = 1; elseif ADMaxMV==0 % do not rescale the data if the data is zero MVtoAD = 1; elseif ADMaxMV>0 % rescale the data so that it fits into the 16 bits with as little loss as possible MVtoAD = ADMaxValue / ADMaxMV; end buf(varlop,:) = int16(double(dat) * UVtoMV * MVtoAD); % remember the calibration value, it should be stored in the variable header ADtoMV(varlop) = 1/MVtoAD; end dat = buf; clear buf; case 3 dat = nex.var.dat; % this is in microVolt nchans = 1; % only one channel is supported nsamples = size(dat,1); nwaves = size(dat,2); if length(hdr.VarHeader)~=nchans error('incorrect number of channels'); end % convert the data from floating point into int16 values ADMaxValue = double(intmax('int16')); ADMaxUV = max(abs(dat(:))); % this is in microVolt ADMaxMV = ADMaxUV/1000; % this is in miliVolt if isa(dat, 'int16') % do not rescale data that is already 16 bit MVtoAD = 1; elseif ADMaxMV==0 % do not rescale the data if the data is zero MVtoAD = 1; elseif ADMaxMV>0 % rescale the data so that it fits into the 16 bits with as little loss as possible MVtoAD = ADMaxValue / ADMaxMV; end dat = int16(double(dat) * UVtoMV * MVtoAD); % remember the calibration value, it should be stored in the variable header ADtoMV = 1/MVtoAD; otherwise error('unsupported data type') end % switch type % determine the first and last timestamp ts = nex.var.ts; ts_beg = min(ts); ts_end = 0; % FIXME fid = fopen(filename, 'wb', 'ieee-le'); % write the file header write_NexFileHeader; % write the variable headers for varlop=1:nchans write_NexVarHeader; end % write the variable data for varlop=1:nchans write_NexVarData; end fclose(fid); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nested function for writing the details %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function write_NexFileHeader % prepare the two char buffers buf1 = padstr('$Id: write_plexon_nex.m 2885 2011-02-16 09:41:58Z roboos $', 256); buf2 = char(zeros(1, 256)); % write the stuff to the file fwrite(fid, 'NEX1' , 'char'); % NexFileHeader = string NEX1 fwrite(fid, 100 , 'int32'); % Version = version fwrite(fid, buf1 , 'char'); % Comment = comment, 256 bytes fwrite(fid, hdr.FileHeader.Frequency, 'double'); % Frequency = timestamped freq. - tics per second fwrite(fid, ts_beg, 'int32'); % Beg = usually 0, minimum of all the timestamps in the file fwrite(fid, ts_end, 'int32'); % End = maximum timestamp + 1 fwrite(fid, nchans, 'int32'); % NumVars = number of variables in the first batch fwrite(fid, 0 , 'int32'); % NextFileHeader = position of the next file header in the file, not implemented yet fwrite(fid, buf2 , 'char'); % Padding = future expansion end % of the nested function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nested function for writing the details %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function write_NexVarHeader filheadersize = 544; varheadersize = 208; offset = filheadersize + nchans*varheadersize + (varlop-1)*nsamples; calib = ADtoMV(varlop); % prepare the two char buffers buf1 = padstr(hdr.VarHeader(varlop).Name, 64); buf2 = char(zeros(1, 68)); % write the continuous variable to the file fwrite(fid, hdr.VarHeader.Type, 'int32'); % Type = 0 - neuron, 1 event, 2- interval, 3 - waveform, 4 - pop. vector, 5 - continuously recorded fwrite(fid, 100, 'int32'); % Version = 100 fwrite(fid, buf1, 'char'); % Name = variable name, 1x64 char fwrite(fid, offset, 'int32'); % DataOffset = where the data array for this variable is located in the file fwrite(fid, nwaves, 'int32'); % Count = number of events, intervals, waveforms or weights fwrite(fid, 0, 'int32'); % WireNumber = neuron only, not used now fwrite(fid, 0, 'int32'); % UnitNumber = neuron only, not used now fwrite(fid, 0, 'int32'); % Gain = neuron only, not used now fwrite(fid, 0, 'int32'); % Filter = neuron only, not used now fwrite(fid, 0, 'double'); % XPos = neuron only, electrode position in (0,100) range, used in 3D fwrite(fid, 0, 'double'); % YPos = neuron only, electrode position in (0,100) range, used in 3D fwrite(fid, hdr.VarHeader.WFrequency, 'double'); % WFrequency = waveform and continuous vars only, w/f sampling frequency fwrite(fid, calib, 'double'); % ADtoMV = waveform continuous vars only, coeff. to convert from A/D values to Millivolts fwrite(fid, nsamples, 'int32'); % NPointsWave = waveform only, number of points in each wave fwrite(fid, 0, 'int32'); % NMarkers = how many values are associated with each marker fwrite(fid, 0, 'int32'); % MarkerLength = how many characters are in each marker value fwrite(fid, buf2, 'char'); % Padding, 1x68 char end % of the nested function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nested function for writing the details %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function write_NexVarData switch hdr.VarHeader.Type case 5 % this code only supports one continuous segment index = 0; fwrite(fid, ts , 'int32'); % timestamps, one for each continuous segment fwrite(fid, index , 'int32'); % where to cut the segments, zero offset fwrite(fid, dat(varlop,:) , 'int16'); % data case 3 fwrite(fid, ts , 'int32'); % timestamps, one for each spike fwrite(fid, dat , 'int16'); % waveforms, one for each spike otherwise error('unsupported data type'); end % switch end % of the nested function end % of the primary function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subfunction for zero padding a char array to fixed length %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = padstr(str, num); if length(str)>num str = str(1:num); else str((end+1):num) = 0; end end % of the padstr subfunction
github
philippboehmsturm/antx-master
ft_convert_units.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/ft_convert_units.m
6,309
utf_8
0405af834cc33a98947a95647175b8d5
function [obj] = ft_convert_units(obj, target) % FT_CONVERT_UNITS changes the geometrical dimension to the specified SI unit. % The units of the input object is determined from the structure field % object.unit, or is estimated based on the spatial extend of the structure, % e.g. a volume conduction model of the head should be approximately 20 cm large. % % Use as % [object] = ft_convert_units(object, target) % % The following input objects are supported % simple dipole position % electrode definition % gradiometer array definition % volume conductor definition % dipole grid definition % anatomical mri % % Possible target units are 'm', 'dm', 'cm ' or 'mm'. % % See FT_READ_VOL, FT_READ_SENS % 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: ft_convert_units.m 3886 2011-07-20 13:58:47Z jansch $ % This function consists of three parts: % 1) determine the input units % 2) determine the requested scaling factor to obtain the output units % 3) try to apply the scaling to the known geometrical elements in the input object % determine the unit-of-dimension of the input object if isfield(obj, 'unit') && ~isempty(obj.unit) % use the units specified in the object unit = obj.unit; else % try to estimate the units from the object type = ft_voltype(obj); if ~strcmp(type, 'unknown') switch type case 'infinite' % there is nothing to do to convert the units unit = target; case 'singlesphere' size = obj.r; case 'multisphere' size = median(obj.r); case 'concentric' size = max(obj.r); case 'nolte' size = norm(range(obj.bnd.pnt)); case {'bem' 'dipoli' 'bemcp' 'asa' 'avo'} size = norm(range(obj.bnd(1).pnt)); otherwise error('cannot determine geometrical units of volume conduction model'); end % switch % determine the units by looking at the size unit = ft_estimate_units(size); elseif ft_senstype(obj, 'meg') size = norm(range(obj.pnt)); unit = ft_estimate_units(size); elseif ft_senstype(obj, 'eeg') size = norm(range(obj.pnt)); unit = ft_estimate_units(size); elseif isfield(obj, 'pnt') && ~isempty(obj.pnt) size = norm(range(obj.pnt)); unit = ft_estimate_units(size); elseif isfield(obj, 'pos') && ~isempty(obj.pos) size = norm(range(obj.pos)); unit = ft_estimate_units(size); elseif isfield(obj, 'transform') && ~isempty(obj.transform) % construct the corner points of the voxel grid in head coordinates xi = 1:obj.dim(1); yi = 1:obj.dim(2); zi = 1:obj.dim(3); pos = [ xi( 1) yi( 1) zi( 1) xi( 1) yi( 1) zi(end) xi( 1) yi(end) zi( 1) xi( 1) yi(end) zi(end) xi(end) yi( 1) zi( 1) xi(end) yi( 1) zi(end) xi(end) yi(end) zi( 1) xi(end) yi(end) zi(end) ]; pos = warp_apply(obj.transform, pos); size = norm(range(pos)); unit = ft_estimate_units(size); elseif isfield(obj, 'fid') && isfield(obj.fid, 'pnt') && ~isempty(obj.fid.pnt) size = norm(range(obj.fid.pnt)); unit = ft_estimate_units(size); else error('cannot determine geometrical units'); end % recognized type of volume conduction model or sensor array end % determine input units if nargin<2 % just remember the units in the output and return obj.unit = unit; return elseif strcmp(unit, target) % no conversion is needed obj.unit = unit; return end % give some information about the conversion fprintf('converting units from ''%s'' to ''%s''\n', unit, target) if strcmp(unit, 'm') unit2meter = 1; elseif strcmp(unit, 'dm') unit2meter = 0.1; elseif strcmp(unit, 'cm') unit2meter = 0.01; elseif strcmp(unit, 'mm') unit2meter = 0.001; end % determine the unit-of-dimension of the output object if strcmp(target, 'm') meter2target = 1; elseif strcmp(target, 'dm') meter2target = 10; elseif strcmp(target, 'cm') meter2target = 100; elseif strcmp(target, 'mm') meter2target = 1000; end % combine the units into one scaling factor scale = unit2meter * meter2target; % volume conductor model if isfield(obj, 'r'), obj.r = scale * obj.r; end if isfield(obj, 'o'), obj.o = scale * obj.o; end if isfield(obj, 'bnd'), for i=1:length(obj.bnd), obj.bnd(i).pnt = scale * obj.bnd(i).pnt; end, end % gradiometer array if isfield(obj, 'pnt1'), obj.pnt1 = scale * obj.pnt1; end if isfield(obj, 'pnt2'), obj.pnt2 = scale * obj.pnt2; end if isfield(obj, 'prj'), obj.prj = scale * obj.prj; end % gradiometer array, electrode array, head shape or dipole grid if isfield(obj, 'pnt'), obj.pnt = scale * obj.pnt; end % fiducials if isfield(obj, 'fid') && isfield(obj.fid, 'pnt'), obj.fid.pnt = scale * obj.fid.pnt; end % dipole grid if isfield(obj, 'pos'), obj.pos = scale * obj.pos; end % anatomical MRI or functional volume if isfield(obj, 'transform'), H = diag([scale scale scale 1]); obj.transform = H * obj.transform; end if isfield(obj, 'transformorig'), H = diag([scale scale scale 1]); obj.transformorig = H * obj.transformorig; end % remember the unit obj.unit = target; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % Use as % r = range(x) % or you can also specify the dimension along which to look by % r = range(x, dim) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function r = range(x, dim) if nargin==1 r = max(x) - min(x); else r = max(x, [], dim) - min(x, [], dim); end
github
philippboehmsturm/antx-master
ft_apply_montage.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/ft_apply_montage.m
9,812
utf_8
c30fdecc34ab9678cc26828eea0538c1
function [sens] = ft_apply_montage(sens, montage, varargin) % FT_APPLY_MONTAGE changes the montage of an electrode or gradiometer array. A % montage can be used for EEG rereferencing, MEG synthetic gradients, MEG % planar gradients or unmixing using ICA. This function applies the montage % to the sensor array. The sensor array can subsequently be used for % forward computation and source reconstruction of the data. % % Use as % [sens] = ft_apply_montage(sens, montage, ...) % [data] = ft_apply_montage(data, montage, ...) % [montage] = ft_apply_montage(montage1, montage2, ...) % where the input is a FieldTrip sensor definition as obtained from FT_READ_SENS % or a FieldTrip raw data structure as obtained from FT_PREPROCESSING. % % A montage is specified as a structure with the fields % montage.tra = MxN matrix % montage.labelnew = Mx1 cell-array % montage.labelorg = Nx1 cell-array % % Additional options should be specified in key-value pairs and can be % 'keepunused' string, 'yes' or 'no' (default = 'no') % 'inverse' string, 'yes' or 'no' (default = 'no') % % If the first input is a montage, then the second input montage will be % applied to the first. In effect the resulting montage will first do % montage1, then montage2. % % See also FT_READ_SENS, FT_TRANSFORM_SENS % Copyright (C) 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: ft_apply_montage.m 3392 2011-04-27 10:26:53Z jansch $ % get optional input arguments keepunused = keyval('keepunused', varargin); if isempty(keepunused), keepunused = 'no'; end inverse = keyval('inverse', varargin); if isempty(inverse), inverse = 'no'; end feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'text'; end bname = keyval('balancename', varargin); if isempty(bname), bname = ''; end % check the consistency of the input sensor array or data if isfield(sens, 'labelorg') && isfield(sens, 'labelnew') % the input data structure is also a montage, i.e. apply the montages sequentially sens.label = sens.labelnew; end % check the consistency of the montage if size(montage.tra,1)~=length(montage.labelnew) error('the number of channels in the montage is inconsistent'); elseif size(montage.tra,2)~=length(montage.labelorg) error('the number of channels in the montage is inconsistent'); end if strcmp(inverse, 'yes') % apply the inverse montage, i.e. undo a previously applied montage tmp.labelnew = montage.labelorg; % swap around tmp.labelorg = montage.labelnew; % swap around tmp.tra = full(montage.tra); if rank(tmp.tra) < length(tmp.tra) warning('the linear projection for the montage is not full-rank, the resulting data will have reduced dimensionality'); tmp.tra = pinv(tmp.tra); else tmp.tra = inv(tmp.tra); end montage = tmp; end % use default transfer from sensors to channels if not specified if isfield(sens, 'pnt') && ~isfield(sens, 'tra') nchan = size(sens.pnt,1); sens.tra = sparse(eye(nchan)); end % select and keep the columns that are non-empty, i.e. remove the empty columns selcol = find(~all(montage.tra==0, 1)); montage.tra = montage.tra(:,selcol); montage.labelorg = montage.labelorg(selcol); clear selcol % select and remove the columns corresponding to channels that are not present in the original data remove = setdiff(montage.labelorg, intersect(montage.labelorg, sens.label)); selcol = match_str(montage.labelorg, remove); % we cannot just remove the colums, all rows that depend on it should also be removed selrow = false(length(montage.labelnew),1); for i=1:length(selcol) selrow = selrow & (montage.tra(:,selcol(i))~=0); end % convert from indices to logical vector selcol = indx2logical(selcol, length(montage.labelorg)); % remove rows and columns montage.labelorg = montage.labelorg(~selcol); montage.labelnew = montage.labelnew(~selrow); montage.tra = montage.tra(~selrow, ~selcol); clear remove selcol selrow i % add columns for the channels that are present in the data but not involved in the montage, and stick to the original order in the data [add, ix] = setdiff(sens.label, montage.labelorg); add = sens.label(sort(ix)); m = size(montage.tra,1); n = size(montage.tra,2); k = length(add); if strcmp(keepunused, 'yes') % add the channels that are not rereferenced to the input and output montage.tra((m+(1:k)),(n+(1:k))) = eye(k); montage.labelorg = cat(1, montage.labelorg(:), add(:)); montage.labelnew = cat(1, montage.labelnew(:), add(:)); else % add the channels that are not rereferenced to the input montage only montage.tra(:,(n+(1:k))) = zeros(m,k); montage.labelorg = cat(1, montage.labelorg(:), add(:)); end clear add m n k % determine whether all channels are unique m = size(montage.tra,1); n = size(montage.tra,2); if length(unique(montage.labelnew))~=m error('not all output channels of the montage are unique'); end if length(unique(montage.labelorg))~=n error('not all input channels of the montage are unique'); end % determine whether all channels that have to be rereferenced are available if length(intersect(sens.label, montage.labelorg))~=length(montage.labelorg) error('not all channels that are required in the montage are available in the data'); end % reorder the columns of the montage matrix [selsens, selmont] = match_str(sens.label, montage.labelorg); montage.tra = double(sparse(montage.tra(:,selmont))); montage.labelorg = montage.labelorg(selmont); if isfield(sens, 'labelorg') && isfield(sens, 'labelnew') % apply the montage on top of the other montage sens = rmfield(sens, 'label'); if isa(sens.tra, 'single') sens.tra = full(montage.tra) * sens.tra; else sens.tra = montage.tra * sens.tra; end sens.labelnew = montage.labelnew; elseif isfield(sens, 'tra') % apply the montage to the sensor array if isa(sens.tra, 'single') sens.tra = full(montage.tra) * sens.tra; else sens.tra = montage.tra * sens.tra; end sens.label = montage.labelnew; % keep track of the order of the balancing and which one is the current % one if strcmp(inverse, 'yes') if isfield(sens, 'balance')% && isfield(sens.balance, 'previous') if isfield(sens.balance, 'previous') && numel(sens.balance.previous)>=1 sens.balance.current = sens.balance.previous{1}; sens.balance.previous = sens.balance.previous(2:end); elseif isfield(sens.balance, 'previous') sens.balance.current = 'none'; sens.balance = rmfield(sens.balance, 'previous'); else sens.balance.current = 'none'; end end elseif ~strcmp(inverse, 'yes') && ~isempty(bname) if isfield(sens, 'balance') && isfield(sens.balance, 'current') if ~isfield(sens.balance, 'previous') sens.balance.previous = {}; end sens.balance.previous = [{sens.balance.current} sens.balance.previous]; sens.balance.current = bname; sens.balance.(bname) = montage; end end elseif isfield(sens, 'trial') % apply the montage to the raw data that was preprocessed using fieldtrip data = sens; clear sens Ntrials = numel(data.trial); ft_progress('init', feedback, 'processing trials'); for i=1:Ntrials ft_progress(i/Ntrials, 'processing trial %d from %d\n', i, Ntrials); if isa(data.trial{i}, 'single') % sparse matrices and single precision do not match data.trial{i} = full(montage.tra) * data.trial{i}; else data.trial{i} = montage.tra * data.trial{i}; end end ft_progress('close'); data.label = montage.labelnew; % rename the output variable sens = data; clear data elseif isfield(sens, 'fourierspctrm') % apply the montage to the spectrally decomposed data freq = sens; clear sens if strcmp(freq.dimord, 'rpttap_chan_freq') siz = size(freq.fourierspctrm); nrpt = siz(1); nchan = siz(2); nfreq = siz(3); output = zeros(nrpt, size(montage.tra,1), nfreq); for foilop=1:nfreq output(:,:,foilop) = freq.fourierspctrm(:,:,foilop) * montage.tra'; end elseif strcmp(freq.dimord, 'rpttap_chan_freq_time') siz = size(freq.fourierspctrm); nrpt = siz(1); nchan = siz(2); nfreq = siz(3); ntime = siz(4); output = zeros(nrpt, size(montage.tra,1), nfreq, ntime); for foilop=1:nfreq for toilop = 1:ntime output(:,:,foilop,toilop) = freq.fourierspctrm(:,:,foilop,toilop) * montage.tra'; end end else error('unsupported dimord in frequency data (%s)', freq.dimord); end % replace the Fourier spectrum freq.fourierspctrm = output; freq.label = montage.labelnew; % rename the output variable sens = freq; clear freq else error('unrecognized input'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = indx2logical(x, n) y = false(1,n); y(x) = true;
github
philippboehmsturm/antx-master
read_biosemi_bdf.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_biosemi_bdf.m
10,860
utf_8
ddbde2abde4535318e1c0fb21c9218bd
function dat = read_biosemi_bdf(filename, hdr, begsample, endsample, chanindx); % READ_BIOSEMI_BDF reads specified samples from a BDF continous datafile % It neglects all trial boundaries as if the data was acquired in % non-continous mode. % % Use as % [hdr] = read_biosemi_bdf(filename); % where % filename name of the datafile, including the .bdf 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 % % Or use as % [dat] = read_biosemi_bdf(filename, hdr, begsample, endsample, chanindx); % where % filename name of the datafile, including the .bdf 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 % 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_biosemi_bdf.m 945 2010-04-21 17:41:20Z roboos $ if nargin==1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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; EDF.AS.spb = sum(EDF.SPR); % Samples per Block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert the header to Fieldtrip-style %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(EDF.SampleRate~=EDF.SampleRate(1)) error('channels with different sampling rate not supported'); end hdr.Fs = EDF.SampleRate(1); hdr.nChans = EDF.NS; hdr.label = cellstr(EDF.Label); % it is continuous data, therefore append all records in one trial hdr.nTrials = 1; hdr.nSamples = EDF.NRec * EDF.Dur * EDF.SampleRate(1); hdr.nSamplesPre = 0; hdr.orig = EDF; % return the header dat = hdr; else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % retrieve the original header EDF = hdr.orig; % determine the trial containing the begin and end sample epochlength = EDF.Dur * EDF.SampleRate(1); begepoch = floor((begsample-1)/epochlength) + 1; endepoch = floor((endsample-1)/epochlength) + 1; nepochs = endepoch - begepoch + 1; nchans = EDF.NS; if nargin<5 chanindx = 1:nchans; end % allocate memory to hold the data dat = zeros(length(chanindx),nepochs*epochlength); % read and concatenate all required data epochs for i=begepoch:endepoch offset = EDF.HeadLen + (i-1)*epochlength*nchans*3; if length(chanindx)==1 % this is more efficient if only one channel has to be read, e.g. the status channel offset = offset + (chanindx-1)*epochlength*3; 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 and then select the desired channels buf = readLowLevel(filename, offset, epochlength*nchans); % 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 length(chanindx)>1 % using a sparse matrix speeds up the multiplication calib = sparse(diag(EDF.Cal(chanindx,:))); dat = calib * dat; else % in case of one channel the calibration would result in a sparse array calib = diag(EDF.Cal(chanindx,:)); dat = calib * dat; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for reading the 24 bit values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function buf = readLowLevel(filename, offset, numwords); if offset < 2*1024^3 % use the external mex file, only works for <2GB buf = read_24bit(filename, offset, numwords); % this would be the only difference between the bdf and edf implementation % 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,'bit24=>double'); fclose(fp); if (num<numwords) error(['failed opening ' filename]); return end end
github
philippboehmsturm/antx-master
read_ctf_ascii.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_ctf_ascii.m
3,218
utf_8
47e7379c0ed92058f4f1d9cca84b2030
function [file] = read_ctf_ascii(filename); % READ_CTF_ASCII reads general data from an CTF configuration file % % The file should be formatted like % Group % { % item1 : value1a value1b value1c % item2 : value2a value2b value2c % item3 : value3a value3b value3c % item4 : value4a value4b value4c % } % % This fileformat structure is used in % params.avg % default.hdm % multiSphere.hdm % processing.cfg % and maybe for other files as well. % Copyright (C) 2003, 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_ctf_ascii.m 1362 2010-07-06 09:04:24Z roboos $ fid = fopen(filename, 'r'); if fid==-1 error(sprintf('could not open file %s', filename)); end line = ''; while ischar(line) line = cleanline(fgetl(fid)); if isempty(line) || (length(line)==1 && all(line==-1)) continue end % the line is not empty, which means that we have encountered a chunck of information subline = cleanline(fgetl(fid)); % read the { subline = cleanline(fgetl(fid)); % read the first item while isempty(findstr(subline, '}')) if ~isempty(subline) [item, value] = strtok(subline, ':'); value(1) = ' '; % remove the : value = strtrim(value); item = strtrim(item); % turn warnings off ws = warning('off'); % the item name should be a real string, otherwise I cannot put it into the structure if strcmp(sprintf('%d', str2num(deblank(item))), deblank(item)) % add something to the start of the string to distinguish it from a number item = ['item_' item]; end % the value can be either a number or a string, and is put into the structure accordingly if isempty(str2num(value)) % the value appears to be a string eval(sprintf('file.%s.%s = [ ''%s'' ];', line, item, value)); else % the value appears to be a number or a list of numbers eval(sprintf('file.%s.%s = [ %s ];', line, item, value)); end % revert to previous warning state warning(ws); end subline = cleanline(fgetl(fid)); % read the first item end end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function line = cleanline(line) if isempty(line) || (length(line)==1 && all(line==-1)) return end comment = findstr(line, '//'); if ~isempty(comment) line(min(comment):end) = ' '; end line = strtrim(line);
github
philippboehmsturm/antx-master
read_mpi_dap.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_mpi_dap.m
7,084
utf_8
84049987cc6e97d585788c8400c1b1da
function [dap] = read_mpi_dap(filename) % READ_MPI_DAP read the analog channels from a DAP file % and returns the values in microvolt (uV) % % Use as % [dap] = read_mpi_dap(filename) % Copyright (C) 2005-2007, 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_mpi_dap.m 945 2010-04-21 17:41:20Z roboos $ fid = fopen(filename, 'rb', 'ieee-le'); % read the file header filehdr = readheader(fid); analog = {}; analoghdr = {}; analogsweephdr = {}; spike = {}; spikehdr = {}; spikesweephdr = {}; W = filehdr.nexps; S = filehdr.nsweeps; for w=1:filehdr.nexps % read the experiment header exphdr{w} = readheader(fid); if filehdr.nanalog if filehdr.analogmode==-1 % record mode for s=1:filehdr.nsweeps % read the analogsweepheader analogsweephdr{s} = readheader(fid); for j=1:filehdr.nanalog % read the analog header analoghdr{w,s,j} = readheader(fid); % read the analog data analog{w,s,j} = fread(fid, analoghdr{w,s,j}.datasize, 'int16'); % calibrate the analog data analog{w,s,j} = analog{w,s,j} * 2.5/2048; end end % for s=1:S elseif filehdr.analogmode==0 % average mode s = 1; for j=1:filehdr.nanalog % read the analog header analoghdr{w,s,j} = readheader(fid); % read the analog data analog{w,s,j} = fread(fid, analoghdr{w,s,j}.datasize, 'int16'); % calibrate the analog data analog{w,s,j} = analog{w,s,j} * 2.5/2048; end else error('unknown analog mode'); end end if filehdr.nspike for s=1:filehdr.nsweeps spikesweephdr{s} = readheader(fid); for j=1:filehdr.nspike % read the spike header spikehdr{w,s,j} = readheader(fid); % read the spike data spike{w,s,j} = fread(fid, spikehdr{w,s,j}.datasize, 'int16'); end end % for s=1:S end end % for w=1:W dap.filehdr = filehdr; dap.exphdr = exphdr; dap.analogsweephdr = analogsweephdr; dap.analoghdr = analoghdr; dap.analog = analog; dap.spikesweephdr = spikesweephdr; dap.spikehdr = spikehdr; dap.spike = spike; fclose(fid); return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = readheader(fid); % determine the header type, header size and data size hdr.headertype = fread(fid, 1, 'uchar'); dummy = fread(fid, 1, 'uchar'); hdr.headersize = fread(fid, 1, 'int16') + 1; % expressed in words, not bytes hdr.datasize = fread(fid, 1, 'int16'); % expressed in words, not bytes % read the header details switch hdr.headertype case 1 % fileheader % fprintf('fileheader at %d\n' ,ftell(fid)-6); dummy = fread(fid, 1, 'uchar')'; % 6 hdr.nexps = fread(fid, 1, 'uchar')'; % 7 hdr.progname = fread(fid, 7, 'uchar')'; % 8-14 hdr.version = fread(fid, 1, 'uchar')'; % 15 hdr.progversion = fread(fid, 2, 'uchar')'; % 16-17 hdr.fileversion = fread(fid, 2, 'uchar')'; % 18-19 hdr.date = fread(fid, 1, 'int16'); % 20-21 hdr.time = fread(fid, 1, 'int16'); % 22-23 hdr.nanalog = fread(fid, 1, 'uint8'); % 24 hdr.nspike = fread(fid, 1, 'uint8'); % 25 hdr.nbins = fread(fid, 1, 'int16'); % 26-27 hdr.binwidth = fread(fid, 1, 'int16'); % 28-29 dummy = fread(fid, 1, 'int16'); % 30-31 hdr.nsweeps = fread(fid, 1, 'int16'); % 32-33 hdr.analogmode = fread(fid, 1, 'uchar')'; % 34 "0 for average, -1 for record" dummy = fread(fid, 1, 'uchar')'; % 35 dummy = fread(fid, 1, 'int16'); % 36-37 dummy = fread(fid, 1, 'int16'); % 38-39 dummy = fread(fid, 1, 'int16'); % 40-41 case 65 % expheader % fprintf('expheader at %d\n' ,ftell(fid)-6); hdr.time = fread(fid, 1, 'int16'); % 6-7 hdr.parallel = fread(fid, 1, 'int16'); % 8-9 hdr.id = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 case 129 % analogchannelheader % fprintf('analogchannelheader at %d\n' ,ftell(fid)-6); dummy = fread(fid, 1, 'int16'); % 6-7 hdr.channum = fread(fid, 1, 'uchar'); % 8 dummy = fread(fid, 1, 'uchar'); % 9 dummy = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 case 161 % spikechannelheader % fprintf('spikechannelheader at %d\n' ,ftell(fid)-6); dummy = fread(fid, 1, 'int16'); % 6-7 hdr.channum = fread(fid, 1, 'uchar'); % 8 dummy = fread(fid, 1, 'uchar'); % 9 dummy = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 case 137 % analogsweepheader % fprintf('analogsweepheader at %d\n' ,ftell(fid)-6); hdr.sweepnum = fread(fid, 1, 'int16'); % 6-7 hdr.parallel = fread(fid, 1, 'int16'); % 8-9 dummy = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 case 169 % spikesweepheader % fprintf('spikesweepheader at %d\n' ,ftell(fid)-6); hdr.sweepnum = fread(fid, 1, 'int16'); % 6-7 hdr.parallel = fread(fid, 1, 'int16'); % 8-9 dummy = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 otherwise error(sprintf('unsupported format for header (%d)', hdr.headertype)); end
github
philippboehmsturm/antx-master
read_neuralynx_bin.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_neuralynx_bin.m
6,705
utf_8
a3589b0e825871f801d479e38ea63033
function [dat] = read_neuralynx_bin(filename, begsample, endsample); % READ_NEURALYNX_BIN % % Use as % hdr = read_neuralynx_bin(filename) % or % dat = read_neuralynx_bin(filename, begsample, endsample) % % This is not a formal Neuralynx file format, but at the % F.C. Donders Centre we use it in conjunction with Neuralynx, % SPIKESPLITTING and SPIKEDOWNSAMPLE. % % The first version of this file format contained in the first 8 bytes the % channel label as string. Subsequently it contained 32 bit integer values. % % The second version of this file format starts with 8 bytes describing (as % a space-padded string) the data type. The channel label is contained in % the filename as dataset.chanlabel.bin. % % The third version of this file format starts with 7 bytes describing (as % a zero-padded string) the data type, followed by the 8th byte which % describes the downscaling for the 8 and 16 bit integer representations. % The downscaling itself is represented as uint8 and should be interpreted as % the number of bits to shift. The channel label is contained in the % filename as dataset.chanlabel.bin. % Copyright (C) 2007-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: read_neuralynx_bin.m 2885 2011-02-16 09:41:58Z roboos $ needhdr = (nargin==1); needdat = (nargin>=2); % this is used for backward compatibility oldformat = false; % the first 8 bytes contain the header fid = fopen(filename, 'rb', 'ieee-le'); magic = fread(fid, 8, 'uint8=>char')'; % the header describes the format of the subsequent samples subtype = []; if strncmp(magic, 'uint8', length('uint8')) format = 'uint8'; samplesize = 1; elseif strncmp(magic, 'int8', length('int8')) format = 'int8'; samplesize = 1; elseif strncmp(magic, 'uint16', length('uint16')) format = 'uint16'; samplesize = 2; elseif strncmp(magic, 'int16', length('int16')) format = 'int16'; samplesize = 2; elseif strncmp(magic, 'uint32', length('uint32')) format = 'uint32'; samplesize = 4; elseif strncmp(magic, 'int32', length('int32')) format = 'int32'; samplesize = 4; elseif strncmp(magic, 'uint64', length('uint64')) format = 'uint64'; samplesize = 8; elseif strncmp(magic, 'int64', length('int64')) format = 'int64'; samplesize = 8; elseif strncmp(magic, 'float32', length('float32')) format = 'float32'; samplesize = 4; elseif strncmp(magic, 'float64', length('float64')) format = 'float64'; samplesize = 8; else warning('could not detect sample format, assuming file format subtype 1 with ''int32'''); subtype = 1; % the file format is version 1 format = 'int32'; samplesize = 4; end % determine whether the file format is version 2 or 3 if isempty(subtype) if all(magic((length(format)+1):end)==' ') subtype = 2; else subtype = 3; end end % determine the channel name switch subtype case 1 % the first 8 bytes of the file contain the channel label (padded with spaces) label = strtrim(magic); case {2, 3} % the filename is formatted like "dataset.chanlabel.bin" [p, f, x1] = fileparts(filename); [p, f, x2] = fileparts(f); if isempty(x2) warning('could not determine channel label'); label = 'unknown'; else label = x2(2:end); end clear p f x1 x2 otherwise error('unknown file format subtype'); end % determine the downscale factor, i.e. the number of bits that the integer representation has to be shifted back to the left switch subtype case 1 % these never contained a multiplication factor but always corresponded % to the lowest N bits of the original 32 bit integer downscale = 0; case 2 % these might contain a multiplication factor but that factor cannot be retrieved from the file warning('downscale factor is unknown for ''%s'', assuming that no downscaling was applied', filename); downscale = 0; case 3 downscale = double(magic(8)); otherwise error('unknown file format subtype'); end [p1, f1, x1] = fileparts(filename); [p2, f2, x2] = fileparts(f1); headerfile = fullfile(p1, [f2, '.txt']); if exist(headerfile, 'file') orig = neuralynx_getheader(headerfile); % construct the header from the accompanying text file hdr = []; hdr.Fs = orig.SamplingFrequency; hdr.nChans = 1; hdr.nSamples = (filesize(filename)-8)/samplesize; hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.label = {label}; else % construct the header from the hard-coded defaults hdr = []; hdr.Fs = 32556; hdr.nChans = 1; hdr.nSamples = (filesize(filename)-8)/samplesize; hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.label = {label}; end if ~needdat % also return the file details hdr.orig.subtype = subtype; hdr.orig.magic = magic; hdr.orig.format = format; hdr.orig.downscale = downscale; % return only the header details dat = hdr; else % read and return the data if begsample<1 begsample = 1; end if isinf(endsample) endsample = hdr.nSamples; end fseek(fid, 8+(begsample-1)*samplesize, 'bof'); % skip to the beginning of the interesting data format = sprintf('%s=>%s', format, format); dat = fread(fid, [1 endsample-begsample+1], format); if downscale>1 % the data was downscaled with 2^N, i.e. shifted N bits to the right in case of integer representations % now it should be upscaled again with the same amount dat = dat.*(2^downscale); end if length(dat)<(endsample-begsample+1) error('could not read the requested data'); end end % needdat fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to determine the file size in bytes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [siz] = filesize(filename) l = dir(filename); if l.isdir error(sprintf('"%s" is not a file', filename)); end siz = l.bytes;
github
philippboehmsturm/antx-master
read_besa_avr.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_besa_avr.m
3,929
utf_8
9e36880bf3e6eb7d211a5dea7ce2d885
function [avr] = read_besa_avr(filename) % READ_BESA_AVR reads average EEG data in BESA format % % Use as % [avr] = read_besa_avr(filename) % % This will return a structure with the header information in % avr.npnt % avr.tsb % avr.di % avr.sb % avr.sc % avr.Nchan (optional) % avr.label (optional) % and the ERP data is contained in the Nchan X Nsamples matrix % avr.data % Copyright (C) 2003-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_besa_avr.m 2885 2011-02-16 09:41:58Z roboos $ fid = fopen(filename, 'rt'); % the first line contains header information headstr = fgetl(fid); ok = 0; if ~ok try buf = sscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f Nchan= %f SegmentName= %s\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); avr.Nchan = buf(6); avr.SegmentName = buf(7); ok = 1; catch ok = 0; end end if ~ok try buf = fscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f Nchan= %f\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); avr.Nchan = buf(6); ok = 1; catch ok = 0; end end if ~ok try buf = sscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); ok = 1; catch ok = 0; end end if ~ok error('Could not interpret the header information.'); end % rewind to the beginning of the file, skip the header line fseek(fid, 0, 'bof'); fgetl(fid); % the second line may contain channel names chanstr = fgetl(fid); chanstr = deblank(fliplr(deblank(fliplr(chanstr)))); if (chanstr(1)>='A' && chanstr(1)<='Z') || (chanstr(1)>='a' && chanstr(1)<='z') haschan = 1; avr.label = str2cell(strrep(deblank(chanstr), '''', ''))'; else [root, name] = fileparts(filename); haschan = 0; elpfile = fullfile(root, [name '.elp']); elafile = fullfile(root, [name '.ela']); if exist(elpfile, 'file') % read the channel names from the accompanying ELP file lbl = importdata(elpfile); avr.label = strrep(lbl.textdata(:,2) ,'''', ''); elseif exist(elafile, 'file') % read the channel names from the accompanying ELA file lbl = importdata(elafile); lbl = strrep(lbl ,'MEG ', ''); % remove the channel type lbl = strrep(lbl ,'EEG ', ''); % remove the channel type avr.label = lbl; else warning('Could not create channels labels.'); end end % seek to the beginning of the data fseek(fid, 0, 'bof'); fgetl(fid); % skip the header line if haschan fgetl(fid); % skip the channel name line end buf = fscanf(fid, '%f'); nchan = length(buf)/avr.npnt; avr.data = reshape(buf, avr.npnt, nchan)'; fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to cut a string into pieces at the spaces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function c = str2cell(s) c = {}; [t, r] = strtok(s, ' '); while ~isempty(t) c{end+1} = t; [t, r] = strtok(r, ' '); end
github
philippboehmsturm/antx-master
read_eeglabdata.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_eeglabdata.m
3,188
utf_8
8feab64154efa64494ff73501c82e253
% read_eeglabdata() - import EEGLAB dataset files % % Usage: % >> dat = read_eeglabdata(filename); % % Inputs: % filename - [string] file name % % Optional inputs: % 'begtrial' - [integer] first trial to read % 'endtrial' - [integer] last trial to read % 'chanindx' - [integer] list with channel indices to read % 'header' - FILEIO structure header % % Outputs: % dat - data over the specified range % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2008- %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2008 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 dat = read_eeglabdata(filename, varargin); if nargin < 1 help read_eeglabdata; return; end; header = keyval('header', varargin); begsample = keyval('begsample', varargin); endsample = keyval('endsample', varargin); begtrial = keyval('begtrial', varargin); endtrial = keyval('endtrial', varargin); chanindx = keyval('chanindx', varargin); if isempty(header) header = read_eeglabheader(filename); end; if ischar(header.orig.data) if strcmpi(header.orig.data(end-2:end), 'set'), header.ori = load('-mat', filename); else % assuming that the data file is in the current directory fid = fopen(header.orig.data); % assuming the .dat and .set files are located in the same directory if fid == -1 pathstr = fileparts(filename); fid = fopen(fullfile(pathstr, header.orig.data)); end if fid == -1 fid = fopen(fullfile(header.orig.filepath, header.orig.data)); % end if fid == -1, error(['Cannot not find data file: ' header.orig.data]); end; % only read the desired trials if strcmpi(header.orig.data(end-2:end), 'dat') dat = fread(fid,[header.nSamples*header.nTrials header.nChans],'float32')'; else dat = fread(fid,[header.nChans header.nSamples*header.nTrials],'float32'); end; dat = reshape(dat, header.nChans, header.nSamples, header.nTrials); fclose(fid); end; else dat = header.orig.data; dat = reshape(dat, header.nChans, header.nSamples, header.nTrials); end; if isempty(begtrial), begtrial = 1; end; if isempty(endtrial), endtrial = header.nTrials; end; if isempty(begsample), begsample = 1; end; if isempty(endsample), endsample = header.nSamples; end; dat = dat(:,begsample:endsample,begtrial:endtrial); if ~isempty(chanindx) % select the desired channels dat = dat(chanindx,:,:); end
github
philippboehmsturm/antx-master
readbdf.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/readbdf.m
3,638
utf_8
f5fc9fc5e8344dcc1d315c4c56c75b28
% readbdf() - Loads selected Records of an EDF or BDF File (European Data Format % for Biosignals) into MATLAB % Usage: % >> [DAT,signal] = readedf(EDF_Struct,Records,Mode); % Notes: % Records - List of Records for Loading % Mode - 0 Default % 1 No AutoCalib % 2 Concatenated (channels with lower sampling rate % if more than 1 record is loaded) % Output: % DAT - EDF data structure % signal - output signal % % Author: Alois Schloegl, 03.02.1998, updated T.S. Lorig Sept 6, 2002 for BDF read % % See also: openbdf(), sdfopen(), sdfread(), eeglab() % Version 2.11 % 03.02.1998 % Copyright (c) 1997,98 by Alois Schloegl % [email protected] % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This program has been modified from the original version for .EDF files % The modifications are to the number of bytes read on line 53 (from 2 to % 3) and to the type of data read - line 54 (from int16 to bit24). Finally the name % was changed from readedf to readbdf % T.S. Lorig Sept 6, 2002 % % Header modified for eeglab() compatibility - Arnaud Delorme 12/02 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [DAT,S]=readbdf(DAT,Records,Mode) if nargin<3 Mode=0; end; EDF=DAT.Head; RecLen=max(EDF.SPR); S=NaN*zeros(RecLen,EDF.NS); DAT.Record=zeros(length(Records)*RecLen,EDF.NS); DAT.Valid=uint8(zeros(1,length(Records)*RecLen)); DAT.Idx=Records(:)'; for nrec=1:length(Records), NREC=(DAT.Idx(nrec)-1); if NREC<0 fprintf(2,'Warning READEDF: invalid Record Number %i \n',NREC);end; fseek(EDF.FILE.FID,(EDF.HeadLen+NREC*EDF.AS.spb*3),'bof'); [s, count]=fread(EDF.FILE.FID,EDF.AS.spb,'bit24'); try, S(EDF.AS.IDX2)=s; catch, error('File is incomplete (try reading begining of file)'); end; %%%%% Test on Over- (Under-) Flow % V=sum([(S'==EDF.DigMax(:,ones(RecLen,1))) + (S'==EDF.DigMin(:,ones(RecLen,1)))])==0; V=sum([(S(:,EDF.Chan_Select)'>=EDF.DigMax(EDF.Chan_Select,ones(RecLen,1))) + ... (S(:,EDF.Chan_Select)'<=EDF.DigMin(EDF.Chan_Select,ones(RecLen,1)))])==0; EDF.ERROR.DigMinMax_Warning(find(sum([(S'>EDF.DigMax(:,ones(RecLen,1))) + (S'<EDF.DigMin(:,ones(RecLen,1)))]')>0))=1; % invalid=[invalid; find(V==0)+l*k]; if floor(Mode/2)==1 for k=1:EDF.NS, DAT.Record(nrec*EDF.SPR(k)+(1-EDF.SPR(k):0),k)=S(1:EDF.SPR(k),k); end; else DAT.Record(nrec*RecLen+(1-RecLen:0),:)=S; end; DAT.Valid(nrec*RecLen+(1-RecLen:0))=V; end; if rem(Mode,2)==0 % Autocalib DAT.Record=[ones(RecLen*length(Records),1) DAT.Record]*EDF.Calib; end; DAT.Record=DAT.Record'; return;
github
philippboehmsturm/antx-master
warning_once.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/warning_once.m
3,060
utf_8
f046009e4f6ffe5745af9c5e527614e8
function [ws warned] = warning_once(varargin) % % Use as % warning_once(string) % or % warning_once(string, timeout) % or % warning_once(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. The default timeout value is 60 seconds. % % Can be used instead of the MATLAB built-in function WARNING, thus as % s = warning_once(...) % or % warning_once(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. % In other words, warning_once accepts as an input the same structure it % returns as an output. This returns or restores the states of warnings to % their previous values. % % Can also be used as % [s w] = warning_once(...) % where w is a boolean that indicates whether a warning as been % thrown or not. persistent stopwatch previous if nargin < 1 error('You need to specify at least a warning message'); end warned = false; if isstruct(varargin{1}) warning(varargin{1}); return; end if nargin==3 msgid = varargin{1}; msgstr = varargin{2}; timeout = varargin{3}; elseif nargin==2 msgstr= ''; % this becomes irrelevant msgid = varargin{1}; % this becomes the real msgstr timeout = varargin{2}; elseif nargin==1 msgstr= ''; % this becomes irrelevant msgid = varargin{1}; % this becomes the real msgstr timeout = 60; % default timeout in seconds end if isempty(timeout) error('Timeout ill-specified'); end if isempty(stopwatch) stopwatch = tic; end if isempty(previous) previous = struct; end now = toc(stopwatch); % measure time since first function call fname = fixname([msgid '_' msgstr]); % make a nice string that is allowed as structure fieldname, copy the subfunction from ft_hastoolbox fname = decomma(fname); if length(fname) > 63 % MATLAB max name fname = fname(1:63); end if isfield(previous, fname) && now>previous.(fname).timeout % it has timed out, give the warning again ws = warning(msgid, msgstr); previous.(fname).timeout = now+timeout; previous.(fname).ws = ws; warned = true; elseif ~isfield(previous, fname) % the warning has not been issued before ws = warning(msgid, msgstr); previous.(fname).timeout = now+timeout; previous.(fname).ws = ws; warned = true; else % the warning has been issued before, but has not timed out yet ws = previous.(fname).ws; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out = fixname(toolbox) out = lower(toolbox); out(out=='-') = '_'; % fix dashes out(out==' ') = '_'; % fix spaces out(out=='/') = '_'; % fix forward slashes out(out=='\') = '_'; % fix backward slashes while(out(1) == '_'), out = out(2:end); end; % remove preceding underscore while(out(end) == '_'), out = out(1:end-1); end; % remove subsequent underscore end function nameout = decomma(name) nameout = name; indx = findstr(name,','); nameout(indx)=[]; end
github
philippboehmsturm/antx-master
ft_hastoolbox.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/ft_hastoolbox.m
15,262
utf_8
c0b501e52231cc82315936a092af6214
function [status] = ft_hastoolbox(toolbox, autoadd, silent) % FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally % it will try to determine the path to the toolbox and install it % automatically. % % Use as % [status] = ft_hastoolbox(toolbox, autoadd, silent) % % autoadd = 0 means that it will not be added % autoadd = 1 means that give an error if it cannot be added % autoadd = 2 means that give a warning if it cannot be added % autoadd = 3 means that it remains silent if it cannot be added % % silent = 0 means that it will give some feedback about adding the toolbox % silent = 1 means that it will not give feedback % Copyright (C) 2005-2010, 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_hastoolbox.m 3873 2011-07-19 14:23:16Z tilsan $ % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before persistent previous previouspath if ~isequal(previouspath, path) previous = []; end if isempty(previous) previous = struct; elseif isfield(previous, fixname(toolbox)) status = previous.(fixname(toolbox)); return end % this points the user to the website where he/she can download the toolbox url = { 'AFNI' 'see http://afni.nimh.nih.gov' 'DSS' 'see http://www.cis.hut.fi/projects/dss' 'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab' 'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox' 'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm' 'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd' 'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com' 'BIOSIG' 'see http://biosig.sourceforge.net' 'EEG' 'see http://eeg.sourceforge.net' 'EEGSF' 'see http://eeg.sourceforge.net' % alternative name 'MRI' 'see http://eeg.sourceforge.net' % alternative name 'NEUROSHARE' 'see http://www.neuroshare.org' 'BESA' 'see http://www.megis.de, or contact Karsten Hoechstetter' 'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde' 'YOKOGAWA' 'see http://www.yokogawa.co.jp, or contact Nobuhiko Takahashi' 'YOKOGAWA_MEG_READER' 'contact Masayuki dot Mochiduki at jp.yokogawa.com' 'BEOWULF' 'see http://oostenveld.net, or contact Robert Oostenveld' 'MENTAT' 'see http://oostenveld.net, or contact Robert Oostenveld' 'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth' '4D-VERSION' 'contact Christian Wienbruch' 'SIGNAL' 'see http://www.mathworks.com/products/signal' 'OPTIM' 'see http://www.mathworks.com/products/optim' 'IMAGE' 'see http://www.mathworks.com/products/image' 'SPLINES' 'see http://www.mathworks.com/products/splines' 'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica' 'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm' 'FILEIO' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'FORWINV' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne' 'BCI2000' 'see http://bci2000.org' 'NLXNETCOM' 'see http://www.neuralynx.com' 'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external' 'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php' 'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydes?ter' 'BEMCP' 'contact Christophe Phillips' 'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435' 'PRTOOLS' 'see http://www.prtools.org' 'ITAB' 'contact Stefania Della Penna' 'BSMART' 'see http://www.brain-smart.org' 'PEER' 'see http://fieldtrip.fcdonders.nl/development/peer' 'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki' 'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page' 'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS' 'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti' 'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0' 'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab' 'BCT' 'see http://www.brain-connectivity-toolbox.net/' }; if nargin<2 % default is not to add the path automatically autoadd = 0; end if nargin<3 % default is not to be silent silent = 0; end % determine whether the toolbox is installed toolbox = upper(toolbox); switch toolbox case 'AFNI' status = (exist('BrikLoad') && exist('BrikInfo')); case 'DSS' status = exist('denss', 'file') && exist('dss_create_state', 'file'); case 'EEGLAB' status = exist('runica', 'file'); case 'NWAY' status = exist('parafac', 'file'); case 'SPM' status = exist('spm.m'); % any version of SPM is fine case 'SPM99' status = exist('spm.m') && strcmp(spm('ver'),'SPM99'); case 'SPM2' status = exist('spm.m') && strcmp(spm('ver'),'SPM2'); case 'SPM5' status = exist('spm.m') && strcmp(spm('ver'),'SPM5'); case 'SPM8' status = exist('spm.m') && strncmp(spm('ver'),'SPM8', 4); case 'MEG-PD' status = (exist('rawdata') && exist('channames')); case 'MEG-CALC' status = (exist('megmodel') && exist('megfield') && exist('megtrans')); case 'BIOSIG' status = (exist('sopen') && exist('sread')); case 'EEG' status = (exist('ctf_read_res4') && exist('ctf_read_meg4')); case 'EEGSF' % alternative name status = (exist('ctf_read_res4') && exist('ctf_read_meg4')); case 'MRI' % other functions in the mri section status = (exist('avw_hdr_read') && exist('avw_img_read')); case 'NEUROSHARE' status = (exist('ns_OpenFile') && exist('ns_SetLibrary') && exist('ns_GetAnalogData')); case 'BESA' status = (exist('readBESAtfc') && exist('readBESAswf')); case 'EEPROBE' status = (exist('read_eep_avr') && exist('read_eep_cnt')); case 'YOKOGAWA' status = (exist('hasyokogawa') && hasyokogawa('16bitBeta6')); case 'YOKOGAWA16BITBETA3' status = (exist('hasyokogawa') && hasyokogawa('16bitBeta3')); case 'YOKOGAWA16BITBETA6' status = (exist('hasyokogawa') && hasyokogawa('16bitBeta6')); case 'YOKOGAWA_MEG_READER' status = (exist('hasyokogawa') && hasyokogawa('1.4')); case 'BEOWULF' status = (exist('evalwulf') && exist('evalwulf') && exist('evalwulf')); case 'MENTAT' status = (exist('pcompile') && exist('pfor') && exist('peval')); case 'SON2' status = (exist('SONFileHeader') && exist('SONChanList') && exist('SONGetChannel')); case '4D-VERSION' status = (exist('read4d') && exist('read4dhdr')); case {'STATS', 'STATISTICS'} status = license('checkout', 'statistics_toolbox'); % also check the availability of a toolbox license case {'OPTIM', 'OPTIMIZATION'} status = license('checkout', 'optimization_toolbox'); % also check the availability of a toolbox license case {'SPLINES', 'CURVE_FITTING'} status = license('checkout', 'curve_fitting_toolbox'); % also check the availability of a toolbox license case 'SIGNAL' status = license('checkout', 'signal_toolbox'); % also check the availability of a toolbox license case 'IMAGE' status = license('checkout', 'image_toolbox'); % also check the availability of a toolbox license case 'DCT' status = license('checkout', 'distrib_computing_toolbox'); % also check the availability of a toolbox license case 'FASTICA' status = exist('fastica', 'file'); case 'BRAINSTORM' status = exist('bem_xfer'); case 'FILEIO' status = (exist('ft_read_header') && exist('ft_read_data') && exist('ft_read_event') && exist('ft_read_sens')); case 'FORMWARD' status = (exist('ft_compute_leadfield') && exist('ft_prepare_vol_sens')); case 'DENOISE' status = (exist('tsr') && exist('sns')); case 'CTF' status = (exist('getCTFBalanceCoefs') && exist('getCTFdata')); case 'BCI2000' status = exist('load_bcidat'); case 'NLXNETCOM' status = (exist('MatlabNetComClient') && exist('NlxConnectToServer') && exist('NlxGetNewCSCData')); case 'DIPOLI' status = exist('dipoli.m', 'file'); case 'MNE' status = (exist('fiff_read_meas_info', 'file') && exist('fiff_setup_read_raw', 'file')); case 'TCP_UDP_IP' status = (exist('pnet', 'file') && exist('pnet_getvar', 'file') && exist('pnet_putvar', 'file')); case 'BEMCP' status = (exist('bem_Cij_cog', 'file') && exist('bem_Cij_lin', 'file') && exist('bem_Cij_cst', 'file')); case 'OPENMEEG' status = exist('openmeeg.m', 'file'); case 'PLOTTING' status = (exist('ft_plot_topo', 'file') && exist('ft_plot_mesh', 'file') && exist('ft_plot_matrix', 'file')); case 'PRTOOLS' status = (exist('prversion', 'file') && exist('dataset', 'file') && exist('svc', 'file')); case 'ITAB' status = (exist('lcReadHeader', 'file') && exist('lcReadData', 'file')); case 'BSMART' status = exist('bsmart'); case 'PEER' status = exist('peerslave', 'file') && exist('peermaster', 'file'); case 'CONNECTIVITY' status = exist('ft_connectivity_corr', 'file') && exist('ft_connectivity_granger', 'file'); case 'FREESURFER' status = exist('MRIread', 'file') && exist('vox2ras_0to1', 'file'); case 'FNS' status = exist('elecsfwd', 'file') && exist('img_get_gray', 'file'); case 'SIMBIO' status = exist('ipm_linux_opt_Venant', 'file'); case 'GIFTI' status = exist('gifti', 'file'); case 'XML4MAT' status = exist('xml2struct.m', 'file') && exist('xml2whos.m', 'file'); case 'SQDPROJECT' status = exist('sqdread.m', 'file') && exist('sqdwrite.m', 'file'); case 'BCT' status = exist('macaque71.mat', 'file') && exist('motif4funct_wei.m', 'file'); otherwise if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end status = 0; end % it should be a boolean value status = (status~=0); % try to determine the path of the requested toolbox if autoadd>0 && ~status % for core fieldtrip modules prefix = fileparts(which('ft_defaults')); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for external fieldtrip modules prefix = fullfile(fileparts(which('ft_defaults')), 'external'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for linux computers in the F.C. Donders Centre prefix = '/home/common/matlab'; if ~status && (strcmp(computer, 'GLNX86') || strcmp(computer, 'GLNXA64')) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for windows computers in the F.C. Donders Centre prefix = 'h:\common\matlab'; if ~status && (strcmp(computer, 'PCWIN') || strcmp(computer, 'PCWIN64')) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % use the matlab subdirectory in your homedirectory, this works on unix and mac prefix = [getenv('HOME') '/matlab']; if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end if ~status % the toolbox is not on the path and cannot be added sel = find(strcmp(url(:,1), toolbox)); if ~isempty(sel) msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2}); else msg = sprintf('the %s toolbox is not installed', toolbox); end if autoadd==1 error(msg); elseif autoadd==2 warning(msg); else % fail silently end end end % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before if status previous.(fixname(toolbox)) = status; end % remember the previous path, allows us to determine on the next call % whether the path has been modified outise of this function previouspath = path; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = myaddpath(toolbox, silent) if exist(toolbox, 'dir') if ~silent, ws = warning('backtrace', 'off'); warning('adding %s toolbox to your Matlab path', toolbox); warning(ws); % return to the previous warning level end addpath(toolbox); status = 1; else status = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out = fixname(toolbox) out = lower(toolbox); out(out=='-') = '_'; % fix dashes out(out==' ') = '_'; % fix spaces out(out=='/') = '_'; % fix forward slashes out(out=='\') = '_'; % fix backward slashes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = hasfunction(funname, toolbox) try % call the function without any input arguments, which probably is inapropriate feval(funname); % it might be that the function without any input already works fine status = true; catch % either the function returned an error, or the function is not available % availability is influenced by the function being present and by having a % license for the function, i.e. in a concurrent licensing setting it might % be that all toolbox licenses are in use m = lasterror; if strcmp(m.identifier, 'MATLAB:license:checkouterror') if nargin>1 warning('the %s toolbox is available, but you don''t have a license for it', toolbox); else warning('the function ''%s'' is available, but you don''t have a license for it', funname); end status = false; elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction') status = false; else % the function seems to be available and it gave an unknown error, % which is to be expected with inappropriate input arguments status = true; end end
github
philippboehmsturm/antx-master
read_plexon_nex.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_plexon_nex.m
7,770
utf_8
ddd5e1bafbd237ca874db87ef640f25f
function [varargout] = read_plexon_nex(filename, varargin) % READ_PLEXON_NEX reads header or data from a Plexon *.nex file, which % is a file containing action-potential (spike) timestamps and waveforms % (spike channels), event timestamps (event channels), and continuous % variable data (continuous A/D channels). % % LFP and spike waveform data that is returned by this function is % expressed in microVolt. % % Use as % [hdr] = read_plexon_nex(filename) % [dat] = read_plexon_nex(filename, ...) % [dat1, dat2, dat3, hdr] = read_plexon_nex(filename, ...) % % Optional arguments should be specified in key-value pairs and can be % header structure with header information % feedback 0 or 1 % tsonly 0 or 1, read only the timestamps and not the waveforms % channel number, or list of numbers (that will result in multiple outputs) % begsample number (for continuous only) % endsample number (for continuous only) % % See also READ_PLEXON_PLX, READ_PLEXON_DDT % Copyright (C) 2007, 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_plexon_nex.m 945 2010-04-21 17:41:20Z roboos $ % parse the optional input arguments hdr = keyval('header', varargin); channel = keyval('channel', varargin); feedback = keyval('feedback', varargin); tsonly = keyval('tsonly', varargin); begsample = keyval('begsample', varargin); endsample = keyval('endsample', varargin); % set the defaults if isempty(feedback) feedback=0; end if isempty(tsonly) tsonly=0; end if isempty(begsample) begsample=1; end if isempty(endsample) endsample=Inf; end % start with empty return values and empty data varargout = {}; % read header info from file, use Matlabs for automatic byte-ordering fid = fopen(filename, 'r', 'ieee-le'); fseek(fid, 0, 'eof'); siz = ftell(fid); fseek(fid, 0, 'bof'); if isempty(hdr) if feedback, fprintf('reading header from %s\n', filename); end % a NEX file consists of a file header, followed by a number of variable headers % sizeof(NexFileHeader) = 544 % sizeof(NexVarHeader) = 208 hdr.FileHeader = NexFileHeader(fid); if hdr.FileHeader.NumVars<1 error('no channels present in file'); end hdr.VarHeader = NexVarHeader(fid, hdr.FileHeader.NumVars); end for i=1:length(channel) chan = channel(i); vh = hdr.VarHeader(chan); clear buf fseek(fid, vh.DataOffset, 'bof'); switch vh.Type case 0 % Neurons, only timestamps buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); case 1 % Events, only timestamps buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); case 2 % Interval variables buf.begs = fread(fid, [1 vh.Count], 'int32=>int32'); buf.ends = fread(fid, [1 vh.Count], 'int32=>int32'); case 3 % Waveform variables buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); if ~tsonly buf.dat = fread(fid, [vh.NPointsWave vh.Count], 'int16'); % convert the AD values to miliVolt, subsequently convert from miliVolt to microVolt buf.dat = buf.dat * (vh.ADtoMV * 1000); end case 4 % Population vector error('population vectors are not supported'); case 5 % Continuously recorded variables buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); buf.indx = fread(fid, [1 vh.Count], 'int32=>int32'); if vh.Count>1 && (begsample~=1 || endsample~=inf) error('reading selected samples from multiple AD segments is not supported'); end if ~tsonly numsample = min(endsample - begsample + 1, vh.NPointsWave); fseek(fid, (begsample-1)*2, 'cof'); buf.dat = fread(fid, [1 numsample], 'int16'); % convert the AD values to miliVolt, subsequently convert from miliVolt to microVolt buf.dat = buf.dat * (vh.ADtoMV * 1000); end case 6 % Markers ts = fread(fid, [1 vh.Count], 'int32=>int32'); for j=1:vh.NMarkers buf.MarkerNames{j,1} = fread(fid, [1 64], 'uint8=>char'); for k=1:vh.Count buf.MarkerValues{j,k} = fread(fid, [1 vh.MarkerLength], 'uint8=>char'); end end otherwise error('incorrect channel type'); end % switch channel type % return the data of this channel varargout{i} = buf; end % for channel % always return the header as last varargout{end+1} = hdr; fclose(fid); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = NexFileHeader(fid); hdr.NexFileHeader = fread(fid,4,'uint8=>char')'; % string NEX1 hdr.Version = fread(fid,1,'int32'); hdr.Comment = fread(fid,256,'uint8=>char')'; hdr.Frequency = fread(fid,1,'double'); % timestamped freq. - tics per second hdr.Beg = fread(fid,1,'int32'); % usually 0 hdr.End = fread(fid,1,'int32'); % maximum timestamp + 1 hdr.NumVars = fread(fid,1,'int32'); % number of variables in the first batch hdr.NextFileHeader = fread(fid,1,'int32'); % position of the next file header in the file, not implemented yet Padding = fread(fid,256,'uint8=>char')'; % future expansion %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = NexVarHeader(fid, numvar); for varlop=1:numvar hdr(varlop).Type = fread(fid,1,'int32'); % 0 - neuron, 1 event, 2- interval, 3 - waveform, 4 - pop. vector, 5 - continuously recorded hdr(varlop).Version = fread(fid,1,'int32'); % 100 hdr(varlop).Name = fread(fid,64,'uint8=>char')'; % variable name hdr(varlop).DataOffset = fread(fid,1,'int32'); % where the data array for this variable is located in the file hdr(varlop).Count = fread(fid,1,'int32'); % number of events, intervals, waveforms or weights hdr(varlop).WireNumber = fread(fid,1,'int32'); % neuron only, not used now hdr(varlop).UnitNumber = fread(fid,1,'int32'); % neuron only, not used now hdr(varlop).Gain = fread(fid,1,'int32'); % neuron only, not used now hdr(varlop).Filter = fread(fid,1,'int32'); % neuron only, not used now hdr(varlop).XPos = fread(fid,1,'double'); % neuron only, electrode position in (0,100) range, used in 3D hdr(varlop).YPos = fread(fid,1,'double'); % neuron only, electrode position in (0,100) range, used in 3D hdr(varlop).WFrequency = fread(fid,1,'double'); % waveform and continuous vars only, w/f sampling frequency hdr(varlop).ADtoMV = fread(fid,1,'double'); % waveform continuous vars only, coeff. to convert from A/D values to Millivolts hdr(varlop).NPointsWave = fread(fid,1,'int32'); % waveform only, number of points in each wave hdr(varlop).NMarkers = fread(fid,1,'int32'); % how many values are associated with each marker hdr(varlop).MarkerLength = fread(fid,1,'int32'); % how many characters are in each marker value Padding = fread(fid,68,'uint8=>char')'; end
github
philippboehmsturm/antx-master
read_bti_m4d.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_bti_m4d.m
5,358
utf_8
efc8ff42ca99052f99b09ebb86c10e54
function [msi] = read_bti_m4d(filename); % READ_BTI_M4D % % Use as % msi = read_bti_m4d(filename) % Copyright (C) 2007, 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_bti_m4d.m 945 2010-04-21 17:41:20Z roboos $ [p, f, x] = fileparts(filename); if ~strcmp(x, '.m4d') % add the extension of the header filename = [filename '.m4d']; end fid = fopen(filename, 'r'); if fid==-1 error(sprintf('could not open file %s', filename)); end % start with an empty header structure msi = struct; % these header elements contain strings and should be converted in a cell-array strlist = { 'MSI.ChannelOrder' }; % these header elements contain numbers and should be converted in a numeric array % 'MSI.ChannelScale' % 'MSI.ChannelGain' % 'MSI.FileType' % 'MSI.TotalChannels' % 'MSI.TotalEpochs' % 'MSI.SamplePeriod' % 'MSI.SampleFrequency' % 'MSI.FirstLatency' % 'MSI.SlicesPerEpoch' % the conversion to numeric arrays is implemented in a general fashion % and all the fields above are automatically converted numlist = {}; line = ''; msi.grad.label = {}; msi.grad.pnt = zeros(0,3); msi.grad.ori = zeros(0,3); while ischar(line) line = cleanline(fgetl(fid)); if isempty(line) || (length(line)==1 && all(line==-1)) continue end sep = strfind(line, ':'); if length(sep)==1 key = line(1:(sep-1)); val = line((sep+1):end); elseif length(sep)>1 % assume that the first separator is the relevant one, and that the % next ones are part of the value string (e.g. a channel with a ':' in % its name sep = sep(1); key = line(1:(sep-1)); val = line((sep+1):end); elseif length(sep)<1 % this is not what I would expect error('unexpected content in m4d file'); end if ~isempty(strfind(line, 'Begin')) sep = strfind(key, '.'); sep = sep(end); key = key(1:(sep-1)); % if the key ends with begin and there is no value, then there is a block % of numbers following that relates to the magnetometer/gradiometer information. % All lines in that Begin-End block should be treated seperately val = {}; lab = {}; num = {}; ind = 0; while isempty(strfind(line, 'End')) line = cleanline(fgetl(fid)); if isempty(line) || (length(line)==1 && all(line==-1)) || ~isempty(strfind(line, 'End')) continue end ind = ind+1; % remember the line itself, and also cut it into pieces val{ind} = line; % the line is tab-separated and looks like this % A68 0.0873437 -0.075789 0.0891512 0.471135 -0.815532 0.336098 sep = find(line==9); % the ascii value of a tab is 9 sep = sep(1); lab{ind} = line(1:(sep-1)); num{ind} = str2num(line((sep+1):end)); end % parsing Begin-End block val = val(:); lab = lab(:); num = num(:); num = cell2mat(num); % the following is FieldTrip specific if size(num,2)==6 msi.grad.label = [msi.grad.label; lab(:)]; % the numbers represent position and orientation of each magnetometer coil msi.grad.pnt = [msi.grad.pnt; num(:,1:3)]; msi.grad.ori = [msi.grad.ori; num(:,4:6)]; else error('unknown gradiometer design') end end % the key looks like 'MSI.fieldname.subfieldname' fieldname = key(5:end); % remove spaces from the begin and end of the string val = strtrim(val); % try to convert the value string into something more usefull if ~iscell(val) % the value can contain a variety of elements, only some of which are decoded here if ~isempty(strfind(key, 'Index')) || ~isempty(strfind(key, 'Count')) || any(strcmp(key, numlist)) % this contains a single number or a comma-separated list of numbers val = str2num(val); elseif ~isempty(strfind(key, 'Names')) || any(strcmp(key, strlist)) % this contains a comma-separated list of strings val = tokenize(val, ','); else tmp = str2num(val); if ~isempty(tmp) val = tmp; end end end % assign this header element to the structure msi = setsubfield(msi, fieldname, val); end % while ischar(line) fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to remove spaces from the begin and end % and to remove comments from the lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function line = cleanline(line) if isempty(line) || (length(line)==1 && all(line==-1)) return end comment = findstr(line, '//'); if ~isempty(comment) line(min(comment):end) = ' '; end line = strtrim(line);
github
philippboehmsturm/antx-master
read_asa.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_asa.m
3,776
utf_8
22d131a6d78524f6b898995dcb17b54d
function [val] = read_asa(filename, elem, format, number, token) % READ_ASA reads a specified element from an ASA file % % val = read_asa(filename, element, type, number) % % where the element is a string such as % NumberSlices % NumberPositions % Rows % Columns % etc. % % and format specifies the datatype according to % %d (integer value) % %f (floating point value) % %s (string) % % number is optional to specify how many lines of data should be read % The default is 1 for strings and Inf for numbers. % % token is optional to specifiy a character that separates the values from % anything not wanted. % Copyright (C) 2002, 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_asa.m 945 2010-04-21 17:41:20Z roboos $ fid = fopen(filename, 'rt'); if fid==-1 error(sprintf('could not open file %s', filename)); end if nargin<4 if strcmp(format, '%s') number = 1; else number = Inf; end end if nargin<5 token = ''; end val = []; elem = strtrim(lower(elem)); while (1) line = fgetl(fid); if ~isempty(line) && isequal(line, -1) % prematurely reached end of file fclose(fid); return end line = strtrim(line); lower_line = lower(line); if strmatch(elem, lower_line) data = line((length(elem)+1):end); break end end while isempty(data) line = fgetl(fid); if isequal(line, -1) % prematurely reached end of file fclose(fid); return end data = strtrim(line); end if strcmp(format, '%s') if number==1 % interpret the data as a single string, create char-array val = detoken(strtrim(data), token); fclose(fid); return end % interpret the data as a single string, create cell-array val{1} = detoken(strtrim(data), token); count = 1; % read the remaining strings while count<number line = fgetl(fid); if ~isempty(line) && isequal(line, -1) fclose(fid); return end tmp = sscanf(line, format); if isempty(tmp) fclose(fid); return else count = count + 1; val{count} = detoken(strtrim(line), token); end end else % interpret the data as numeric, create numeric array count = 1; data = sscanf(detoken(data, token), format)'; if isempty(data), fclose(fid); return else val(count,:) = data; end % read remaining numeric data while count<number line = fgetl(fid); if ~isempty(line) && isequal(line, -1) fclose(fid); return end data = sscanf(detoken(line, token), format)'; if isempty(data) fclose(fid); return else count = count+1; val(count,:) = data; end end end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [out] = detoken(in, token) if isempty(token) out = in; return; end [tok rem] = strtok(in, token); if isempty(rem) out = in; return; else out = strtok(rem, token); return end
github
philippboehmsturm/antx-master
nanmean.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/nanmean.m
2,121
utf_8
7e0ebd9ca56f2cd79f89031bbccebb9a
% nanmean() - Average, not considering NaN values % % Usage: same as mean() % Author: Arnaud Delorme, CNL / Salk Institute, 16 Oct 2002 %123456789012345678901234567890123456789012345678901234567890123456789012 % 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 % 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: nanmean.m 2885 2011-02-16 09:41:58Z roboos $ function out = nanmean(in, dim) if nargin < 1 help nanmean; return; end; if nargin < 2 if size(in,1) ~= 1 dim = 1; elseif size(in,2) ~= 1 dim = 2; else dim = 3; end; end; tmpin = in; tmpin(find(isnan(in(:)))) = 0; out = sum(tmpin, dim) ./ sum(~isnan(in),dim);
github
philippboehmsturm/antx-master
ft_checkdata.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/ft_checkdata.m
58,801
utf_8
ebc65e88732dfae50505a780bebeb965
function [data] = ft_checkdata(data, varargin) % FT_CHECKDATA checks the input data of the main FieldTrip functions, e.g. whether % the type of data strucure corresponds with the required data. If neccessary % and possible, this function will adjust the data structure to the input % requirements (e.g. change dimord, average over trials, convert inside from % index into logical). % % If the input data does NOT correspond to the requirements, this function % is supposed to give a elaborate warning message and if applicable point % the user to external documentation (link to website). % % Use as % [data] = ft_checkdata(data, ...) % % Optional input arguments should be specified as key-value pairs and can include % feedback = yes, no % datatype = raw, freq, timelock, comp, spike, source, volume, dip % dimord = any combination of time, freq, chan, refchan, rpt, subj, chancmb, rpttap, pos % senstype = ctf151, ctf275, ctf151_planar, ctf275_planar, neuromag122, neuromag306, bti148, bti248, bti248_planar, magnetometer, electrode % inside = logical, index % ismeg = yes, no % hastrials = yes, no % hasunits = yes, no % hassampleinfo = yes, no, ifmakessense % hascumtapcnt = yes, no (only applies to freq data) % hasdim = yes, no % hasdof = yes, no % cmbrepresentation = sparse, full (applies to covariance and cross-spectral density) % % For some options you can specify multiple values, e.g. % [data] = ft_checkdata(data, 'senstype', {'ctf151', 'ctf275'}), e.g. in megrealign % [data] = ft_checkdata(data, 'datatype', {'timelock', 'freq'}), e.g. in sourceanalysis % Copyright (C) 2007-2009, 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 Publhasoffsetic License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_checkdata.m 3881 2011-07-20 09:39:41Z jansch $ % in case of an error this function could use dbstack for more detailled % user feedback % % this function should replace/encapsulate % fixdimord % fixinside % fixprecision % fixvolume % data2raw % raw2data % grid2transform % transform2grid % fourier2crsspctrm % freq2cumtapcnt % sensortype % time2offset % offset2time % % other potential uses for this function: % time -> offset in freqanalysis % average over trials % csd as matrix % get the optional input arguments feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'no'; end dtype = keyval('datatype', varargin); % should not conflict with the ft_datatype function dimord = keyval('dimord', varargin); stype = keyval('senstype', varargin); % senstype is a function name which should not be masked ismeg = keyval('ismeg', varargin); inside = keyval('inside', varargin); % can be logical or index hastrials = keyval('hastrials', varargin); hasunits = keyval('hasunits', varargin); hassampleinfo = keyval('hassampleinfo', varargin); if isempty(hassampleinfo), hassampleinfo = 'no'; end hasdimord = keyval('hasdimord', varargin); if isempty(hasdimord), hasdimord = 'no'; end hasdim = keyval('hasdim', varargin); hascumtapcnt = keyval('hascumtapcnt', varargin); hasdof = keyval('hasdof', varargin); if isempty(hasdof), hasdof = 'no'; end haspow = keyval('haspow', varargin); if isempty(haspow), haspow = 'no'; end cmbrepresentation = keyval('cmbrepresentation', varargin); channelcmb = keyval('channelcmb', varargin); sourcedimord = keyval('sourcedimord', varargin); sourcerepresentation = keyval('sourcerepresentation', varargin); % check whether people are using deprecated stuff depHastrialdef = keyval('hastrialdef', varargin); if (~isempty(depHastrialdef)) warning_once('ft_checkdata option ''hastrialdef'' is deprecated; use ''hassampleinfo'' instead'); hassampleinfo = depHastrialdef; end if (~isempty(keyval('hasoffset', varargin))) warning_once('ft_checkdata option ''hasoffset'' has been removed and will be ignored'); end % determine the type of input data % this can be raw, freq, timelock, comp, spike, source, volume, dip israw = ft_datatype(data, 'raw'); isfreq = ft_datatype(data, 'freq'); istimelock = ft_datatype(data, 'timelock'); iscomp = ft_datatype(data, 'comp'); isspike = ft_datatype(data, 'spike'); isvolume = ft_datatype(data, 'volume'); issource = ft_datatype(data, 'source'); isdip = ft_datatype(data, 'dip'); ismvar = ft_datatype(data, 'mvar'); isfreqmvar = ft_datatype(data, 'freqmvar'); ischan = ft_datatype(data, 'chan'); % FIXME use the istrue function on ismeg and hasxxx options if ~isequal(feedback, 'no') if israw nchan = length(data.label); ntrial = length(data.trial); fprintf('the input is raw data with %d channels and %d trials\n', nchan, ntrial); elseif isfreq nchan = length(data.label); nfreq = length(data.freq); if isfield(data, 'time'), ntime = num2str(length(data.time)); else ntime = 'no'; end fprintf('the input is freq data with %d channels, %d frequencybins and %s timebins\n', nchan, nfreq, ntime); elseif istimelock nchan = length(data.label); ntime = length(data.time); fprintf('the input is timelock data with %d channels and %d timebins\n', nchan, ntime); elseif iscomp ncomp = length(data.label); nchan = length(data.topolabel); fprintf('the input is component data with %d components and %d original channels\n', ncomp, nchan); elseif isspike nchan = length(data.label); fprintf('the input is spike data\n'); elseif isvolume fprintf('the input is volume data with dimensions [%d %d %d]\n', data.dim(1), data.dim(2), data.dim(3)); elseif issource nsource = size(data.pos, 1); fprintf('the input is source data with %d positions\n', nsource); elseif isdip fprintf('the input is dipole data\n'); elseif ismvar fprintf('the input is mvar data\n'); elseif isfreqmvar fprintf('the input is freqmvar data\n'); end end % give feedback if issource && isvolume % it should be either one or the other: the choice here is to % represent it as volume description since that is simpler to handle % the conversion is done by remove the grid positions data = rmfield(data, 'pos'); issource = false; end % the ft_datatype_XXX functions ensures the consistency of the XXX datatype % and provides a detailled description of the dataformat and its history if israw data = ft_datatype_raw(data); elseif isfreq data = ft_datatype_freq(data); elseif istimelock data = ft_datatype_timelock(data); elseif iscomp data = ft_datatype_comp(data); elseif isspike data = ft_datatype_spike(data); elseif isvolume data = ft_datatype_volume(data); elseif issource data = ft_datatype_source(data); elseif isdip data = ft_datatype_dip(data); elseif ismvar || isfreqmvar data = ft_datatype_mvar(data); end if ~isempty(dtype) if ~isa(dtype, 'cell') dtype = {dtype}; end okflag = 0; for i=1:length(dtype) % check that the data matches with one or more of the required ft_datatypes switch dtype{i} case 'raw' okflag = okflag + israw; case 'freq' okflag = okflag + isfreq; case 'timelock' okflag = okflag + istimelock; case 'comp' okflag = okflag + iscomp; case 'spike' okflag = okflag + isspike; case 'volume' okflag = okflag + isvolume; case 'source' okflag = okflag + issource; case 'dip' okflag = okflag + isdip; case 'mvar' okflag = okflag + ismvar; case 'freqmvar' okflag = okflag + isfreqmvar; end % switch dtype end % for dtype if ~okflag % try to convert the data for iCell = 1:length(dtype) if isequal(dtype(iCell), {'source'}) && isvolume data = volume2source(data); isvolume = 0; issource = 1; okflag = 1; elseif isequal(dtype(iCell), {'volume'}) && issource data = source2volume(data); isvolume = 1; issource = 0; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && issource data = data2raw(data); issource = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && istimelock data = timelock2raw(data); istimelock = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'timelock'}) && israw data = raw2timelock(data); israw = 0; istimelock = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && isfreq data = freq2raw(data); isfreq = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && iscomp data = comp2raw(data); iscomp = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'timelock'}) && iscomp data = comp2raw(data); data = raw2timelock(data); iscomp = 0; istimelock = 1; okflag = 1; elseif isequal(dtype(iCell), {'timelock'}) && ischan data = chan2timelock(data); ischan = 0; istimelock = 1; okflag = 1; elseif isequal(dtype(iCell), {'freq'}) && ischan data = chan2freq(data); ischan = 0; isfreq = 1; okflag = 1; end end % for iCell end % if okflag if ~okflag % construct an error message if length(dtype)>1 str = sprintf('%s, ', dtype{1:(end-2)}); str = sprintf('%s%s or %s', str, dtype{end-1}, dtype{end}); else str = dtype{1}; end str = sprintf('This function requires %s data as input.', str); error(str); end % if okflag end if ~isempty(dimord) if ~isa(dimord, 'cell') dimord = {dimord}; end if isfield(data, 'dimord') okflag = any(strcmp(data.dimord, dimord)); else okflag = 0; end if ~okflag % construct an error message if length(dimord)>1 str = sprintf('%s, ', dimord{1:(end-2)}); str = sprintf('%s%s or %s', str, dimord{end-1}, dimord{end}); else str = dimord{1}; end str = sprintf('This function requires data with a dimord of %s.', str); error(str); end % if okflag end if ~isempty(stype) if ~isa(stype, 'cell') stype = {stype}; end if isfield(data, 'grad') || isfield(data, 'elec') if any(strcmp(ft_senstype(data), stype)); okflag = 1; else okflag = 0; end else okflag = 0; end if ~okflag % construct an error message if length(stype)>1 str = sprintf('%s, ', stype{1:(end-2)}); str = sprintf('%s%s or %s', str, stype{end-1}, stype{end}); else str = stype{1}; end str = sprintf('This function requires %s data as input, but you are giving %s data.', str, ft_senstype(data)); error(str); end % if okflag end if ~isempty(ismeg) if isequal(ismeg, 'yes') okflag = isfield(data, 'grad'); elseif isequal(ismeg, 'no') okflag = ~isfield(data, 'grad'); end if ~okflag && isequal(ismeg, 'yes') error('This function requires MEG data with a ''grad'' field'); elseif ~okflag && isequal(ismeg, 'no') error('This function should not be given MEG data with a ''grad'' field'); end % if okflag end if ~isempty(inside) % TODO absorb the fixinside function into this code data = fixinside(data, inside); okflag = isfield(data, 'inside'); if ~okflag % construct an error message error('This function requires data with an ''inside'' field.'); end % if okflag end %if isvolume % % ensure consistent dimensions of the volumetric data % % reshape each of the volumes that is found into a 3D array % param = parameterselection('all', data); % dim = data.dim; % for i=1:length(param) % tmp = getsubfield(data, param{i}); % tmp = reshape(tmp, dim); % data = setsubfield(data, param{i}, tmp); % end %end if isequal(hasunits, 'yes') && ~isfield(data, 'units') % calling convert_units with only the input data adds the units without converting data = ft_convert_units(data); end if issource || isvolume, % the following section is to make a dimord-consistent representation of % volume and source data, taking trials, time and frequency into account if isequal(hasdimord, 'yes') && (~isfield(data, 'dimord') || ~strcmp(data.dimord,sourcedimord)) % determine the size of the data if isfield(data, 'dimord'), dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('time', dimtok)), Ntime = length(data.time); else Ntime = 1; end if ~isempty(strmatch('freq', dimtok)), Nfreq = length(data.freq); else Nfreq = 1; end else Nfreq = 1; Ntime = 1; end %convert old style source representation into new style if isfield(data, 'avg') && isfield(data.avg, 'mom') && (isfield(data, 'freq') || isfield(data, 'frequency')) && strcmp(sourcedimord, 'rpt_pos'), %frequency domain source representation convert to single trial power Npos = size(data.pos,1); Nrpt = size(data.cumtapcnt,1); tmpmom = zeros(Npos, size(data.avg.mom{data.inside(1)},2)); tmpmom(data.inside,:) = cat(1,data.avg.mom{data.inside}); tmppow = zeros(Npos, Nrpt); tapcnt = [0;cumsum(data.cumtapcnt)]; for k = 1:Nrpt Ntap = tapcnt(k+1)-tapcnt(k); tmppow(data.inside,k) = sum(abs(tmpmom(data.inside,(tapcnt(k)+1):tapcnt(k+1))).^2,2)./Ntap; end data.pow = tmppow'; data = rmfield(data, 'avg'); if strcmp(inside, 'logical'), data = fixinside(data, 'logical'); data.inside = repmat(data.inside(:)',[Nrpt 1]); end elseif isfield(data, 'avg') && isfield(data.avg, 'mom') && (isfield(data, 'freq') || isfield(data, 'frequency')) && strcmp(sourcedimord, 'rpttap_pos'), %frequency domain source representation convert to single taper fourier coefficients Npos = size(data.pos,1); Nrpt = sum(data.cumtapcnt); data.fourierspctrm = complex(zeros(Nrpt, Npos), zeros(Nrpt, Npos)); data.fourierspctrm(:, data.inside) = transpose(cat(1, data.avg.mom{data.inside})); data = rmfield(data, 'avg'); elseif isfield(data, 'avg') && isfield(data.avg, 'mom') && isfield(data, 'time') && strcmp(sourcedimord, 'pos_time'), Npos = size(data.pos,1); Nrpt = 1; tmpmom = zeros(Npos, size(data.avg.mom{data.inside(1)},2)); tmpmom(data.inside,:) = cat(1,data.avg.mom{data.inside}); data.mom = tmpmom; if isfield(data.avg, 'noise'), tmpnoise = data.avg.noise(:); data.noise = tmpnoise(:,ones(1,size(tmpmom,2))); end data = rmfield(data, 'avg'); Ntime = length(data.time); elseif isfield(data, 'trial') && isfield(data.trial(1), 'mom') && isfield(data, 'time') && strcmp(sourcedimord, 'rpt_pos_time'), Npos = size(data.pos,1); Nrpt = length(data.trial); Ntime = length(data.time); tmpmom = zeros(Nrpt, Npos, Ntime); for k = 1:Nrpt tmpmom(k,data.inside,:) = cat(1,data.trial(k).mom{data.inside}); end data = rmfield(data, 'trial'); data.mom = tmpmom; elseif isfield(data, 'trial') && isstruct(data.trial) Nrpt = length(data.trial); else Nrpt = 1; end % start with an initial specification of the dimord and dim if (~isfield(data, 'dim') || ~isfield(data, 'dimord')) if issource % at least it should have a Nx3 pos data.dim = size(data.pos, 1); data.dimord = 'pos'; elseif isvolume % at least it should have a 1x3 dim data.dim = data.dim; data.dimord = 'dim1_dim2_dim3'; end end % add the additional dimensions if Nfreq>1 data.dimord = [data.dimord '_freq']; data.dim = [data.dim Nfreq]; end if Ntime>1 data.dimord = [data.dimord '_time']; data.dim = [data.dim Ntime]; end if Nrpt>1 && strcmp(sourcedimord, 'rpt_pos'), data.dimord = ['rpt_' data.dimord]; data.dim = [Nrpt data.dim ]; elseif Nrpt>1 && strcmp(sourcedimord, 'rpttap_pos'), data.dimord = ['rpttap_' data.dimord]; data.dim = [Nrpt data.dim ]; end % the nested trial structure is not compatible with dimord if isfield(data, 'trial') && isstruct(data.trial) param = fieldnames(data.trial); for i=1:length(param) if isa(data.trial(1).(param{i}), 'cell') concat = cell(data.dim(1), prod(data.dim(2:end))); else concat = zeros(data.dim(1), prod(data.dim(2:end))); end for j=1:length(data.trial) tmp = data.trial(j).(param{i}); concat(j,:) = tmp(:); end % for each trial data.trial = rmfield(data.trial, param{i}); data.(param{i}) = reshape(concat, data.dim); end % for each param data = rmfield(data, 'trial'); end end % ensure consistent dimensions of the source reconstructed data % reshape each of the source reconstructed parameters if issource && isfield(data, 'dim') && prod(data.dim)==size(data.pos,1) dim = [prod(data.dim) 1]; elseif issource && any(~cellfun('isempty',strfind(fieldnames(data), 'dimord'))) dim = [size(data.pos,1) 1]; %sparsely represented source structure new style elseif isfield(data, 'dim'), dim = [data.dim 1]; elseif issource dim = [size(data.pos,1) 1]; elseif isfield(data, 'dimord'), %HACK dimtok = tokenize(data.dimord, '_'); for i=1:length(dimtok) if strcmp(dimtok(i), 'pos') dim(1,i) = size(getsubfield(data,dimtok{i}),1); elseif strcmp(dimtok(i), 'rpt') dim(1,i) = nan; else dim(1,i) = length(getsubfield(data,dimtok{i})); end end i = find(isnan(dim)); if ~isempty(i) n = fieldnames(data); for ii=1:length(n) numels(1,ii) = numel(getfield(data,n{ii})); end nrpt = numels./prod(dim(setdiff(1:length(dim),i))); nrpt = nrpt(nrpt==round(nrpt)); dim(i) = max(nrpt); end if numel(dim)==1, dim(1,2) = 1; end; end % these fields should not be reshaped exclude = {'cfg' 'fwhm' 'leadfield' 'q' 'rough'}; if ~strcmp(inside, 'logical') % also exclude the inside/outside from being reshaped exclude = cat(2, exclude, {'inside' 'outside'}); end param = setdiff(parameterselection('all', data), exclude); for i=1:length(param) if any(param{i}=='.') % the parameter is nested in a substructure, which can have multiple elements (e.g. source.trial(1).pow, source.trial(2).pow, ...) % loop over the substructure array and reshape for every element tok = tokenize(param{i}, '.'); sub1 = tok{1}; % i.e. this would be 'trial' sub2 = tok{2}; % i.e. this would be 'pow' tmp1 = getfield(data, sub1); for j=1:numel(tmp1) tmp2 = getfield(tmp1(j), sub2); tmp2 = reshape(tmp2, dim); tmp1(j) = setfield(tmp1(j), sub2, tmp2); end data = setfield(data, sub1, tmp1); else tmp = getfield(data, param{i}); tmp = reshape(tmp, dim); data = setfield(data, param{i}, tmp); end end end if isequal(hastrials, 'yes') okflag = isfield(data, 'trial'); if ~okflag error('This function requires data with a ''trial'' field'); end % if okflag end if isequal(hassampleinfo, 'yes') || isequal(hassampleinfo, 'ifmakessense') data = fixsampleinfo(data); end if isequal(hasdim, 'yes') && ~isfield(data, 'dim') data.dim = pos2dim(data.pos); elseif isequal(hasdim, 'no') && isfield(data, 'dim') data = rmfield(data, 'dim'); end % if hasdim if isequal(hascumtapcnt, 'yes') && ~isfield(data, 'cumtapcnt') error('This function requires data with a ''cumtapcnt'' field'); elseif isequal(hascumtapcnt, 'no') && isfield(data, 'cumtapcnt') data = rmfield(data, 'cumtapcnt'); end % if hascumtapcnt if isequal(hasdof, 'yes') && ~isfield(data, 'hasdof') error('This function requires data with a ''dof'' field'); elseif isequal(hasdof, 'no') && isfield(data, 'hasdof') data = rmfield(data, 'cumtapcnt'); end % if hasdof if ~isempty(cmbrepresentation) if istimelock data = fixcov(data, cmbrepresentation); elseif isfreq data = fixcsd(data, cmbrepresentation, channelcmb); elseif isfreqmvar data = fixcsd(data, cmbrepresentation, channelcmb); else error('This function requires data with a covariance, coherence or cross-spectrum'); end end % cmbrepresentation if issource && ~isempty(sourcerepresentation) data = fixsource(data, 'type', sourcerepresentation); end if issource && ~strcmp(haspow, 'no') data = fixsource(data, 'type', sourcerepresentation, 'haspow', haspow); end if isfield(data, 'grad') % ensure that the gradiometer balancing is specified if ~isfield(data.grad, 'balance') || ~isfield(data.grad.balance, 'current') data.grad.balance.current = 'none'; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % represent the covariance matrix in a particular manner %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = fixcov(data, desired) if isfield(data, 'cov') && ~isfield(data, 'labelcmb') current = 'full'; elseif isfield(data, 'cov') && isfield(data, 'labelcmb') current = 'sparse'; else error('Could not determine the current representation of the covariance matrix'); end if isequal(current, desired) % nothing to do elseif strcmp(current, 'full') && strcmp(desired, 'sparse') % FIXME should be implemented error('not yet implemented'); elseif strcmp(current, 'sparse') && strcmp(desired, 'full') % FIXME should be implemented error('not yet implemented'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % represent the cross-spectral density matrix in a particular manner %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = fixcsd(data, desired, channelcmb) % FIXCSD converts univariate frequency domain data (fourierspctrm) into a bivariate % representation (crsspctrm), or changes the representation of bivariate frequency % domain data (sparse/full/sparsewithpow, sparsewithpow only works for crsspctrm or % fourierspctrm) % Copyright (C) 2010, Jan-Mathijs Schoffelen, Robert Oostenveld if isfield(data, 'crsspctrm') && isfield(data, 'powspctrm') current = 'sparsewithpow'; elseif isfield(data, 'powspctrm') current = 'sparsewithpow'; elseif isfield(data, 'fourierspctrm') && ~isfield(data, 'labelcmb') current = 'fourier'; elseif ~isfield(data, 'labelcmb') current = 'full'; elseif isfield(data, 'labelcmb') current = 'sparse'; else error('Could not determine the current representation of the %s matrix', param); end % first go from univariate fourier to the required bivariate representation if strcmp(current, 'fourier') && strcmp(desired, 'fourier') % nothing to do elseif strcmp(current, 'fourier') && strcmp(desired, 'sparsewithpow') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpttap', dimtok)), nrpt = size(data.cumtapcnt,1); flag = 0; else nrpt = 1; flag = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1)); %create auto-spectra nchan = length(data.label); if fastflag % all trials have the same amount of tapers powspctrm = zeros(nrpt,nchan,nfrq,ntim); ntap = data.cumtapcnt(1); for p = 1:ntap powspctrm = powspctrm + abs(data.fourierspctrm(p:ntap:end,:,:,:,:)).^2; end powspctrm = powspctrm./ntap; else % different amount of tapers powspctrm = zeros(nrpt,nchan,nfrq,ntim)+i.*zeros(nrpt,nchan,nfrq,ntim); sumtapcnt = [0;cumsum(data.cumtapcnt(:))]; for p = 1:nrpt indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat = data.fourierspctrm(indx,:,:,:); powspctrm(p,:,:,:) = (sum(tmpdat.*conj(tmpdat),1))./data.cumtapcnt(p); end end %create cross-spectra if ~isempty(channelcmb), ncmb = size(channelcmb,1); cmbindx = zeros(ncmb,2); labelcmb = cell(ncmb,2); for k = 1:ncmb ch1 = find(strcmp(data.label, channelcmb(k,1))); ch2 = find(strcmp(data.label, channelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(k,:) = [ch1 ch2]; labelcmb(k,:) = data.label([ch1 ch2])'; end end crsspctrm = zeros(nrpt,ncmb,nfrq,ntim)+i.*zeros(nrpt,ncmb,nfrq,ntim); if fastflag for p = 1:ntap tmpdat1 = data.fourierspctrm(p:ntap:end,cmbindx(:,1),:,:,:); tmpdat2 = data.fourierspctrm(p:ntap:end,cmbindx(:,2),:,:,:); crsspctrm = crsspctrm + tmpdat1.*conj(tmpdat2); end crsspctrm = crsspctrm./ntap; else for p = 1:nrpt indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:); tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:); crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p); end end data.crsspctrm = crsspctrm; data.labelcmb = labelcmb; end data.powspctrm = powspctrm; data = rmfield(data, 'fourierspctrm'); if ntim>1, data.dimord = 'chan_freq_time'; else data.dimord = 'chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end if flag, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end elseif strcmp(current, 'fourier') && strcmp(desired, 'sparse') if isempty(channelcmb), error('no channel combinations are specified'); end dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpttap', dimtok)), nrpt = size(data.cumtapcnt,1); flag = 0; else nrpt = 1; flag = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end ncmb = size(channelcmb,1); cmbindx = zeros(ncmb,2); labelcmb = cell(ncmb,2); for k = 1:ncmb ch1 = find(strcmp(data.label, channelcmb(k,1))); ch2 = find(strcmp(data.label, channelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(k,:) = [ch1 ch2]; labelcmb(k,:) = data.label([ch1 ch2])'; end end sumtapcnt = [0;cumsum(data.cumtapcnt(:))]; fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1)); if fastflag && nrpt>1 ntap = data.cumtapcnt(1); % compute running sum across tapers siz = [size(data.fourierspctrm) 1]; for p = 1:ntap indx = p:ntap:nrpt*ntap; if p==1. tmpc = zeros(numel(indx), size(cmbindx,1), siz(3), siz(4)) + ... 1i.*zeros(numel(indx), size(cmbindx,1), siz(3), siz(4)); end for k = 1:size(cmbindx,1) tmpc(:,k,:,:) = data.fourierspctrm(indx,cmbindx(k,1),:,:).* ... conj(data.fourierspctrm(indx,cmbindx(k,2),:,:)); end if p==1 crsspctrm = tmpc; else crsspctrm = tmpc + crsspctrm; end end crsspctrm = crsspctrm./ntap; else crsspctrm = zeros(nrpt, ncmb, nfrq, ntim); for p = 1:nrpt indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:); tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:); crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p); end end data.crsspctrm = crsspctrm; data.labelcmb = labelcmb; data = rmfield(data, 'fourierspctrm'); data = rmfield(data, 'label'); if ntim>1, data.dimord = 'chan_freq_time'; else data.dimord = 'chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end if flag, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end elseif strcmp(current, 'fourier') && strcmp(desired, 'full') % this is how it is currently and the desired functionality of prepare_freq_matrices dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpttap', dimtok)), nrpt = size(data.cumtapcnt, 1); flag = 0; else nrpt = 1; flag = 1; end if ~isempty(strmatch('rpttap',dimtok)), nrpt=size(data.cumtapcnt, 1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end if any(data.cumtapcnt(1,:) ~= data.cumtapcnt(1,1)), error('this only works when all frequencies have the same number of tapers'); end nchan = length(data.label); crsspctrm = zeros(nrpt,nchan,nchan,nfrq,ntim); sumtapcnt = [0;cumsum(data.cumtapcnt(:,1))]; for k = 1:ntim for m = 1:nfrq for p = 1:nrpt %FIXME speed this up in the case that all trials have equal number of tapers indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat = transpose(data.fourierspctrm(indx,:,m,k)); crsspctrm(p,:,:,m,k) = (tmpdat*tmpdat')./data.cumtapcnt(p); clear tmpdat; end end end data.crsspctrm = crsspctrm; data = rmfield(data, 'fourierspctrm'); if ntim>1, data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end % remove first singleton dimension if flag || nrpt==1, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end elseif strcmp(current, 'fourier') && strcmp(desired, 'fullfast'), dimtok = tokenize(data.dimord, '_'); nrpt = size(data.fourierspctrm, 1); nchn = numel(data.label); nfrq = numel(data.freq); if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end data.fourierspctrm = reshape(data.fourierspctrm, [nrpt nchn nfrq*ntim]); data.fourierspctrm(~isfinite(data.fourierspctrm)) = 0; crsspctrm = complex(zeros(nchn,nchn,nfrq*ntim)); for k = 1:nfrq*ntim tmp = transpose(data.fourierspctrm(:,:,k)); n = sum(tmp~=0,2); crsspctrm(:,:,k) = tmp*tmp'./n(1); end data = rmfield(data, 'fourierspctrm'); data.crsspctrm = reshape(crsspctrm, [nchn nchn nfrq ntim]); if isfield(data, 'time'), data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end if isfield(data, 'trialinfo'), data = rmfield(data, 'trialinfo'); end; if isfield(data, 'sampleinfo'), data = rmfield(data, 'sampleinfo'); end; if isfield(data, 'cumsumcnt'), data = rmfield(data, 'cumsumcnt'); end; if isfield(data, 'cumtapcnt'), data = rmfield(data, 'cumtapcnt'); end; end % convert to the requested bivariate representation % from one bivariate representation to another if isequal(current, desired) % nothing to do elseif (strcmp(current, 'full') && strcmp(desired, 'fourier')) || ... (strcmp(current, 'sparse') && strcmp(desired, 'fourier')) || ... (strcmp(current, 'sparsewithpow') && strcmp(desired, 'fourier')) % this is not possible error('converting the cross-spectrum into a Fourier representation is not possible'); elseif strcmp(current, 'full') && strcmp(desired, 'sparsewithpow') error('not yet implemented'); elseif strcmp(current, 'sparse') && strcmp(desired, 'sparsewithpow') % convert back to crsspctrm/powspctrm representation: useful for plotting functions etc indx = labelcmb2indx(data.labelcmb); autoindx = indx(indx(:,1)==indx(:,2), 1); cmbindx = setdiff([1:size(indx,1)]', autoindx); if strcmp(data.dimord(1:3), 'rpt') data.powspctrm = data.crsspctrm(:, autoindx, :, :); data.crsspctrm = data.crsspctrm(:, cmbindx, :, :); else data.powspctrm = data.crsspctrm(autoindx, :, :); data.crsspctrm = data.crsspctrm(cmbindx, :, :); end data.label = data.labelcmb(autoindx,1); data.labelcmb = data.labelcmb(cmbindx, :); if isempty(cmbindx) data = rmfield(data, 'crsspctrm'); data = rmfield(data, 'labelcmb'); end elseif strcmp(current, 'full') && strcmp(desired, 'sparse') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end nchan = length(data.label); ncmb = nchan*nchan; labelcmb = cell(ncmb, 2); cmbindx = zeros(nchan, nchan); k = 1; for j=1:nchan for m=1:nchan labelcmb{k, 1} = data.label{m}; labelcmb{k, 2} = data.label{j}; cmbindx(m,j) = k; k = k+1; end end % reshape all possible fields fn = fieldnames(data); for ii=1:numel(fn) if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim; if nrpt>1, data.(fn{ii}) = reshape(data.(fn{ii}), nrpt, ncmb, nfrq, ntim); else data.(fn{ii}) = reshape(data.(fn{ii}), ncmb, nfrq, ntim); end end end % remove obsolete fields data = rmfield(data, 'label'); try, data = rmfield(data, 'dof'); end % replace updated fields data.labelcmb = labelcmb; if ntim>1, data.dimord = 'chancmb_freq_time'; else data.dimord = 'chancmb_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end elseif strcmp(current, 'sparsewithpow') && strcmp(desired, 'sparse') % this representation for sparse data contains autospectra % as e.g. {'A' 'A'} in labelcmb if isfield(data, 'crsspctrm'), dimtok = tokenize(data.dimord, '_'); catdim = match_str(dimtok, {'chan' 'chancmb'}); data.crsspctrm = cat(catdim, data.powspctrm, data.crsspctrm); data.labelcmb = [data.label(:) data.label(:); data.labelcmb]; data = rmfield(data, 'powspctrm'); else data.crsspctrm = data.powspctrm; data.labelcmb = [data.label(:) data.label(:)]; data = rmfield(data, 'powspctrm'); end data = rmfield(data, 'label'); elseif strcmp(current, 'sparse') && strcmp(desired, 'full') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end if ~isfield(data, 'label') % ensure that the bivariate spectral factorization results can be % processed. FIXME this is experimental and will not work if the user % did something weird before for k = 1:numel(data.labelcmb) tmp = tokenize(data.labelcmb{k}, '['); data.labelcmb{k} = tmp{1}; end data.label = unique(data.labelcmb(:)); end nchan = length(data.label); ncmb = size(data.labelcmb,1); cmbindx = zeros(nchan,nchan); for k = 1:size(data.labelcmb,1) ch1 = find(strcmp(data.label, data.labelcmb(k,1))); ch2 = find(strcmp(data.label, data.labelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(ch1,ch2) = k; end end complete = all(cmbindx(:)~=0); fn = fieldnames(data); for ii=1:numel(fn) if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim; if nrpt==1, data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]); end tmpall = nan(nrpt,nchan,nchan,nfrq,ntim); for j = 1:nrpt for k = 1:ntim for m = 1:nfrq tmpdat = nan(nchan,nchan); indx = find(cmbindx); if ~complete % this realizes the missing combinations to be represented as the % conjugate of the corresponding combination across the diagonal tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]); tmpdat = ctranspose(tmpdat); end tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]); tmpall(j,:,:,m,k) = tmpdat; end % for m end % for k end % for j % replace the data in the old representation with the new representation if nrpt>1, data.(fn{ii}) = tmpall; else data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]); end end % if numel end % for ii % remove obsolete fields try, data = rmfield(data, 'powspctrm'); end try, data = rmfield(data, 'labelcmb'); end try, data = rmfield(data, 'dof'); end if ntim>1, data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end elseif strcmp(current, 'sparse') && strcmp(desired, 'fullfast') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end if ~isfield(data, 'label') data.label = unique(data.labelcmb(:)); end nchan = length(data.label); ncmb = size(data.labelcmb,1); cmbindx = zeros(nchan,nchan); for k = 1:size(data.labelcmb,1) ch1 = find(strcmp(data.label, data.labelcmb(k,1))); ch2 = find(strcmp(data.label, data.labelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(ch1,ch2) = k; end end complete = all(cmbindx(:)~=0); fn = fieldnames(data); for ii=1:numel(fn) if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim; if nrpt==1, data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]); end tmpall = nan(nchan,nchan,nfrq,ntim); for k = 1:ntim for m = 1:nfrq tmpdat = nan(nchan,nchan); indx = find(cmbindx); if ~complete % this realizes the missing combinations to be represented as the % conjugate of the corresponding combination across the diagonal tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]); tmpdat = ctranspose(tmpdat); end tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]); tmpall(:,:,m,k) = tmpdat; end % for m end % for k % replace the data in the old representation with the new representation if nrpt>1, data.(fn{ii}) = tmpall; else data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]); end end % if numel end % for ii % remove obsolete fields try, data = rmfield(data, 'powspctrm'); end try, data = rmfield(data, 'labelcmb'); end try, data = rmfield(data, 'dof'); end if ntim>1, data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end elseif strcmp(current, 'sparsewithpow') && strcmp(desired, 'full') % this is how is currently done in prepare_freq_matrices data = ft_checkdata(data, 'cmbrepresentation', 'sparse'); data = ft_checkdata(data, 'cmbrepresentation', 'full'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert to new source representation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [output] = fixsource(input, varargin) % FIXSOURCE converts old style source structures into new style source structures and the % other way around % % Use as: % fixsource(input, type) % where input is a source structure, % % Typically, old style source structures contain % avg.XXX or trial.XXX fields % % The new style source structure contains: % source.pos % source.dim (optional, if the list of positions describes a 3D volume % source.XXX the old style subfields in avg/trial % source.XXXdimord string how to interpret the respective XXX field: % e.g. source.leadfield = cell(1,Npos), source.leadfielddimord = '{pos}_chan_ori' % source.mom = cell(1,Npos), source.momdimord = '{pos}_ori_rpttap' type = keyval('type', varargin); haspow = keyval('haspow', varargin); if isempty(type), type = 'old'; end if isempty(haspow), haspow = 'no'; end fnames = fieldnames(input); tmp = cell2mat(strfind(fnames, 'dimord')); %get dimord like fields if any(tmp>1), current = 'new'; elseif any(tmp==1), %don't know what to do yet data is JM's own invention current = 'old'; else current = 'old'; end if strcmp(current, type), %do nothing output = input; %return elseif strcmp(current, 'old') && strcmp(type, 'new'), %go from old to new if isfield(input, 'avg'), stuff = getfield(input, 'avg'); output = rmfield(input, 'avg'); elseif isfield(input, 'trial'), stuff = getfield(input, 'trial'); output = rmfield(input, 'trial'); else %this could occur later in the pipeline, e.g. when doing group statistics using individual subject %descriptive statistics error('the input does not contain an avg or trial field'); end %------------------------------------------------- %remove and rename the specified fields if present removefields = {'xgrid';'ygrid';'zgrid';'method'}; renamefields = {'frequency' 'freq'; 'csdlabel' 'orilabel'}; fnames = fieldnames(output); for k = 1:numel(fnames) ix = strmatch(fnames{k}, removefields); if ~isempty(ix), output = rmfield(output, fnames{k}); end ix = strmatch(fnames{k}, renamefields(:,1), 'exact'); if ~isempty(ix), output = setfield(output, renamefields{ix,2}, ... getfield(output, renamefields{ix,1})); output = rmfield(output, fnames{k}); end end %---------------------------------------------------------------------- %put the stuff originally in avg or trial one level up in the structure fnames = fieldnames(stuff(1)); npos = size(input.pos,1); nrpt = numel(stuff); for k = 1:numel(fnames) if nrpt>1, %multiple trials %(or subjects FIXME not yet implemented, nor tested) tmp = getfield(stuff(1), fnames{k}); siz = size(tmp); if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom') %pcc based mom is orixrpttap %tranpose to keep manageable for kk = 1:numel(input.inside) indx = input.inside(kk); tmp{indx} = permute(tmp{indx}, [2 1 3]); end nrpttap = sum(input.cumtapcnt); sizvox = [size(tmp{input.inside(1)}) 1]; sizvox = [nrpttap sizvox(2:end)]; elseif strcmp(fnames{k}, 'mom'), %this is then probably not a frequency based mom nrpttap = numel(stuff); sizvox = [size(tmp{input.inside(1)}) 1]; sizvox = [nrpttap sizvox]; elseif iscell(tmp) nrpttap = numel(stuff); sizvox = [size(tmp{input.inside(1)}) 1]; sizvox = [nrpttap sizvox]; end if siz(1) ~= npos && siz(2) ==npos, tmp = transpose(tmp); end if iscell(tmp) %allocate memory for cell-array tmpall = cell(npos,1); for n = 1:numel(input.inside) tmpall{input.inside(n)} = zeros(sizvox); end else %allocate memory for matrix tmpall = zeros([npos nrpt siz(2:end)]); end cnt = 0; for m = 1:nrpt tmp = getfield(stuff(m), fnames{k}); siz = size(tmp); if siz(1) ~= npos && siz(2) ==npos, tmp = transpose(tmp); end if ~iscell(tmp), tmpall(:,m,:,:,:) = tmp; else for n = 1:numel(input.inside) indx = input.inside(n); tmpdat = tmp{indx}; if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom'), if n==1, siz1 = size(tmpdat,2); end else if n==1, siz1 = 1; end end tmpall{indx}(cnt+[1:siz1],:,:,:,:) = tmpdat; if n==numel(input.inside), cnt = cnt + siz1; end end end end output = setfield(output, fnames{k}, tmpall); newdimord = createdimord(output, fnames{k}, 1); if ~isempty(newdimord) output = setfield(output, [fnames{k},'dimord'], newdimord); end else tmp = getfield(stuff, fnames{k}); siz = size(tmp); if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom') %pcc based mom is orixrpttap %tranpose to keep manageable for kk = 1:numel(input.inside) indx = input.inside(kk); tmp{indx} = permute(tmp{indx}, [2 1 3]); end end if siz(1) ~= npos && siz(2) ==npos, tmp = transpose(tmp); end output = setfield(output, fnames{k}, tmp); newdimord = createdimord(output, fnames{k}); if ~isempty(newdimord) output = setfield(output, [fnames{k},'dimord'], newdimord); end end end if isfield(output, 'csdlabel') output = setfield(output, 'orilabel', getfield(output, 'csdlabel')); output = rmfield(output, 'csdlabel'); end if isfield(output, 'leadfield') % add dimord to leadfield as well. since the leadfield is not in % the original .avg or .trial field it has not yet been taken care of output.leadfielddimord = createdimord(output, 'leadfield'); end if isfield(output, 'ori') % convert cell-array ori into matrix ori = zeros(3,npos) + nan; try, ori(:,output.inside) = cat(2, output.ori{output.inside}); catch %when oris are in wrong orientation (row rather than column) for k = 1:numel(output.inside) ori(:,output.inside(k)) = output.ori{output.inside(k)}'; end end output.ori = ori; end current = 'new'; elseif strcmp(current, 'new') && strcmp(type, 'old') %go from new to old error('not implemented yet'); end if strcmp(current, 'new') && strcmp(haspow, 'yes'), %---------------------------------------------- %convert mom into pow if requested and possible convert = 0; if isfield(output, 'mom') && size(output.mom{output.inside(1)},2)==1, convert = 1; else warning('conversion from mom to pow is not possible, either because there is no mom in the data, or because the dimension of mom>1. in that case call ft_sourcedescriptives first with cfg.projectmom'); end if isfield(output, 'cumtapcnt') convert = 1 & convert; else warning('conversion from mom to pow will not be done, because cumtapcnt is missing'); end if convert, npos = size(output.pos,1); nrpt = size(output.cumtapcnt,1); tmpmom = cat(2,output.mom{output.inside}); tmppow = zeros(npos, nrpt); tapcnt = [0;cumsum(output.cumtapcnt(:))]; for k = 1:nrpt ntap = tapcnt(k+1)-tapcnt(k); tmppow(output.inside,k) = sum(abs(tmpmom((tapcnt(k)+1):tapcnt(k+1),:)).^2,1)./ntap; end output.pow = tmppow; output.powdimord = ['pos_rpt_freq']; end elseif strcmp(current, 'old') && strcmp(haspow, 'yes') warning('construction of single trial power estimates is not implemented here using old style source representation'); end %-------------------------------------------------------- function [dimord] = createdimord(output, fname, rptflag); if nargin==2, rptflag = 0; end tmp = getfield(output, fname); dimord = ''; dimnum = 1; hasori = isfield(output, 'ori'); %if not, this is probably singleton and not relevant at the end if iscell(tmp) && (size(output.pos,1)==size(tmp,dimnum) || size(output.pos,1)==size(tmp,2)) dimord = [dimord,'{pos}']; dimnum = dimnum + 1; elseif ~iscell(tmp) && size(output.pos,1)==size(tmp,dimnum) dimord = [dimord,'pos']; dimnum = dimnum + 1; end switch fname case 'cov' if hasori, dimord = [dimord,'_ori_ori']; end; case 'csd' if hasori, dimord = [dimord,'_ori_ori']; end; case 'csdlabel' dimord = dimord; case 'filter' dimord = [dimord,'_ori_chan']; case 'leadfield' %if hasori, dimord = [dimord,'_chan_ori']; %else % dimord = [dimord,'_chan']; %end case 'mom' if isfield(output, 'cumtapcnt') && sum(output.cumtapcnt)==size(tmp{output.inside(1)},1) if hasori, dimord = [dimord,'_rpttap_ori']; else dimord = [dimord,'_rpttap']; end elseif isfield(output, 'time') if rptflag, dimord = [dimord,'_rpt']; dimnum = dimnum + 1; end if numel(output.time)==size(tmp{output.inside(1)},dimnum) dimord = [dimord,'_ori_time']; end end if isfield(output, 'freq') && numel(output.freq)>1, dimord = [dimord,'_freq']; end case 'nai' if isfield(output, 'freq') && numel(output.freq)==size(tmp,dimnum) dimord = [dimord,'_freq']; end case 'noise' if isfield(output, 'freq') && numel(output.freq)==size(tmp,dimnum) dimord = [dimord,'_freq']; end case 'noisecsd' if hasori, dimord = [dimord,'_ori_ori']; end case 'ori' dimord = ''; case 'pow' if isfield(output, 'cumtapcnt') && size(output.cumtapcnt,1)==size(tmp,dimnum) dimord = [dimord,'_rpt']; dimnum = dimnum + 1; end if isfield(output, 'freq') && numel(output.freq)>1 && numel(output.freq)==size(tmp,dimnum) dimord = [dimord,'_freq']; dimnum = dimnum+1; end if isfield(output, 'time') && numel(output.time)>1 && numel(output.time)==size(tmp,dimnum) dimord = [dimord,'_time']; dimnum = dimnum+1; end otherwise warning('skipping unknown fieldname %s', fname); %error(sprintf('unknown fieldname %s', fname)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = comp2raw(data) % just remove the component topographies data = rmfield(data, 'topo'); data = rmfield(data, 'topolabel'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = volume2source(data) if isfield(data, 'dimord') % it is a modern source description else % it is an old-fashioned source description xgrid = 1:data.dim(1); ygrid = 1:data.dim(2); zgrid = 1:data.dim(3); [x y z] = ndgrid(xgrid, ygrid, zgrid); data.pos = warp_apply(data.transform, [x(:) y(:) z(:)]); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = source2volume(data) if isfield(data, 'dimord') % it is a modern source description %this part depends on the assumption that the list of positions is describing a full 3D volume in %an ordered way which allows for the extraction of a transformation matrix %i.e. slice by slice try, if isfield(data, 'dim'), data.dim = pos2dim(data.pos, data.dim); else data.dim = pos2dim(data); end catch end end if isfield(data, 'dim') && length(data.dim)>=3, % it is an old-fashioned source description, or the source describes a regular 3D volume in pos xgrid = 1:data.dim(1); ygrid = 1:data.dim(2); zgrid = 1:data.dim(3); [x y z] = ndgrid(xgrid, ygrid, zgrid); ind = [x(:) y(:) z(:)]; % these are the positions expressed in voxel indices along each of the three axes pos = data.pos; % these are the positions expressed in head coordinates % represent the positions in a manner that is compatible with the homogeneous matrix multiplication, % i.e. pos = H * ind ind = ind'; ind(4,:) = 1; pos = pos'; pos(4,:) = 1; % recompute the homogeneous transformation matrix data.transform = pos / ind; end % remove the unwanted fields if isfield(data, 'pos'), data = rmfield(data, 'pos'); end if isfield(data, 'xgrid'), data = rmfield(data, 'xgrid'); end if isfield(data, 'ygrid'), data = rmfield(data, 'ygrid'); end if isfield(data, 'zgrid'), data = rmfield(data, 'zgrid'); end % make inside a volume data = fixinside(data, 'logical'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = freq2raw(freq) if strcmp(freq.dimord, 'rpt_chan_freq_time') dat = freq.powspctrm; elseif strcmp(freq.dimord, 'rpttap_chan_freq_time') warning('converting fourier representation into raw data format. this is experimental code'); dat = freq.fourierspctrm; else error('this only works for dimord=''rpt_chan_freq_time'''); end nrpt = size(dat,1); nchan = size(dat,2); nfreq = size(dat,3); ntime = size(dat,4); data = []; % create the channel labels like "MLP11@12Hz"" k = 0; for i=1:nfreq for j=1:nchan k = k+1; data.label{k} = sprintf('%s@%dHz', freq.label{j}, freq.freq(i)); end end % reshape and copy the data as if it were timecourses only for i=1:nrpt data.time{i} = freq.time; data.trial{i} = reshape(dat(i,:,:,:), nchan*nfreq, ntime); if any(isnan(data.trial{i}(1,:))), tmp = data.trial{i}(1,:); begsmp = find(isfinite(tmp),1, 'first'); endsmp = find(isfinite(tmp),1, 'last' ); data.trial{i} = data.trial{i}(:, begsmp:endsmp); data.time{i} = data.time{i}(begsmp:endsmp); end end nsmp = cellfun('size',data.time,2); seln = find(nsmp>1,1, 'first'); data.fsample = 1/(data.time{seln}(2)-data.time{seln}(1)); if isfield(freq, 'trialinfo'), data.trialinfo = freq.trialinfo; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = raw2timelock(data) nsmp = cellfun('size',data.time,2); data = ft_checkdata(data, 'hassampleinfo', 'yes'); ntrial = numel(data.trial); nchan = numel(data.label); if ntrial==1 data.time = data.time{1}; data.avg = data.trial{1}; data = rmfield(data, 'trial'); data.dimord = 'chan_time'; else % determine the location of the trials relative to the resulting combined time axis begtime = cellfun(@min, data.time); endtime = cellfun(@max, data.time); begsmp = round((begtime - min(begtime)) * data.fsample) + 1; endsmp = round((endtime - min(begtime)) * data.fsample) + 1; % create a combined time axis and concatenate all trials tmptime = min(begtime):(1/data.fsample):max(endtime); tmptrial = zeros(ntrial, nchan, length(tmptime)) + nan; for i=1:ntrial tmptrial(i,:,begsmp(i):endsmp(i)) = data.trial{i}; end % update the sampleinfo begpad = begsmp - min(begsmp); endpad = max(endsmp) - endsmp; if isfield(data, 'sampleinfo') data.sampleinfo = data.sampleinfo + [-begpad(:) endpad(:)]; end % construct the output timelocked data % data.avg = reshape(nanmean(tmptrial, 1), nchan, length(tmptime)); % data.var = reshape(nanvar (tmptrial, [], 1), nchan, length(tmptime)) % data.dof = reshape(sum(~isnan(tmptrial), 1), nchan, length(tmptime)); data.trial = tmptrial; data.time = tmptime; data.dimord = 'rpt_chan_time'; data = rmfield(data, 'fsample'); % fsample in timelock data is obsolete end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = timelock2raw(data) try nsmp = cellfun('size',data.time,2); catch nsmp = size(data.time,2); end switch data.dimord case 'chan_time' data.trial{1} = data.avg; data.time = {data.time}; data = rmfield(data, 'avg'); seln = find(nsmp>1,1, 'first'); data.fsample = 1/(data.time{seln}(2)-data.time{seln}(1)); case 'rpt_chan_time' tmptrial = {}; tmptime = {}; ntrial = size(data.trial,1); nchan = size(data.trial,2); ntime = size(data.trial,3); for i=1:ntrial tmptrial{i} = reshape(data.trial(i,:,:), [nchan, ntime]); tmptime{i} = data.time; end data = rmfield(data, 'trial'); data.trial = tmptrial; data.time = tmptime; seln = find(nsmp>1,1, 'first'); data.fsample = 1/(data.time{seln}(2)-data.time{seln}(1)); case 'subj_chan_time' tmptrial = {}; tmptime = {}; ntrial = size(data.individual,1); nchan = size(data.individual,2); ntime = size(data.individual,3); for i=1:ntrial tmptrial{i} = reshape(data.individual(i,:,:), [nchan, ntime]); tmptime{i} = data.time; end data = rmfield(data, 'individual'); data.trial = tmptrial; data.time = tmptime; seln = find(nsmp>1,1, 'first'); data.fsample = 1/(data.time{seln}(2)-data.time{seln}(1)); otherwise error('unsupported dimord'); end % remove the unwanted fields if isfield(data, 'avg'), data = rmfield(data, 'avg'); end if isfield(data, 'var'), data = rmfield(data, 'var'); end if isfield(data, 'cov'), data = rmfield(data, 'cov'); end if isfield(data, 'dimord'), data = rmfield(data, 'dimord'); end if isfield(data, 'numsamples'), data = rmfield(data, 'numsamples'); end if isfield(data, 'dof'), data = rmfield(data, 'dof'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = chan2freq(data) data.dimord = [data.dimord '_freq']; data.freq = nan; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = chan2timelock(data) data.dimord = [data.dimord '_time']; data.time = nan;
github
philippboehmsturm/antx-master
read_yokogawa_data.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_yokogawa_data.m
11,038
utf_8
74c9636ae61942d31441ba41eab36d6f
function [dat] = read_yokogawa_data(filename, hdr, begsample, endsample, chanindx) % READ_YOKAGAWA_DATA reads continuous, epoched or averaged MEG data % that has been generated by the Yokogawa MEG system and software % and allows that data to be used in combination with FieldTrip. % % Use as % [dat] = read_yokogawa_data(filename, hdr, begsample, endsample, chanindx) % % This is a wrapper function around the functions % GetMeg160ContinuousRawDataM % GetMeg160EvokedAverageDataM % GetMeg160EvokedRawDataM % % See also READ_YOKOGAWA_HEADER, READ_YOKOGAWA_EVENT % 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_data.m 2617 2011-01-20 15:19:35Z jorhor $ if ~ft_hastoolbox('yokogawa') error('cannot determine whether Yokogawa toolbox is present'); end % hdr = read_yokogawa_header(filename); hdr = hdr.orig; % use the original Yokogawa header, not the FieldTrip header % default is to select all channels if nargin<5 chanindx = 1:hdr.channel_count; end handles = definehandles; fid = fopen(filename, 'rb', 'ieee-le'); switch hdr.acq_type case handles.AcqTypeEvokedAve % Data is returned by double. start_sample = begsample - 1; % samples start at 0 sample_length = endsample - begsample + 1; epoch_count = 1; start_epoch = 0; dat = double(GetMeg160EvokedAverageDataM( fid, start_sample, sample_length )); % the first extra sample is the channel number channum = dat(:,1); dat = dat(:,2:end); case handles.AcqTypeContinuousRaw % Data is returned by int16. start_sample = begsample - 1; % samples start at 0 sample_length = endsample - begsample + 1; epoch_count = 1; start_epoch = 0; dat = double(GetMeg160ContinuousRawDataM( fid, start_sample, sample_length )); % the first extra sample is the channel number channum = dat(:,1); dat = dat(:,2:end); case handles.AcqTypeEvokedRaw % Data is returned by int16. begtrial = ceil(begsample/hdr.sample_count); endtrial = ceil(endsample/hdr.sample_count); if begtrial<1 error('cannot read before the begin of the file'); elseif endtrial>hdr.actual_epoch_count error('cannot read beyond the end of the file'); end epoch_count = endtrial-begtrial+1; start_epoch = begtrial-1; % read all the neccessary trials that contain the desired samples dat = double(GetMeg160EvokedRawDataM( fid, start_epoch, epoch_count )); % the first extra sample is the channel number channum = dat(:,1); dat = dat(:,2:end); if size(dat,2)~=epoch_count*hdr.sample_count error('could not read all epochs'); end rawbegsample = begsample - (begtrial-1)*hdr.sample_count; rawendsample = endsample - (begtrial-1)*hdr.sample_count; sample_length = rawendsample - rawbegsample + 1; % select the desired samples from the complete trials dat = dat(:,rawbegsample:rawendsample); otherwise error('unknown data type'); end fclose(fid); if size(dat,1)~=hdr.channel_count error('could not read all channels'); elseif size(dat,2)~=(endsample-begsample+1) error('could not read all samples'); end % Count of AxialGradioMeter ch_type = hdr.channel_info(:,2); index = find(ch_type==[handles.AxialGradioMeter]); axialgradiometer_index_tmp = index; axialgradiometer_ch_count = length(index); % Count of PlannerGradioMeter ch_type = hdr.channel_info(:,2); index = find(ch_type==[handles.PlannerGradioMeter]); plannergradiometer_index_tmp = index; plannergradiometer_ch_count = length(index); % Count of EegChannel ch_type = hdr.channel_info(:,2); index = find(ch_type==[handles.EegChannel]); eegchannel_index_tmp = index; eegchannel_ch_count = length(index); % Count of NullChannel ch_type = hdr.channel_info(:,2); index = find(ch_type==[handles.NullChannel]); nullchannel_index_tmp = index; nullchannel_ch_count = length(index); %%% Pulling out AxialGradioMeter and value conversion to physical units. if ~isempty(axialgradiometer_index_tmp) % Acquisition of channel information axialgradiometer_index = axialgradiometer_index_tmp; ch_info = hdr.channel_info; axialgradiometer_ch_info = ch_info(axialgradiometer_index, :); % Value conversion % B = ( ADValue * VoltRange / ADRange - Offset ) * Sensitivity / FLLGain calib = hdr.calib_info; amp_gain = hdr.amp_gain(1); tmp_ch_no = channum(axialgradiometer_index, 1); tmp_data = dat(axialgradiometer_index, 1:sample_length); tmp_offset = calib(axialgradiometer_index, 3) * ones(1,sample_length); ad_range = 5/2^(hdr.ad_bit-1); tmp_data = ( tmp_data * ad_range - tmp_offset ); clear tmp_offset; tmp_gain = calib(axialgradiometer_index, 2) * ones(1,sample_length); tmp_data = tmp_data .* tmp_gain / amp_gain; dat(axialgradiometer_index, 1:sample_length) = tmp_data; clear tmp_gain; % Deletion of Inf row index = find(axialgradiometer_ch_info(1,:) == Inf); axialgradiometer_ch_info(:,index) = []; % Deletion of channel_type row axialgradiometer_ch_info(:,2) = []; % Outputs to the global variable handles.sqd.axialgradiometer_ch_info = axialgradiometer_ch_info; handles.sqd.axialgradiometer_ch_no = tmp_ch_no; handles.sqd.axialgradiometer_data = [ tmp_ch_no tmp_data]; clear tmp_data; end %%% Pulling out PlannerGradioMeter and value conversion to physical units. if ~isempty(plannergradiometer_index_tmp) % Acquisition of channel information plannergradiometer_index = plannergradiometer_index_tmp; ch_info = hdr.channel_info; plannergradiometer_ch_info = ch_info(plannergradiometer_index, :); % Value conversion % B = ( ADValue * VoltRange / ADRange - Offset ) * Sensitivity / FLLGain calib = hdr.calib_info; amp_gain = hdr.amp_gain(1); tmp_ch_no = channum(plannergradiometer_index, 1); tmp_data = dat(plannergradiometer_index, 1:sample_length); tmp_offset = calib(plannergradiometer_index, 3) * ones(1,sample_length); ad_range = 5/2^(hdr.ad_bit-1); tmp_data = ( tmp_data * ad_range - tmp_offset ); clear tmp_offset; tmp_gain = calib(plannergradiometer_index, 2) * ones(1,sample_length); tmp_data = tmp_data .* tmp_gain / amp_gain; dat(plannergradiometer_index, 1:sample_length) = tmp_data; clear tmp_gain; % Deletion of Inf row index = find(plannergradiometer_ch_info(1,:) == Inf); plannergradiometer_ch_info(:,index) = []; % Deletion of channel_type row plannergradiometer_ch_info(:,2) = []; % Outputs to the global variable handles.sqd.plannergradiometer_ch_info = plannergradiometer_ch_info; handles.sqd.plannergradiometer_ch_no = tmp_ch_no; handles.sqd.plannergradiometer_data = [ tmp_ch_no tmp_data]; clear tmp_data; end %%% Pulling out EegChannel Channel and value conversion to Volt units. if ~isempty(eegchannel_index_tmp) % Acquisition of channel information eegchannel_index = eegchannel_index_tmp; % Value conversion % B = ADValue * VoltRange / ADRange tmp_ch_no = channum(eegchannel_index, 1); tmp_data = dat(eegchannel_index, 1:sample_length); ad_range = 5/2^(hdr.ad_bit-1); tmp_data = tmp_data * ad_range; dat(eegchannel_index, 1:sample_length) = tmp_data; % Outputs to the global variable handles.sqd.eegchannel_ch_no = tmp_ch_no; handles.sqd.eegchannel_data = [ tmp_ch_no tmp_data]; clear tmp_data; end %%% Pulling out Null Channel and value conversion to Volt units. if ~isempty(nullchannel_index_tmp) % Acquisition of channel information nullchannel_index = nullchannel_index_tmp; % Value conversion % B = ADValue * VoltRange / ADRange tmp_ch_no = channum(nullchannel_index, 1); tmp_data = dat(nullchannel_index, 1:sample_length); ad_range = 5/2^(hdr.ad_bit-1); tmp_data = tmp_data * ad_range; dat(nullchannel_index, 1:sample_length) = tmp_data; % Outputs to the global variable handles.sqd.nullchannel_ch_no = tmp_ch_no; handles.sqd.nullchannel_data = [ tmp_ch_no tmp_data]; clear tmp_data; end % select only the desired channels dat = dat(chanindx,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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
philippboehmsturm/antx-master
read_biff.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_biff.m
5,856
utf_8
0a2dd51be5783d5f256831f0a6d9e6ae
function [this] = read_biff(filename, opt) % READ_BIFF reads data and header information from a BIFF file % % This is a attemt for a reference implementation to read the BIFF % file format as defined by the Clinical Neurophysiology department of % the University Medical Centre, Nijmegen. % % read all data and information % [data] = read_biff(filename) % or read a selected top-level chunk % [chunk] = read_biff(filename, chunkID) % % known top-level chunk id's are % data : measured data (matrix) % dati : information on data (struct) % expi : information on experiment (struct) % pati : information on patient (struct) % evnt : event markers (struct) % Copyright (C) 2000, 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_biff.m 945 2010-04-21 17:41:20Z roboos $ define_biff; this = []; fid = fopen(filename, 'r'); fseek(fid,0,'eof'); eof = ftell(fid); fseek(fid,0,'bof'); [id, siz] = chunk_header(fid); switch id case 'SEMG' child = subtree(BIFF, id); this = read_biff_chunk(fid, id, siz, child); case 'LIST' fprintf('skipping unimplemented chunk id="%s" size=%4d\n', id, siz); case 'CAT ' fprintf('skipping unimplemented chunk id="%s" size=%4d\n', id, siz); otherwise fprintf('skipping unrecognized chunk id="%s" size=%4d\n', id, siz); fseek(fid, siz, 'cof'); end % switch fclose(fid); % close file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION read_biff_chunk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function this = read_biff_chunk(fid, id, siz, chunk); % start with empty structure this = []; if strcmp(id, 'null') % this is an empty chunk fprintf('skipping empty chunk id="%s" size=%4d\n', id, siz); assert(~feof(fid)); fseek(fid, siz, 'cof'); elseif isempty(chunk) % this is an unrecognized chunk fprintf('skipping unrecognized chunk id="%s" size=%4d\n', id, siz); assert(~feof(fid)); fseek(fid, siz, 'cof'); else eoc = ftell(fid) + siz; name = char(chunk.desc(2)); type = char(chunk.desc(3)); fprintf('reading chunk id= "%s" size=%4d name="%s"\n', id, siz, name); switch type case 'group' while ~feof(fid) & ftell(fid)<eoc % read all subchunks [id, siz] = chunk_header(fid); child = subtree(chunk, id); if ~isempty(child) % read data and add subchunk data to chunk structure name = char(child.desc(2)); val = read_biff_chunk(fid, id, siz, child); this = setfield(this, name, val); else fprintf('skipping unrecognized chunk id="%s" size=%4d\n', id, siz); fseek(fid, siz, 'cof'); end end % while case 'string' this = char(fread(fid, siz, 'uchar')'); case {'char', 'uchar', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'float32', 'float64'} this = fread(fid, 1, type); case {'char', 'uchar', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'float32', 'float64'} this = fread(fid, 1, type); case {'int8vec', 'int16vec', 'int32vec', 'int64vec', 'uint8vec', 'uint16vec', 'uint32vec', 'float32vec', 'float64vec'} ncol = fread(fid, 1, 'uint32'); this = fread(fid, ncol, type(1:(length(type)-3))); case {'int8mat', 'int16mat', 'int32mat', 'int64mat', 'uint8mat', 'uint16mat', 'uint32mat', 'float32mat', 'float64mat'} nrow = fread(fid, 1, 'uint32'); ncol = fread(fid, 1, 'uint32'); this = fread(fid, [nrow, ncol], type(1:(length(type)-3))); otherwise fseek(fid, siz, 'cof'); % skip this chunk sprintf('unimplemented data type "%s" in chunk "%s"', type, id); % warning(ans); end % switch chunk type end % else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION subtree %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function child = subtree(parent, id); blank = findstr(id, ' '); while ~isempty(blank) id(blank) = '_'; blank = findstr(id, ' '); end elem = fieldnames(parent); % list of all subitems num = find(strcmp(elem, id)); % number in parent tree if size(num) == [1,1] child = getfield(parent, char(elem(num))); % child subtree else child = []; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION chunk_header %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [id, siz] = chunk_header(fid); id = char(fread(fid, 4, 'uchar')'); % read chunk ID siz = fread(fid, 1, 'uint32'); % read chunk size if strcmp(id, 'GRP ') | strcmp(id, 'BIFF') id = char(fread(fid, 4, 'uchar')'); % read real chunk ID siz = siz - 4; % reduce size by 4 end
github
philippboehmsturm/antx-master
read_eeglabheader.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_eeglabheader.m
2,255
utf_8
fe4446f32b250441d57acff9ebe691a2
% read_eeglabheader() - import EEGLAB dataset files % % Usage: % >> header = read_eeglabheader(filename); % % Inputs: % filename - [string] file name % % Outputs: % header - FILEIO toolbox type structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2008- %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2008 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 header = read_eeglabheader(filename) if nargin < 1 help read_eeglabheader; return; end; if ~isstruct(filename) load('-mat', filename); else EEG = filename; end; header.Fs = EEG.srate; header.nChans = EEG.nbchan; header.nSamples = EEG.pnts; header.nSamplesPre = -EEG.xmin*EEG.srate; header.nTrials = EEG.trials; try header.label = { EEG.chanlocs.labels }'; catch warning('creating default channel names'); for i=1:header.nChans header.label{i} = sprintf('chan%03d', i); end end ind = 1; for i = 1:length( EEG.chanlocs ) if isfield(EEG.chanlocs(i), 'X') && ~isempty(EEG.chanlocs(i).X) header.elec.label{ind, 1} = EEG.chanlocs(i).labels; % this channel has a position header.elec.pnt(ind,1) = EEG.chanlocs(i).X; header.elec.pnt(ind,2) = EEG.chanlocs(i).Y; header.elec.pnt(ind,3) = EEG.chanlocs(i).Z; ind = ind+1; end; end; % remove data % ----------- %if isfield(EEG, 'datfile') % if ~isempty(EEG.datfile) % EEG.data = EEG.datfile; % end; %else % EEG.data = 'in set file'; %end; EEG.icaact = []; header.orig = EEG;
github
philippboehmsturm/antx-master
read_ctf_svl.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_ctf_svl.m
3,812
utf_8
d3442d0a013cf5e0a8d4277d99e45206
% [data, hdr] = opensvl(filename) % % Reads a CTF SAM (.svl) file. function [data, hdr] = read_ctf_svl(filename) fid = fopen(filename, 'rb', 'ieee-be', 'ISO-8859-1'); if fid <= 0 error('Could not open SAM file: %s\n', filename); end % ---------------------------------------------------------------------- % Read header. hdr.identity = fread(fid, 8, '*char')'; % 'SAMIMAGE' hdr.version = fread(fid, 1, 'int32'); % SAM file version. hdr.setName = fread(fid, 256, '*char')'; % Dataset name. hdr.numChans = fread(fid, 1, 'int32'); hdr.numWeights = fread(fid, 1, 'int32'); % 0 for static image. if(hdr.numWeights ~= 0) warning('hdr.numWeights ~= 0'); end fread(fid,1,'int32'); % Padding to next 8 byte boundary. hdr.xmin = fread(fid, 1, 'double'); % Bounding box coordinates (m). hdr.xmax = fread(fid, 1, 'double'); hdr.ymin = fread(fid, 1, 'double'); hdr.ymax = fread(fid, 1, 'double'); hdr.zmin = fread(fid, 1, 'double'); hdr.zmax = fread(fid, 1, 'double'); hdr.stepSize = fread(fid, 1, 'double'); % m hdr.hpFreq = fread(fid, 1, 'double'); % High pass filtering frequency (Hz). hdr.lpFreq = fread(fid, 1, 'double'); % Low pass. hdr.bwFreq = fread(fid, 1, 'double'); % Bandwidth hdr.meanNoise = fread(fid, 1, 'double'); % Sensor noise (T). hdr.mriName = fread(fid, 256, '*char')'; hdr.fiducial.mri.nas = fread(fid, 3, 'int32'); % CTF MRI voxel coordinates? hdr.fiducial.mri.rpa = fread(fid, 3, 'int32'); hdr.fiducial.mri.lpa = fread(fid, 3, 'int32'); hdr.SAMType = fread(fid, 1, 'int32'); % 0: image, 1: weights array, 2: weights list. hdr.SAMUnit = fread(fid, 1, 'int32'); % Possible values: 0 coefficients Am/T, 1 moment Am, 2 power (Am)^2, 3 Z, % 4 F, 5 T, 6 probability, 7 MUSIC. fread(fid, 1, 'int32'); % Padding to next 8 byte boundary. if hdr.version > 1 % Version 2 has extra fields. hdr.fiducial.head.nas = fread(fid, 3, 'double'); % CTF head coordinates? hdr.fiducial.head.rpa = fread(fid, 3, 'double'); hdr.fiducial.head.lpa = fread(fid, 3, 'double'); hdr.SAMUnitName = fread(fid, 32, '*char')'; % Possible values: 'Am/T' SAM coefficients, 'Am' source strength, % '(Am)^2' source power, ('Z', 'F', 'T') statistics, 'P' probability. end % ---------------------------------------------------------------------- % Read image data. data = fread(fid, inf, 'double'); fclose(fid); % Raw image data is ordered as a C array with indices: [x][y][z], meaning % z changes fastest and x slowest. These x, y, z axes point to ALS % (anterior, left, superior) respectively in real world coordinates, % which means the voxels are in SLA order. % ---------------------------------------------------------------------- % Post processing. % Change from m to mm. hdr.xmin = hdr.xmin * 1000; hdr.ymin = hdr.ymin * 1000; hdr.zmin = hdr.zmin * 1000; hdr.xmax = hdr.xmax * 1000; hdr.ymax = hdr.ymax * 1000; hdr.zmax = hdr.zmax * 1000; hdr.stepSize = hdr.stepSize * 1000; % Number of voxels in each dimension. hdr.dim = [round((hdr.xmax - hdr.xmin)/hdr.stepSize) + 1, ... round((hdr.ymax - hdr.ymin)/hdr.stepSize) + 1, ... round((hdr.zmax - hdr.zmin)/hdr.stepSize) + 1]; data = reshape(data, hdr.dim([3, 2, 1])); % Build transformation matrix from raw voxel coordinates (indexed from 1) % to head coordinates in mm. Note that the bounding box is given in % these coordinates (in m, but converted above). % Apply scaling. hdr.transform = diag([hdr.stepSize * ones(1, 3), 1]); % Reorder directions. hdr.transform = hdr.transform(:, [3, 2, 1, 4]); % Apply translation. hdr.transform(1:3, 4) = [hdr.xmin; hdr.ymin; hdr.zmin] - hdr.stepSize; % -step is needed since voxels are indexed from 1. end
github
philippboehmsturm/antx-master
loadcnt.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/loadcnt.m
22,223
utf_8
5b218c963fe0c618bc663fc79c2fd844
% loadcnt() - Load a Neuroscan continuous signal file. % % Usage: % >> cnt = loadcnt(file, varargin) % % Inputs: % filename - name of the file with extension % % Optional inputs: % 't1' - start at time t1, default 0 % 'sample1' - start at sample1, default 0, overrides t1 % 'lddur' - duration of segment to load, default = whole file % 'ldnsamples' - number of samples to load, default = whole file, % overrides lddur % 'scale' - ['on'|'off'] scale data to microvolt (default:'on') % 'dataformat' - ['int16'|'int32'] default is 'int16' for 16-bit data. % Use 'int32' for 32-bit data. % 'blockread' - [integer] by default it is automatically determined % from the file header, though sometimes it finds an % incorect value, so you may want to enter a value manually % here (1 is the most standard value). % 'memmapfile' - ['memmapfile_name'] use this option if the .cnt file % is too large to read in conventially. The suffix of % the memmapfile_name must be .fdt. The memmapfile % functions process files based on their suffix, and an % error will occur if you use a different suffix. % % Outputs: % cnt - structure with the continuous data and other informations % cnt.header % cnt.electloc % cnt.data % cnt.tag % % Authors: Sean Fitzgibbon, Arnaud Delorme, 2000- % % Note: function original name was load_scan41.m % % Known limitations: % For more see http://www.cnl.salk.edu/~arno/cntload/index.html %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2000 Sean Fitzgibbon, <[email protected]> % 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 [f,lab,ev2p] = loadcnt(filename,varargin) if ~isempty(varargin) r=struct(varargin{:}); else r = []; end; try, r.t1; catch, r.t1=0; end try, r.sample1; catch, r.sample1=[]; end try, r.lddur; catch, r.lddur=[]; end try, r.ldnsamples; catch, r.ldnsamples=[]; end try, r.scale; catch, r.scale='on'; end try, r.blockread; catch, r.blockread = []; end try, r.dataformat; catch, r.dataformat = 'int16'; end try, r.memmapfile; catch, r.memmapfile = ''; end sizeEvent1 = 8 ; %%% 8 bytes for Event1 sizeEvent2 = 19 ; %%% 19 bytes for Event2 sizeEvent3 = 19 ; %%% 19 bytes for Event3 type='cnt'; if nargin ==1 scan=0; end fid = fopen(filename,'r', 'l'); disp(['Loading file ' filename ' ...']) h.rev = fread(fid,12,'char'); h.nextfile = fread(fid,1,'long'); h.prevfile = fread(fid,1,'ulong'); h.type = fread(fid,1,'char'); h.id = fread(fid,20,'char'); h.oper = fread(fid,20,'char'); h.doctor = fread(fid,20,'char'); h.referral = fread(fid,20,'char'); h.hospital = fread(fid,20,'char'); h.patient = fread(fid,20,'char'); h.age = fread(fid,1,'short'); h.sex = fread(fid,1,'char'); h.hand = fread(fid,1,'char'); h.med = fread(fid,20, 'char'); h.category = fread(fid,20, 'char'); h.state = fread(fid,20, 'char'); h.label = fread(fid,20, 'char'); h.date = fread(fid,10, 'char'); h.time = fread(fid,12, 'char'); h.mean_age = fread(fid,1,'float'); h.stdev = fread(fid,1,'float'); h.n = fread(fid,1,'short'); h.compfile = fread(fid,38,'char'); h.spectwincomp = fread(fid,1,'float'); h.meanaccuracy = fread(fid,1,'float'); h.meanlatency = fread(fid,1,'float'); h.sortfile = fread(fid,46,'char'); h.numevents = fread(fid,1,'int'); h.compoper = fread(fid,1,'char'); h.avgmode = fread(fid,1,'char'); h.review = fread(fid,1,'char'); h.nsweeps = fread(fid,1,'ushort'); h.compsweeps = fread(fid,1,'ushort'); h.acceptcnt = fread(fid,1,'ushort'); h.rejectcnt = fread(fid,1,'ushort'); h.pnts = fread(fid,1,'ushort'); h.nchannels = fread(fid,1,'ushort'); h.avgupdate = fread(fid,1,'ushort'); h.domain = fread(fid,1,'char'); h.variance = fread(fid,1,'char'); h.rate = fread(fid,1,'ushort'); % A USER CLAIMS THAT SAMPLING RATE CAN BE h.scale = fread(fid,1,'double'); % FRACTIONAL IN NEUROSCAN WHICH IS h.veogcorrect = fread(fid,1,'char'); % OBVIOUSLY NOT POSSIBLE HERE (BUG 606) h.heogcorrect = fread(fid,1,'char'); h.aux1correct = fread(fid,1,'char'); h.aux2correct = fread(fid,1,'char'); h.veogtrig = fread(fid,1,'float'); h.heogtrig = fread(fid,1,'float'); h.aux1trig = fread(fid,1,'float'); h.aux2trig = fread(fid,1,'float'); h.heogchnl = fread(fid,1,'short'); h.veogchnl = fread(fid,1,'short'); h.aux1chnl = fread(fid,1,'short'); h.aux2chnl = fread(fid,1,'short'); h.veogdir = fread(fid,1,'char'); h.heogdir = fread(fid,1,'char'); h.aux1dir = fread(fid,1,'char'); h.aux2dir = fread(fid,1,'char'); h.veog_n = fread(fid,1,'short'); h.heog_n = fread(fid,1,'short'); h.aux1_n = fread(fid,1,'short'); h.aux2_n = fread(fid,1,'short'); h.veogmaxcnt = fread(fid,1,'short'); h.heogmaxcnt = fread(fid,1,'short'); h.aux1maxcnt = fread(fid,1,'short'); h.aux2maxcnt = fread(fid,1,'short'); h.veogmethod = fread(fid,1,'char'); h.heogmethod = fread(fid,1,'char'); h.aux1method = fread(fid,1,'char'); h.aux2method = fread(fid,1,'char'); h.ampsensitivity = fread(fid,1,'float'); h.lowpass = fread(fid,1,'char'); h.highpass = fread(fid,1,'char'); h.notch = fread(fid,1,'char'); h.autoclipadd = fread(fid,1,'char'); h.baseline = fread(fid,1,'char'); h.offstart = fread(fid,1,'float'); h.offstop = fread(fid,1,'float'); h.reject = fread(fid,1,'char'); h.rejstart = fread(fid,1,'float'); h.rejstop = fread(fid,1,'float'); h.rejmin = fread(fid,1,'float'); h.rejmax = fread(fid,1,'float'); h.trigtype = fread(fid,1,'char'); h.trigval = fread(fid,1,'float'); h.trigchnl = fread(fid,1,'char'); h.trigmask = fread(fid,1,'short'); h.trigisi = fread(fid,1,'float'); h.trigmin = fread(fid,1,'float'); h.trigmax = fread(fid,1,'float'); h.trigdir = fread(fid,1,'char'); h.autoscale = fread(fid,1,'char'); h.n2 = fread(fid,1,'short'); h.dir = fread(fid,1,'char'); h.dispmin = fread(fid,1,'float'); h.dispmax = fread(fid,1,'float'); h.xmin = fread(fid,1,'float'); h.xmax = fread(fid,1,'float'); h.automin = fread(fid,1,'float'); h.automax = fread(fid,1,'float'); h.zmin = fread(fid,1,'float'); h.zmax = fread(fid,1,'float'); h.lowcut = fread(fid,1,'float'); h.highcut = fread(fid,1,'float'); h.common = fread(fid,1,'char'); h.savemode = fread(fid,1,'char'); h.manmode = fread(fid,1,'char'); h.ref = fread(fid,10,'char'); h.rectify = fread(fid,1,'char'); h.displayxmin = fread(fid,1,'float'); h.displayxmax = fread(fid,1,'float'); h.phase = fread(fid,1,'char'); h.screen = fread(fid,16,'char'); h.calmode = fread(fid,1,'short'); h.calmethod = fread(fid,1,'short'); h.calupdate = fread(fid,1,'short'); h.calbaseline = fread(fid,1,'short'); h.calsweeps = fread(fid,1,'short'); h.calattenuator = fread(fid,1,'float'); h.calpulsevolt = fread(fid,1,'float'); h.calpulsestart = fread(fid,1,'float'); h.calpulsestop = fread(fid,1,'float'); h.calfreq = fread(fid,1,'float'); h.taskfile = fread(fid,34,'char'); h.seqfile = fread(fid,34,'char'); h.spectmethod = fread(fid,1,'char'); h.spectscaling = fread(fid,1,'char'); h.spectwindow = fread(fid,1,'char'); h.spectwinlength = fread(fid,1,'float'); h.spectorder = fread(fid,1,'char'); h.notchfilter = fread(fid,1,'char'); h.headgain = fread(fid,1,'short'); h.additionalfiles = fread(fid,1,'int'); h.unused = fread(fid,5,'char'); h.fspstopmethod = fread(fid,1,'short'); h.fspstopmode = fread(fid,1,'short'); h.fspfvalue = fread(fid,1,'float'); h.fsppoint = fread(fid,1,'short'); h.fspblocksize = fread(fid,1,'short'); h.fspp1 = fread(fid,1,'ushort'); h.fspp2 = fread(fid,1,'ushort'); h.fspalpha = fread(fid,1,'float'); h.fspnoise = fread(fid,1,'float'); h.fspv1 = fread(fid,1,'short'); h.montage = fread(fid,40,'char'); h.eventfile = fread(fid,40,'char'); h.fratio = fread(fid,1,'float'); h.minor_rev = fread(fid,1,'char'); h.eegupdate = fread(fid,1,'short'); h.compressed = fread(fid,1,'char'); h.xscale = fread(fid,1,'float'); h.yscale = fread(fid,1,'float'); h.xsize = fread(fid,1,'float'); h.ysize = fread(fid,1,'float'); h.acmode = fread(fid,1,'char'); h.commonchnl = fread(fid,1,'uchar'); h.xtics = fread(fid,1,'char'); h.xrange = fread(fid,1,'char'); h.ytics = fread(fid,1,'char'); h.yrange = fread(fid,1,'char'); h.xscalevalue = fread(fid,1,'float'); h.xscaleinterval = fread(fid,1,'float'); h.yscalevalue = fread(fid,1,'float'); h.yscaleinterval = fread(fid,1,'float'); h.scaletoolx1 = fread(fid,1,'float'); h.scaletooly1 = fread(fid,1,'float'); h.scaletoolx2 = fread(fid,1,'float'); h.scaletooly2 = fread(fid,1,'float'); h.port = fread(fid,1,'short'); h.numsamples = fread(fid,1,'ulong'); h.filterflag = fread(fid,1,'char'); h.lowcutoff = fread(fid,1,'float'); h.lowpoles = fread(fid,1,'short'); h.highcutoff = fread(fid,1,'float'); h.highpoles = fread(fid,1,'short'); h.filtertype = fread(fid,1,'char'); h.filterdomain = fread(fid,1,'char'); h.snrflag = fread(fid,1,'char'); h.coherenceflag = fread(fid,1,'char'); h.continuoustype = fread(fid,1,'char'); h.eventtablepos = fread(fid,1,'ulong'); h.continuousseconds = fread(fid,1,'float'); h.channeloffset = fread(fid,1,'long'); h.autocorrectflag = fread(fid,1,'char'); h.dcthreshold = fread(fid,1,'uchar'); for n = 1:h.nchannels e(n).lab = deblank(char(fread(fid,10,'char')')); e(n).reference = fread(fid,1,'char'); e(n).skip = fread(fid,1,'char'); e(n).reject = fread(fid,1,'char'); e(n).display = fread(fid,1,'char'); e(n).bad = fread(fid,1,'char'); e(n).n = fread(fid,1,'ushort'); e(n).avg_reference = fread(fid,1,'char'); e(n).clipadd = fread(fid,1,'char'); e(n).x_coord = fread(fid,1,'float'); e(n).y_coord = fread(fid,1,'float'); e(n).veog_wt = fread(fid,1,'float'); e(n).veog_std = fread(fid,1,'float'); e(n).snr = fread(fid,1,'float'); e(n).heog_wt = fread(fid,1,'float'); e(n).heog_std = fread(fid,1,'float'); e(n).baseline = fread(fid,1,'short'); e(n).filtered = fread(fid,1,'char'); e(n).fsp = fread(fid,1,'char'); e(n).aux1_wt = fread(fid,1,'float'); e(n).aux1_std = fread(fid,1,'float'); e(n).senstivity = fread(fid,1,'float'); e(n).gain = fread(fid,1,'char'); e(n).hipass = fread(fid,1,'char'); e(n).lopass = fread(fid,1,'char'); e(n).page = fread(fid,1,'uchar'); e(n).size = fread(fid,1,'uchar'); e(n).impedance = fread(fid,1,'uchar'); e(n).physicalchnl = fread(fid,1,'uchar'); e(n).rectify = fread(fid,1,'char'); e(n).calib = fread(fid,1,'float'); end % finding if 32-bits of 16-bits file % ---------------------------------- begdata = ftell(fid); enddata = h.eventtablepos; % after data if strcmpi(r.dataformat, 'int16') nums = (enddata-begdata)/h.nchannels/2; else nums = (enddata-begdata)/h.nchannels/4; end; % number of sample to read % ------------------------ if ~isempty(r.sample1) r.t1 = r.sample1/h.rate; else r.sample1 = r.t1*h.rate; end; if strcmpi(r.dataformat, 'int16') startpos = round(r.t1*h.rate*2*h.nchannels); else startpos = round(r.t1*h.rate*4*h.nchannels); end; if isempty(r.ldnsamples) if ~isempty(r.lddur) r.ldnsamples = round(r.lddur*h.rate); else r.ldnsamples = nums; end; end; % VL modification 1 ========================= h.nums = nums; % channel offset % -------------- if ~isempty(r.blockread) h.channeloffset = r.blockread; end; if h.channeloffset > 1 fprintf('WARNING: reading data in blocks of %d, if this fails, try using option "''blockread'', 1"\n', ... h.channeloffset); end; disp('Reading data .....') if type == 'cnt' % while (ftell(fid) +1 < h.eventtablepos) %d(:,i)=fread(fid,h.nchannels,'int16'); %end if fseek(fid, startpos, 'cof')<0 fclose(fid); error('fseek failed'); end % **** This marks the beginning of the code modified for reading % large .cnt files % Switched to r.memmapfile for continuity. Check to see if the % variable exists. If it does, then the user has indicated the % file is too large to be processed in memory. If the variable % is blank, the file is processed in memory. if (~isempty(r.memmapfile)) % open a file for writing foutid = fopen(r.memmapfile, 'w') ; % This portion of the routine reads in a section of the EEG file % and then writes it out to the harddisk. samples_left = h.nchannels * r.ldnsamples ; % the size of the data block to be read is limited to 4M % samples. This equates to 16MB and 32MB of memory for % 16 and 32 bit files, respectively. data_block = 4000000 ; max_rows = data_block / h.nchannels ; ws = warning('off'); max_written = h.nchannels * uint32(max_rows) ; warning(ws); % This while look tracks the remaining samples. The % data is processed in chunks rather than put into % memory whole. while (samples_left > 0) % Check to see if the remaining data is smaller than % the general processing block by looking at the % remaining number of rows. to_read = max_rows ; if (data_block > samples_left) to_read = samples_left / h.nchannels ; end ; % Read data in a relatively small chunk temp_dat = fread(fid, [h.nchannels to_read], r.dataformat) ; % The data is then scaled using the original routine. % In the original routine, the entire data set was scaled % after being read in. For this version, scaling occurs % after every chunk is read. if strcmpi(r.scale, 'on') disp('Scaling data .....') %%% scaling to microvolts for i=1:h.nchannels bas=e(i).baseline;sen=e(i).senstivity;cal=e(i).calib; mf=sen*(cal/204.8); temp_dat(i,:)=(temp_dat(i,:)-bas).*mf; end end % Write out data in float32 form to the file name % supplied by the user. written = fwrite (foutid, temp_dat, 'float32') ; if (written ~= max_written) samples_left = 0 ; else samples_left = samples_left - written ; end ; end ; fclose (foutid) ; % Set the dat variable. This gets used later by other % EEGLAB functions. dat = r.memmapfile ; % This variable tracks how the data should be read. bReadIntoMemory = false ; else % The memmapfile variable is empty, read into memory. bReadIntoMemory = true ; end % This ends the modifications made to read large files. % Everything contained within the following if statement is the % original code. if (bReadIntoMemory == true) if h.channeloffset <= 1 dat=fread(fid, [h.nchannels r.ldnsamples], r.dataformat); else h.channeloffset = h.channeloffset/2; % reading data in blocks dat = zeros( h.nchannels, r.ldnsamples); dat(:, 1:h.channeloffset) = fread(fid, [h.channeloffset h.nchannels], r.dataformat)'; counter = 1; while counter*h.channeloffset < r.ldnsamples dat(:, counter*h.channeloffset+1:counter*h.channeloffset+h.channeloffset) = ... fread(fid, [h.channeloffset h.nchannels], r.dataformat)'; counter = counter + 1; end; end ; % ftell(fid) if strcmpi(r.scale, 'on') disp('Scaling data .....') %%% scaling to microvolts for i=1:h.nchannels bas=e(i).baseline;sen=e(i).senstivity;cal=e(i).calib; mf=sen*(cal/204.8); dat(i,:)=(dat(i,:)-bas).*mf; end % end for i=1:h.nchannels end; % end if (strcmpi(r.scale, 'on') end ; ET_offset = (double(h.prevfile) * (2^32)) + double(h.eventtablepos); % prevfile contains high order bits of event table offset, eventtablepos contains the low order bits if fseek(fid, ET_offset, 'bof')<0 error('fseek failed'); end disp('Reading Event Table...') eT.teeg = fread(fid,1,'uchar'); eT.size = fread(fid,1,'ulong'); eT.offset = fread(fid,1,'ulong'); if eT.teeg==2 nevents=eT.size/sizeEvent2; if nevents > 0 ev2(nevents).stimtype = []; for i=1:nevents ev2(i).stimtype = fread(fid,1,'ushort'); ev2(i).keyboard = fread(fid,1,'char'); temp = fread(fid,1,'uint8'); ev2(i).keypad_accept = bitand(15,temp); ev2(i).accept_ev1 = bitshift(temp,-4); ev2(i).offset = fread(fid,1,'long'); ev2(i).type = fread(fid,1,'short'); ev2(i).code = fread(fid,1,'short'); ev2(i).latency = fread(fid,1,'float'); ev2(i).epochevent = fread(fid,1,'char'); ev2(i).accept = fread(fid,1,'char'); ev2(i).accuracy = fread(fid,1,'char'); end else ev2 = []; end; elseif eT.teeg==3 % type 3 is similar to type 2 except the offset field encodes the global sample frame nevents=eT.size/sizeEvent3; if nevents > 0 ev2(nevents).stimtype = []; if r.dataformat == 'int32' bytes_per_samp = 4; % I only have 32 bit data, unable to check whether this is necessary, else % perhaps there is no type 3 file with 16 bit data bytes_per_samp = 2; end for i=1:nevents ev2(i).stimtype = fread(fid,1,'ushort'); ev2(i).keyboard = fread(fid,1,'char'); temp = fread(fid,1,'uint8'); ev2(i).keypad_accept = bitand(15,temp); ev2(i).accept_ev1 = bitshift(temp,-4); os = fread(fid,1,'ulong'); ev2(i).offset = os * bytes_per_samp * h.nchannels; ev2(i).type = fread(fid,1,'short'); ev2(i).code = fread(fid,1,'short'); ev2(i).latency = fread(fid,1,'float'); ev2(i).epochevent = fread(fid,1,'char'); ev2(i).accept = fread(fid,1,'char'); ev2(i).accuracy = fread(fid,1,'char'); end else ev2 = []; end; elseif eT.teeg==1 nevents=eT.size/sizeEvent1; if nevents > 0 ev2(nevents).stimtype = []; for i=1:nevents ev2(i).stimtype = fread(fid,1,'ushort'); ev2(i).keyboard = fread(fid,1,'char'); % modified by Andreas Widmann 2005/05/12 14:15:00 %ev2(i).keypad_accept = fread(fid,1,'char'); temp = fread(fid,1,'uint8'); ev2(i).keypad_accept = bitand(15,temp); ev2(i).accept_ev1 = bitshift(temp,-4); % end modification ev2(i).offset = fread(fid,1,'long'); end; else ev2 = []; end; else disp('Skipping event table (tag != 1,2,3 ; theoritically impossible)'); ev2 = []; end fseek(fid, -1, 'eof'); t = fread(fid,'char'); f.header = h; f.electloc = e; f.data = dat; f.Teeg = eT; f.event = ev2; f.tag=t; % Surgical addition of number of samples f.ldnsamples = r.ldnsamples ; %%%% channels labels for i=1:h.nchannels plab=sprintf('%c',f.electloc(i).lab); if i>1 lab=str2mat(lab,plab); else lab=plab; end end %%%% to change offest in bytes to points if ~isempty(ev2) if r.sample1 ~= 0 % VL modification 2 ========================= % fprintf(2,'Warning: events imported with a time shift might be innacurate (bug 661)\n'); end; ev2p=ev2; ioff=900+(h.nchannels*75); %% initial offset : header + electordes desc if strcmpi(r.dataformat, 'int16') for i=1:nevents ev2p(i).offset=(ev2p(i).offset-ioff)/(2*h.nchannels) - r.sample1; %% 2 short int end end else % 32 bits for i=1:nevents ev2p(i).offset=(ev2p(i).offset-ioff)/(4*h.nchannels) - r.sample1; %% 4 short int end end end; f.event = ev2p; end; fclose(fid); end
github
philippboehmsturm/antx-master
read_yokogawa_header.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/read_yokogawa_header.m
8,340
utf_8
32f28f1896d6e12abd4e5d44024649bf
function hdr = read_yokogawa_header(filename) % READ_YOKOGAWA_HEADER reads the header information from continuous, % epoched or averaged MEG data that has been generated by the Yokogawa % MEG system and software and allows that data to be used in combination % with FieldTrip. % % Use as % [hdr] = read_yokogawa_header(filename) % % This is a wrapper function around the functions % GetMeg160SystemInfoM % GetMeg160ChannelCountM % GetMeg160ChannelInfoM % GetMeg160CalibInfoM % GetMeg160AmpGainM % GetMeg160DataAcqTypeM % GetMeg160ContinuousAcqCondM % GetMeg160EvokedAcqCondM % % See also READ_YOKOGAWA_DATA, READ_YOKOGAWA_EVENT % this function also calls % GetMeg160MriInfoM % GetMeg160MatchingInfoM % GetMeg160SourceInfoM % but I don't know whether to use the information provided by those % 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_header.m 2617 2011-01-20 15:19:35Z jorhor $ % FIXED % txt -> m % fopen iee-le if ~ft_hastoolbox('yokogawa') error('cannot determine whether Yokogawa toolbox is present'); end handles = definehandles; fid = fopen(filename, 'rb', 'ieee-le'); % these are always present [id ver rev sys_name] = GetMeg160SystemInfoM(fid); channel_count = GetMeg160ChannelCountM(fid); channel_info = GetMeg160ChannelInfoM(fid); calib_info = GetMeg160CalibInfoM(fid); amp_gain = GetMeg160AmpGainM(fid); acq_type = GetMeg160DataAcqTypeM(fid); ad_bit = GetMeg160ADbitInfoM(fid); % these depend on the data type sample_rate = []; sample_count = []; pretrigger_length = []; averaged_count = []; actual_epoch_count = []; switch acq_type case handles.AcqTypeContinuousRaw [sample_rate, sample_count] = GetMeg160ContinuousAcqCondM(fid); if isempty(sample_rate) | isempty(sample_count) fclose(fid); return; end pretrigger_length = 0; averaged_count = 1; case handles.AcqTypeEvokedAve [sample_rate, sample_count, pretrigger_length, averaged_count] = GetMeg160EvokedAcqCondM( fid ); if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(averaged_count) fclose(fid); return; end case handles.AcqTypeEvokedRaw [sample_rate, sample_count, pretrigger_length, actual_epoch_count] = GetMeg160EvokedAcqCondM( fid ); if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(actual_epoch_count) fclose(fid); return; end otherwise error('unknown data type'); end % these are always present mri_info = GetMeg160MriInfoM(fid); matching_info = GetMeg160MatchingInfoM(fid); source_info = GetMeg160SourceInfoM(fid); fclose(fid); % put all local variables into a structure, this is a bit unusual matlab programming style tmp = whos; orig = []; for i=1:length(tmp) if isempty(strmatch(tmp(i).name, {'tmp', 'fid', 'ans', 'handles'})) orig = setfield(orig, tmp(i).name, eval(tmp(i).name)); end end % convert the original header information into something that FieldTrip understands hdr = []; hdr.orig = orig; % also store the original full header information hdr.Fs = orig.sample_rate; % sampling frequency hdr.nChans = orig.channel_count; % 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 switch orig.acq_type case handles.AcqTypeEvokedAve hdr.nSamples = orig.sample_count; hdr.nSamplesPre = orig.pretrigger_length; hdr.nTrials = 1; % only the average, which can be considered as a single trial case handles.AcqTypeContinuousRaw hdr.nSamples = orig.sample_count; hdr.nSamplesPre = 0; % there is no fixed relation between triggers and data hdr.nTrials = 1; % the continuous data can be considered as a single very long trial case handles.AcqTypeEvokedRaw hdr.nSamples = orig.sample_count; hdr.nSamplesPre = orig.pretrigger_length; hdr.nTrials = orig.actual_epoch_count; otherwise error('unknown acquisition type'); end % construct a cell-array with labels of each channel for i=1:hdr.nChans % this should be consistent with the predefined list in ft_senslabel, % with yokogawa2grad and with ft_channelselection if hdr.orig.channel_info(i, 2) == handles.NullChannel prefix = ''; elseif hdr.orig.channel_info(i, 2) == handles.MagnetoMeter prefix = 'M'; elseif hdr.orig.channel_info(i, 2) == handles.AxialGradioMeter prefix = 'AG'; elseif hdr.orig.channel_info(i, 2) == handles.PlannerGradioMeter prefix = 'PG'; elseif hdr.orig.channel_info(i, 2) == handles.RefferenceMagnetoMeter prefix = 'RM'; elseif hdr.orig.channel_info(i, 2) == handles.RefferenceAxialGradioMeter prefix = 'RAG'; elseif hdr.orig.channel_info(i, 2) == handles.RefferencePlannerGradioMeter prefix = 'RPG'; elseif hdr.orig.channel_info(i, 2) == handles.TriggerChannel prefix = 'TRIG'; elseif hdr.orig.channel_info(i, 2) == handles.EegChannel prefix = 'EEG'; elseif hdr.orig.channel_info(i, 2) == handles.EcgChannel prefix = 'ECG'; elseif hdr.orig.channel_info(i, 2) == handles.EtcChannel prefix = 'ETC'; end hdr.label{i} = sprintf('%s%03d', prefix, i); 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
philippboehmsturm/antx-master
encode_nifti1.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/encode_nifti1.m
4,870
utf_8
9cf92a03587c511a5cec2c8c76a3c2c3
function blob = encode_nifti1(H) %function blob = encode_nifti1(H) % % Encodes a NIFTI-1 header (=> raw 348 bytes (uint8)) from a Matlab structure % that matches the C struct defined in nifti1.h. % % WARNING: This function currently ignores endianness !!! % (C) 2010 S.Klanke blob = uint8(zeros(1,348)); if ~isstruct(H) error 'Input must be a structure'; end % see nift1.h for information on structure sizeof_hdr = int32(348); blob(1:4) = typecast(sizeof_hdr, 'uint8'); blob = setString(blob, 5, 14, H, 'data_type'); blob = setString(blob, 15, 32, H, 'db_name'); blob = setInt32( blob, 33, 36, H, 'extents'); blob = setInt16( blob, 37, 38, H, 'session_error'); blob = setInt8( blob, 39, 39, H, 'regular'); blob = setInt8( blob, 40, 40, H, 'dim_info'); dim = int16(H.dim(:)'); ndim = numel(dim); if ndim<1 || ndim>7 error 'Field "dim" must have 1..7 elements'; end dim = [int16(ndim) dim]; blob(41:(42+2*ndim)) = typecast(dim,'uint8'); blob = setSingle(blob, 57, 60, H, 'intent_p1'); blob = setSingle(blob, 61, 64, H, 'intent_p2'); blob = setSingle(blob, 65, 68, H, 'intent_p3'); blob = setInt16( blob, 69, 70, H, 'intent_code'); blob = setInt16( blob, 71, 72, H, 'datatype'); blob = setInt16( blob, 73, 74, H, 'bitpix'); blob = setInt16( blob, 75, 76, H, 'slice_start'); blob = setSingle(blob, 77, 80, H, 'qfac'); if isfield(H,'pixdim') pixdim = single(H.pixdim(:)'); ndim = numel(pixdim); if ndim<1 || ndim>7 error 'Field "pixdim" must have 1..7 elements'; end blob(81:(80+4*ndim)) = typecast(pixdim,'uint8'); end blob = setSingle(blob, 109, 112, H, 'vox_offset'); blob = setSingle(blob, 113, 116, H, 'scl_scope'); blob = setSingle(blob, 117, 120, H, 'scl_inter'); blob = setInt16( blob, 121, 122, H, 'slice_end'); blob = setInt8( blob, 123, 123, H, 'slice_code'); blob = setInt8( blob, 124, 124, H, 'xyzt_units'); blob = setSingle(blob, 125, 128, H, 'cal_max'); blob = setSingle(blob, 129, 132, H, 'cal_min'); blob = setSingle(blob, 133, 136, H, 'slice_duration'); blob = setSingle(blob, 137, 140, H, 'toffset'); blob = setInt32( blob, 141, 144, H, 'glmax'); blob = setInt32( blob, 145, 148, H, 'glmin'); blob = setString(blob, 149, 228, H, 'descrip'); blob = setString(blob, 229, 252, H, 'aux_file'); blob = setInt16( blob, 253, 254, H, 'qform_code'); blob = setInt16( blob, 255, 256, H, 'sform_code'); blob = setSingle(blob, 257, 260, H, 'quatern_b'); blob = setSingle(blob, 261, 264, H, 'quatern_c'); blob = setSingle(blob, 265, 268, H, 'quatern_d'); blob = setSingle(blob, 269, 272, H, 'quatern_x'); blob = setSingle(blob, 273, 276, H, 'quatern_y'); blob = setSingle(blob, 277, 280, H, 'quatern_z'); blob = setSingle(blob, 281, 296, H, 'srow_x'); blob = setSingle(blob, 297, 312, H, 'srow_y'); blob = setSingle(blob, 313, 328, H, 'srow_z'); blob = setString(blob, 329, 344, H, 'intent_name'); if ~isfield(H,'magic') blob(345:347) = uint8('ni1'); else blob = setString(blob, 345, 347, H, 'magic'); end function blob = setString(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = getfield(H, fieldname); ne = numel(F); mx = endidx - begidx +1; if ne > 0 if ~ischar(F) || ne > mx errmsg = sprintf('Field "data_type" must be a string of maximally %i characters.', mx); error(errmsg); end blob(begidx:(begidx+ne-1)) = uint8(F(:)'); end % set 32-bit integers (check #elements) function blob = setInt32(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = int32(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1) / 4; if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8'); % set 16-bit integers (check #elements) function blob = setInt16(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = int16(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1) / 2; if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+2*ne-1)) = typecast(F(:)', 'uint8'); % just 8-bit integers (check #elements) function blob = setInt8(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = int8(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1); if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+ne-1)) = typecast(F(:)', 'uint8'); % single precision floats function blob = setSingle(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = single(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1) / 4; if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8');
github
philippboehmsturm/antx-master
avw_hdr_read.m
.m
antx-master/freiburgLight/matlab/spm8/external/fieldtrip/fileio/private/avw_hdr_read.m
16,668
utf_8
48271159722bc225bff6496756cf9f5d
function [ avw, machine ] = avw_hdr_read(fileprefix, machine, verbose) % avw_hdr_read - read Analyze format data header (*.hdr) % % [ avw, machine ] = avw_hdr_read(fileprefix, [machine], [verbose]) % % fileprefix - string filename (without .hdr); the file name % can be given as a full path or relative to the % current directory. % % 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. % % avw.hdr - a struct, all fields returned from the header. % For details, find a good description on the web % or see the Analyze File Format pdf in the % mri_toolbox doc folder or read this .m file. % % verbose - the default is to output processing information to the command % window. If verbose = 0, this will not happen. % % This function is called by avw_img_read % % See also avw_hdr_write, avw_hdr_make, avw_view_hdr, avw_view % % $Revision: 2885 $ $Date: 2009/01/14 09:24:45 $ % Licence: GNU GPL, no express or implied warranties % History: 05/2002, [email protected] % The Analyze format and c code below is copyright % (c) Copyright, 1986-1995 % Biomedical Imaging Resource, Mayo Foundation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist('verbose','var'), verbose = 1; end if verbose, version = '[$Revision: 2885 $]'; fprintf('\nAVW_HDR_READ [v%s]\n',version(12:16)); tic; end if ~exist('fileprefix','var'), msg = sprintf('...no input fileprefix - see help avw_hdr_read\n\n'); error(msg); end if ~exist('machine','var'), machine = 'ieee-le'; end if findstr('.hdr',fileprefix), % fprintf('...removing .hdr extension from ''%s''\n',fileprefix); fileprefix = strrep(fileprefix,'.hdr',''); end if findstr('.img',fileprefix), % fprintf('...removing .img extension from ''%s''\n',fileprefix); fileprefix = strrep(fileprefix,'.img',''); end file = sprintf('%s.hdr',fileprefix); if exist(file), if verbose, fprintf('...reading %s Analyze format',machine); end fid = fopen(file,'r',machine); avw.hdr = read_header(fid,verbose); avw.fileprefix = fileprefix; fclose(fid); if ~isequal(avw.hdr.hk.sizeof_hdr,348), if verbose, fprintf('...failed.\n'); end % first try reading the opposite endian to 'machine' switch machine, case 'ieee-le', machine = 'ieee-be'; case 'ieee-be', machine = 'ieee-le'; end if verbose, fprintf('...reading %s Analyze format',machine); end fid = fopen(file,'r',machine); avw.hdr = read_header(fid,verbose); avw.fileprefix = fileprefix; fclose(fid); end if ~isequal(avw.hdr.hk.sizeof_hdr,348), % Now throw an error if verbose, fprintf('...failed.\n'); end msg = sprintf('...size of header not equal to 348 bytes!\n\n'); error(msg); end else msg = sprintf('...cannot find file %s.hdr\n\n',file); error(msg); end if verbose, t=toc; fprintf('...done (%5.2f sec).\n',t); end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ dsr ] = read_header(fid,verbose) % Original header structures - ANALYZE 7.5 %struct dsr % { % struct header_key hk; /* 0 + 40 */ % struct image_dimension dime; /* 40 + 108 */ % struct data_history hist; /* 148 + 200 */ % }; /* total= 348 bytes*/ dsr.hk = header_key(fid); dsr.dime = image_dimension(fid,verbose); dsr.hist = data_history(fid); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [hk] = header_key(fid) % The required elements in the header_key substructure are: % % int sizeof_header Must indicate the byte size of the header file. % int extents Should be 16384, the image file is created as % contiguous with a minimum extent size. % char regular Must be 'r' to indicate that all images and % volumes are the same size. % Original header structures - ANALYZE 7.5 % struct header_key /* header key */ % { /* off + size */ % int sizeof_hdr /* 0 + 4 */ % char data_type[10]; /* 4 + 10 */ % char db_name[18]; /* 14 + 18 */ % int extents; /* 32 + 4 */ % short int session_error; /* 36 + 2 */ % char regular; /* 38 + 1 */ % char hkey_un0; /* 39 + 1 */ % }; /* total=40 bytes */ fseek(fid,0,'bof'); hk.sizeof_hdr = fread(fid, 1,'*int32'); % should be 348! hk.data_type = fread(fid,10,'*char')'; hk.db_name = fread(fid,18,'*char')'; hk.extents = fread(fid, 1,'*int32'); hk.session_error = fread(fid, 1,'*int16'); hk.regular = fread(fid, 1,'*char')'; % might be uint8 hk.hkey_un0 = fread(fid, 1,'*uint8')'; % check if this value was a char zero if hk.hkey_un0 == 48, hk.hkey_un0 = 0; end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ dime ] = image_dimension(fid,verbose) %struct image_dimension % { /* off + size */ % short int dim[8]; /* 0 + 16 */ % /* % 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 % */ % char vox_units[4]; /* 16 + 4 */ % char cal_units[8]; /* 20 + 8 */ % short int unused1; /* 28 + 2 */ % short int datatype; /* 30 + 2 */ % short int bitpix; /* 32 + 2 */ % short int dim_un0; /* 34 + 2 */ % float pixdim[8]; /* 36 + 32 */ % /* % pixdim[] specifies the voxel dimensions: % pixdim[1] - voxel width, mm % pixdim[2] - voxel height, mm % pixdim[3] - slice thickness, mm % pixdim[4] - volume timing, in msec % ..etc % */ % float vox_offset; /* 68 + 4 */ % float roi_scale; /* 72 + 4 */ % float funused1; /* 76 + 4 */ % float funused2; /* 80 + 4 */ % float cal_max; /* 84 + 4 */ % float cal_min; /* 88 + 4 */ % int compressed; /* 92 + 4 */ % int verified; /* 96 + 4 */ % int glmax; /* 100 + 4 */ % int glmin; /* 104 + 4 */ % }; /* total=108 bytes */ dime.dim = fread(fid,8,'*int16')'; dime.vox_units = fread(fid,4,'*char')'; dime.cal_units = fread(fid,8,'*char')'; dime.unused1 = fread(fid,1,'*int16'); dime.datatype = fread(fid,1,'*int16'); dime.bitpix = fread(fid,1,'*int16'); dime.dim_un0 = fread(fid,1,'*int16'); dime.pixdim = fread(fid,8,'*float')'; dime.vox_offset = fread(fid,1,'*float'); dime.roi_scale = fread(fid,1,'*float'); dime.funused1 = fread(fid,1,'*float'); dime.funused2 = fread(fid,1,'*float'); dime.cal_max = fread(fid,1,'*float'); dime.cal_min = fread(fid,1,'*float'); dime.compressed = fread(fid,1,'*int32'); dime.verified = fread(fid,1,'*int32'); dime.glmax = fread(fid,1,'*int32'); dime.glmin = fread(fid,1,'*int32'); if dime.dim(1) < 4, % Number of dimensions in database; usually 4. if verbose, fprintf('...ensuring 4 dimensions in avw.hdr.dime.dim\n'); end dime.dim(1) = int16(4); end if dime.dim(5) < 1, % Time points; number of volumes in database if verbose, fprintf('...ensuring at least 1 volume in avw.hdr.dime.dim(5)\n'); end dime.dim(5) = int16(1); end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ hist ] = data_history(fid) % Original header structures - ANALYZE 7.5 %struct data_history % { /* off + size */ % char descrip[80]; /* 0 + 80 */ % char aux_file[24]; /* 80 + 24 */ % char orient; /* 104 + 1 */ % char originator[10]; /* 105 + 10 */ % char generated[10]; /* 115 + 10 */ % char scannum[10]; /* 125 + 10 */ % char patient_id[10]; /* 135 + 10 */ % char exp_date[10]; /* 145 + 10 */ % char exp_time[10]; /* 155 + 10 */ % char hist_un0[3]; /* 165 + 3 */ % int views /* 168 + 4 */ % int vols_added; /* 172 + 4 */ % int start_field; /* 176 + 4 */ % int field_skip; /* 180 + 4 */ % int omax; /* 184 + 4 */ % int omin; /* 188 + 4 */ % int smax; /* 192 + 4 */ % int smin; /* 196 + 4 */ % }; /* total=200 bytes */ hist.descrip = fread(fid,80,'*char')'; hist.aux_file = fread(fid,24,'*char')'; hist.orient = fread(fid, 1,'*uint8'); % see note below on char hist.originator = fread(fid,10,'*char')'; hist.generated = fread(fid,10,'*char')'; hist.scannum = fread(fid,10,'*char')'; hist.patient_id = fread(fid,10,'*char')'; hist.exp_date = fread(fid,10,'*char')'; hist.exp_time = fread(fid,10,'*char')'; hist.hist_un0 = fread(fid, 3,'*char')'; hist.views = fread(fid, 1,'*int32'); hist.vols_added = fread(fid, 1,'*int32'); hist.start_field = fread(fid, 1,'*int32'); hist.field_skip = fread(fid, 1,'*int32'); hist.omax = fread(fid, 1,'*int32'); hist.omin = fread(fid, 1,'*int32'); hist.smax = fread(fid, 1,'*int32'); hist.smin = fread(fid, 1,'*int32'); % check if hist.orient was saved as ascii char value switch hist.orient, case 48, hist.orient = uint8(0); case 49, hist.orient = uint8(1); case 50, hist.orient = uint8(2); case 51, hist.orient = uint8(3); case 52, hist.orient = uint8(4); case 53, hist.orient = uint8(5); end return % Note on using char: % The 'char orient' field in the header is intended to % hold simply an 8-bit unsigned integer value, not the ASCII representation % of the character for that value. A single 'char' byte is often used to % represent an integer value in Analyze if the known value range doesn't % go beyond 0-255 - saves a byte over a short int, which may not mean % much in today's computing environments, but given that this format % has been around since the early 1980's, saving bytes here and there on % older systems was important! In this case, 'char' simply provides the % byte of storage - not an indicator of the format for what is stored in % this byte. Generally speaking, anytime a single 'char' is used, it is % probably meant to hold an 8-bit integer value, whereas if this has % been dimensioned as an array, then it is intended to hold an ASCII % character string, even if that was only a single character. % Denny <[email protected]> % Comments % The header format is flexible and can be extended for new % user-defined data types. The essential structures of the header % are the header_key and the image_dimension. % % The required elements in the header_key substructure are: % % int sizeof_header Must indicate the byte size of the header file. % int extents Should be 16384, the image file is created as % contiguous with a minimum extent size. % char regular Must be 'r' to indicate that all images and % volumes are the same size. % % The image_dimension substructure describes the organization and % size of the images. These elements enable the database to reference % images by volume and slice number. Explanation of each element follows: % % 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. % dim[5] Undocumented. % dim[6] Undocumented. % dim[7] Undocumented. % % char vox_units[4] Specifies the spatial units of measure for a voxel. % char cal_units[8] Specifies the name of the calibration unit. % short int unused1 /* Unused */ % 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*/ % % short int bitpix; /* Number of bits per pixel; 1, 8, 16, 32, or 64. */ % short int dim_un0; /* Unused */ % % float pixdim[]; Parallel array to dim[], giving real world measurements in mm and ms. % pixdim[0]; Pixel dimensions? % pixdim[1]; Voxel width in mm. % pixdim[2]; Voxel height in mm. % pixdim[3]; Slice thickness in mm. % pixdim[4]; timeslice in ms (ie, TR in fMRI). % pixdim[5]; Undocumented. % pixdim[6]; Undocumented. % pixdim[7]; Undocumented. % % float vox_offset; Byte offset in the .img file at which voxels start. This value can be % negative to specify that the absolute value is applied for every image % in the file. % % float roi_scale; Specifies the Region Of Interest scale? % float funused1; Undocumented. % float funused2; Undocumented. % % float cal_max; Specifies the upper bound of the range of calibration values. % float cal_min; Specifies the lower bound of the range of calibration values. % % int compressed; Undocumented. % int verified; Undocumented. % % int glmax; The maximum pixel value for the entire database. % int glmin; The minimum pixel value for the entire database. % %