plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
lcnbeapp/beapp-master
ft_platform_supports.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/peer/private/ft_platform_supports.m
9,557
utf_8
eb0e55d84d57e6873cce8df6cad90d96
function tf = ft_platform_supports(what,varargin) % FT_PLATFORM_SUPPORTS returns a boolean indicating whether the current platform % supports a specific capability % % Usage: % tf = ft_platform_supports(what) % tf = ft_platform_supports('matlabversion', min_version, max_version) % % The following values are allowed for the 'what' parameter: % value means that the following is supported: % % 'which-all' which(...,'all') % 'exists-in-private-directory' exists(...) will look in the /private % subdirectory to see if a file exists % 'onCleanup' onCleanup(...) % 'alim' alim(...) % 'int32_logical_operations' bitand(a,b) with a, b of type int32 % 'graphics_objects' graphics sysem is object-oriented % 'libmx_c_interface' libmx is supported through mex in the % C-language (recent Matlab versions only % support C++) % 'stats' all statistical functions in % FieldTrip's external/stats directory % 'program_invocation_name' program_invocation_name() (GNU Octave) % 'singleCompThread' start Matlab with -singleCompThread % 'nosplash' -nosplash % 'nodisplay' -nodisplay % 'nojvm' -nojvm % 'no-gui' start GNU Octave with --no-gui % 'RandStream.setGlobalStream' RandStream.setGlobalStream(...) % 'RandStream.setDefaultStream' RandStream.setDefaultStream(...) % 'rng' rng(...) % 'rand-state' rand('state') % 'urlread-timeout' urlread(..., 'Timeout', t) % 'griddata-vector-input' griddata(...,...,...,a,b) with a and b % vectors % 'griddata-v4' griddata(...,...,...,...,...,'v4'), % that is v4 interpolation support % 'uimenu' uimenu(...) if ~ischar(what) error('first argument must be a string'); end switch what case 'matlabversion' tf = is_matlab() && matlabversion(varargin{:}); case 'exists-in-private-directory' tf = is_matlab(); case 'which-all' tf = is_matlab(); case 'onCleanup' tf = is_octave() || matlabversion(7.8, Inf); case 'alim' tf = is_matlab(); case 'int32_logical_operations' % earlier version of Matlab don't support bitand (and similar) % operations on int32 tf = is_octave() || ~matlabversion(-inf, '2012a'); case 'graphics_objects' % introduced in Matlab 2014b, graphics is handled through objects; % previous versions use numeric handles tf = is_matlab() && matlabversion('2014b', Inf); case 'libmx_c_interface' % removed after 2013b tf = matlabversion(-Inf, '2013b'); case 'stats' root_dir=fileparts(which('ft_defaults')); external_stats_dir=fullfile(root_dir,'external','stats'); % these files are only used by other functions in the external/stats % directory exclude_mfiles={'common_size.m',... 'iscomplex.m',... 'lgamma.m'}; tf = has_all_functions_in_dir(external_stats_dir,exclude_mfiles); case 'program_invocation_name' % Octave supports program_invocation_name, which returns the path % of the binary that was run to start Octave tf = is_octave(); case 'singleCompThread' tf = is_matlab() && matlabversion(7.8, inf); case {'nosplash','nodisplay','nojvm'} % Only on Matlab tf = is_matlab(); case 'no-gui' % Only on Octave tf = is_octave(); case 'RandStream.setDefaultStream' tf = is_matlab() && matlabversion('2008b', '2011b'); case 'RandStream.setGlobalStream' tf = is_matlab() && matlabversion('2012a', inf); case 'randomized_PRNG_on_startup' tf = is_octave() || ~matlabversion(-Inf,'7.3'); case 'rng' % recent Matlab versions tf = is_matlab() && matlabversion('7.12',Inf); case 'rand-state' % GNU Octave tf = is_octave(); case 'urlread-timeout' tf = is_matlab() && matlabversion('2012b',Inf); case 'griddata-vector-input' tf = is_matlab(); case 'griddata-v4' tf = is_matlab() && matlabversion('2009a',Inf); case 'uimenu' tf = is_matlab(); otherwise error('unsupported value for first argument: %s', what); end % switch end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_matlab() tf = ~is_octave(); end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_octave() persistent cached_tf; if isempty(cached_tf) cached_tf = logical(exist('OCTAVE_VERSION', 'builtin')); end tf = cached_tf; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = has_all_functions_in_dir(in_dir, exclude_mfiles) % returns true if all functions in in_dir are already provided by the % platform m_files=dir(fullfile(in_dir,'*.m')); n=numel(m_files); for k=1:n m_filename=m_files(k).name; if isempty(which(m_filename)) && ... isempty(strmatch(m_filename,exclude_mfiles)) tf=false; return; end end tf=true; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 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(6, '7.10') % is version between 6 and 7.10? (note: '7.10', not 7.10) % matlabversion(-Inf, 7.6) % is version <= 7.6? % matlabversion('2009b') % exactly 2009b % matlabversion('2008b', '2010a') % between two versions % matlabversion('2008b', Inf) % from a version onwards % etc. % % See also VERSION, VER, VERLESSTHAN % Copyright (C) 2006, Robert Oostenveld % Copyright (C) 2010, Eelke Spaak % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this does not change over subsequent calls, making it persistent speeds it up persistent curVer if nargin<2 max = min; end if isempty(curVer) curVer = version(); end 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 end % function 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 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 % function % 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 % function
github
lcnbeapp/beapp-master
ft_plot_sens.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/ft_plot_sens.m
12,664
utf_8
2fa8bf27fb2d400b192ebf7e24e2a1bb
function hs = ft_plot_sens(sens, varargin) % FT_PLOT_SENS plots the position of all channels or coils that comprise the EEG or % MEG sensor array description % % Use as % ft_plot_sens(sens, ...) % where the first argument is the sensor array as returned by FT_READ_SENS or % by FT_PREPARE_VOL_SENS. % % Optional input arguments should come in key-value pairs and can include % 'chantype' = string or cell-array with strings, for example 'meg' (default = 'all') % 'unit' = string, convert the data to the specified geometrical units (default = []) % 'label' = show the label, can be 'off', 'label', 'number' (default = 'off') % 'coil' = true/false, plot each individual coil (default = false) % 'orientation' = true/false, plot a line for the orientation of each coil (default = false) % % The following option only applies when individual coils are being plotted % 'coilsize' = diameter or edge length of the coils (default is automatic) % 'coilshape' = 'point', 'circle' or 'square' (default is automatic) % 'facecolor' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r', or an Nx1 array where N is the number of faces (default = 'none') % 'edgecolor' = [r g b] values or string, for example 'brain', 'cortex', 'skin', 'black', 'red', 'r' (default = 'k') % 'facealpha' = transparency, between 0 and 1 (default = 1) % 'edgealpha' = transparency, between 0 and 1 (default = 1) % % The following option only applies when individual coils are NOT being plotted % 'style' = plotting style for the points representing the channels, see plot3 (default = 'k.') % % Example % sens = ft_read_sens('Subject01.ds'); % ft_plot_sens(sens, 'style', 'r*') % % See also FT_READ_SENS, FT_DATATYPE_SENS, FT_PLOT_HEADSHAPE, FT_PREPARE_VOL_SENS % Copyright (C) 2009-2016, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ ws = warning('on', 'MATLAB:divideByZero'); % ensure that the sensor description is up-to-date (Aug 2011) sens = ft_datatype_sens(sens); % get the optional input arguments label = ft_getopt(varargin, 'label', 'off'); chantype = ft_getopt(varargin, 'chantype'); unit = ft_getopt(varargin, 'unit'); orientation = ft_getopt(varargin, 'orientation', false); % this is for MEG magnetometer and/or gradiometer arrays coil = ft_getopt(varargin, 'coil', false); coilsize = ft_getopt(varargin, 'coilsize'); % default depends on the input, see below coilshape = ft_getopt(varargin, 'coilshape'); % default depends on the input, see below % this is simply passed to plot3 style = ft_getopt(varargin, 'style', 'k.'); % this is simply passed to ft_plot_mesh edgecolor = ft_getopt(varargin, 'edgecolor', 'k'); facecolor = ft_getopt(varargin, 'facecolor', 'none'); facealpha = ft_getopt(varargin, 'facealpha', 1); edgealpha = ft_getopt(varargin, 'edgealpha', 1); if ischar(chantype) % should be a cell array chantype = {chantype}; end if ~isempty(ft_getopt(varargin, 'coilorientation')) % for backward compatibility, added on 17 Aug 2016 warning('the coilorientation option is deprecated, please use orientation instead') orientation = ft_getopt(varargin, 'coilorientation'); end if ~isempty(ft_getopt(varargin, 'coildiameter')) % for backward compatibility, added on 6 July 2016 % the size is the diameter for a circle, or the edge length for a square warning('the coildiameter option is deprecated, please use coilsize instead') coilsize = ft_getopt(varargin, 'coilsize'); end if ~isempty(unit) % convert the sensor description to the specified units sens = ft_convert_units(sens, unit); end if isempty(coilshape) if ft_senstype(sens, 'neuromag') if strcmp(chantype, 'megmag') coilshape = 'point'; % these cannot be plotted as squares else coilshape = 'square'; end elseif ft_senstype(sens, 'meg') coilshape = 'circle'; else coilshape = 'point'; end end if isempty(coilsize) switch ft_senstype(sens) case 'neuromag306' coilsize = 30; % FIXME this is only an estimate case 'neuromag122' coilsize = 35; % FIXME this is only an estimate case 'ctf151' coilsize = 15; % FIXME this is only an estimate case 'ctf275' coilsize = 15; % FIXME this is only an estimate otherwise coilsize = 10; end % convert from mm to the units of the sensor array coilsize = coilsize/ft_scalingfactor(sens.unit, 'mm'); end % select a subset of channels and coils to be plotted if ~isempty(chantype) % remove the balancing from the sensor definition, e.g. 3rd order gradients, PCA-cleaned data or ICA projections sens = undobalancing(sens); chansel = match_str(sens.chantype, chantype); % remove the channels that are not selected sens.label = sens.label(chansel); sens.chanpos = sens.chanpos(chansel,:); sens.chantype = sens.chantype(chansel); sens.chanunit = sens.chanunit(chansel); if isfield(sens, 'chanori') % this is only present for MEG sensor descriptions sens.chanori = sens.chanori(chansel,:); end % remove the magnetometer and gradiometer coils that are not in one of the selected channels if isfield(sens, 'tra') && isfield(sens, 'coilpos') sens.tra = sens.tra(chansel,:); coilsel = any(sens.tra~=0,1); sens.coilpos = sens.coilpos(coilsel,:); sens.coilori = sens.coilori(coilsel,:); sens.tra = sens.tra(:,coilsel); end % FIXME note that I have not tested this on any complicated electrode definitions % remove the electrodes that are not in one of the selected channels if isfield(sens, 'tra') && isfield(sens, 'elecpos') sens.tra = sens.tra(chansel,:); elecsel = any(sens.tra~=0,1); sens.elecpos = sens.elecpos(elecsel,:); sens.tra = sens.tra(:,elecsel); end end % selecting channels and coils % everything is added to the current figure holdflag = ishold; if ~holdflag hold on end if istrue(orientation) if istrue(coil) if isfield(sens, 'coilori') pos = sens.coilpos; ori = sens.coilori; elseif isfield(sens, 'elecori') pos = sens.elecpos; ori = sens.elecori; else pos = []; ori = []; end else if isfield(sens, 'chanori') pos = sens.chanpos; ori = sens.chanori; else pos = []; ori = []; end end scale = ft_scalingfactor('mm', sens.unit)*20; % draw a line segment of 20 mm for i=1:size(pos,1) x = [pos(i,1) pos(i,1)+ori(i,1)*scale]; y = [pos(i,2) pos(i,2)+ori(i,2)*scale]; z = [pos(i,3) pos(i,3)+ori(i,3)*scale]; line(x, y, z) end end % determine the rotation-around-the-axis of each sensor % only applicable for neuromag planar gradiometers if ft_senstype(sens, 'neuromag') [nchan, ncoil] = size(sens.tra); chandir = nan(nchan,3); for i=1:nchan poscoil = find(sens.tra(i,:)>0); negcoil = find(sens.tra(i,:)<0); if numel(poscoil)==1 && numel(negcoil)==1 % planar gradiometer direction = sens.coilpos(poscoil,:)-sens.coilpos(negcoil,:); direction = direction/norm(direction); chandir(i,:) = direction; elseif (numel([poscoil negcoil]))==1 % magnetometer elseif numel(poscoil)>1 || numel(negcoil)>1 error('cannot work with balanced gradiometer definition') end end end if istrue(coil) % simply get the position of all coils or electrodes if isfield(sens, 'coilpos') pos = sens.coilpos; elseif isfield(sens, 'elecpos') pos = sens.elecpos; end if isfield(sens, 'coilori') ori = sens.coilori; elseif isfield(sens, 'elecori') ori = sens.elecori; else ori = []; end else % determine the position of each channel, which is for example the mean of % two bipolar electrodes, or the bottom coil of a axial gradiometer, or % the center between two coils of a planar gradiometer if isfield(sens, 'chanpos') pos = sens.chanpos; else pos = []; end if isfield(sens, 'chanori') ori = sens.chanori; else ori = []; end end % if istrue(coil) switch coilshape case 'point' hs = plot3(pos(:,1), pos(:,2), pos(:,3), style); case 'circle' plotcoil(pos, ori, [], coilsize, coilshape, 'edgecolor', edgecolor, 'facecolor', facecolor, 'edgealpha', edgealpha, 'facealpha', facealpha); case 'square' plotcoil(pos, ori, chandir, coilsize, coilshape, 'edgecolor', edgecolor, 'facecolor', facecolor, 'edgealpha', edgealpha, 'facealpha', facealpha); otherwise error('incorrect coilshape'); end % switch if ~isempty(label) && ~any(strcmp(label, {'off', 'no'})) for i=1:length(sens.label) switch label case {'on', 'yes'} str = sens.label{i}; case {'label' 'labels'} str = sens.label{i}; case {'number' 'numbers'} str = num2str(i); otherwise error('unsupported value for option ''label'''); end % switch text(sens.chanpos(i,1), sens.chanpos(i,2), sens.chanpos(i,3), str); end % for end % if empty or off/no axis vis3d axis equal if ~nargout clear hs end if ~holdflag hold off end warning(ws); % revert to original state %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION all optional inputs are passed to ft_plot_mesh %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%'%%%%%%%%%%%%%%%%%% function plotcoil(coilpos, coilori, chandir, coilsize, coilshape, varargin) % start with a single template coil at [0 0 0], oriented towards [0 0 1] switch coilshape case 'circle' pos = circle(24); case 'square' pos = square; end ncoil = size(coilpos,1); npos = size(pos,1); mesh.pos = nan(ncoil*npos,3); mesh.poly = nan(ncoil,npos); % determine the scaling of the coil as homogenous transformation matrix s = scale([coilsize coilsize coilsize]); for i=1:ncoil x = coilori(i,1); y = coilori(i,2); z = coilori(i,3); ph = atan2(y, x)*180/pi; th = atan2(sqrt(x^2+y^2), z)*180/pi; % determine the rotation and translation of the coil as homogenous transformation matrix r1 = rotate([0 th 0]); r2 = rotate([0 0 ph]); t = translate(coilpos(i,:)); % determine the initial rotation of the coil as homogenous transformation matrix if isempty(chandir) % none of the coils needs to be rotated around their axis, this applies to circular coils r0 = eye(4); elseif ~all(isfinite(chandir(i,:))) % the rotation around the axis of this coil is not known r0 = nan(4); else % express the direction of sensitivity of the planar channel relative to the orientation of the channel dir = ft_warp_apply(inv(r2*r1), chandir(i,:)); x = dir(1); y = dir(2); % determine the rotation rh = atan2(y, x)*180/pi; r0 = rotate([0 0 rh]); end % construct a single mesh with separate polygons for all coils sel = ((i-1)*npos+1):(i*npos); mesh.pos(sel,:) = ft_warp_apply(t*r2*r1*r0*s, pos); % scale, rotate and translate the template coil vertices, skip the central vertex mesh.poly(i,:) = sel; % this is a polygon connecting all edge points end % plot all polygons together ft_plot_mesh(mesh, varargin{:}); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION return a circle with unit diameter %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [pos] = circle(n) phi = linspace(0, 2*pi, n+1)'; x = cos(phi); y = sin(phi); z = zeros(size(phi)); pos = [x y z]/2; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION return a square with unit edges %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [pos] = square pos = [ 0.5 0.5 0 -0.5 0.5 0 -0.5 -0.5 0 0.5 -0.5 0 0.5 0.5 0 % this closes the square ];
github
lcnbeapp/beapp-master
ft_plot_montage.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/ft_plot_montage.m
6,988
utf_8
4a804759bff8cad4c6b860a900990b77
function ft_plot_montage(dat, varargin) % FT_PLOT_MONTAGE makes a montage of a 3-D array by selecting slices at % regular distances and combining them in one large 2-D image. % % Use as % ft_plot_montage(dat, ...) % where dat is a 3-D array. % % Additional options should be specified in key-value pairs and can be % 'transform' = 4x4 homogeneous transformation matrix specifying the mapping from voxel space to the coordinate system in which the data are plotted. % 'location' = 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' = 1x3 vector specifying the direction orthogonal through the plane which will be plotted (default = [0 0 1]) % 'srange' = % 'slicesize' = % 'nslice' = scalar, number of slices % % See also FT_PLOT_ORTHO, FT_PLOT_SLICE, FT_SOURCEPLOT % undocumented, these are passed on to FT_PLOT_SLICE % 'intersectmesh' = triangulated mesh through which the intersection of the plane will be plotted (e.g. cortical sheet) % 'intersectcolor' = color for the intersection % Copyrights (C) 2012, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ transform = ft_getopt(varargin, 'transform', eye(4)); loc = ft_getopt(varargin, 'location'); ori = ft_getopt(varargin, 'orientation'); srange = ft_getopt(varargin, 'slicerange'); slicesize = ft_getopt(varargin, 'slicesize'); nslice = ft_getopt(varargin, 'nslice'); backgroundcolor = ft_getopt(varargin, 'backgroundcolor', [0 0 0]); % the intersectmesh and intersectcolor options are passed on to FT_PLOT_SLICE dointersect = ~isempty(ft_getopt(varargin, 'intersectmesh')) || ~isempty(ft_getopt(varargin, 'plotmarker')); % set the location if empty if isempty(loc) && (isempty(transform) || all(all(transform-eye(4)==0)==1)) % go to the middle of the volume if the data seem to be in voxel coordinates loc = size(dat)./2; elseif isempty(loc) % otherwise take the origin of the coordinate system loc = [0 0 0]; end % check compatibility of inputs if size(loc, 1) == 1 && isempty(nslice) nslice = 20; elseif size(loc, 1) == 1 && ~isempty(nslice) % this is not a problem, slice spacing will be determined elseif size(loc, 1) > 1 && isempty(nslice) % this is not a problem, number of slices is determined by loc nslice = size(loc, 1); elseif size(loc, 1) > 1 && ~isempty(nslice) if size(loc, 1) ~= nslice error('you should either specify a set of locations or a single location with a number of slices'); end end % set the orientation if empty if isempty(ori), ori = [0 0 1]; end % ensure the ori to have unit norm for k = 1:size(ori,1) ori(k,:) = ori(k,:)./norm(ori(k,:)); end % determine the slice range if size(loc, 1) == 1 && nslice > 1, if isempty(srange) || (ischar(srange) && strcmp(srange, 'auto')) srange = [-50 70]; else end loc = repmat(loc, [nslice 1]) + linspace(srange(1),srange(2),nslice)'*ori; end % ensure that the ori has the same size as the loc if size(ori,1)==1 && size(loc,1)>1, ori = repmat(ori, size(loc,1), 1); end div = [ceil(sqrt(nslice)) ceil(sqrt(nslice))]; optarg = varargin; corners = [inf -inf inf -inf inf -inf]; % get the corners for the axis specification for k = 1:nslice % define 'x' and 'y' axis in projection plane, the definition of x and y is more or less arbitrary [x, y] = projplane(ori(k,:)); % z = ori % get the transformation matrix to project onto the xy-plane T = [x(:) y(:) ori(k,:)' loc(k,:)'; 0 0 0 1]; optarg = ft_setopt(optarg, 'location', loc(k,:)); optarg = ft_setopt(optarg, 'orientation', ori(k,:)); ix = mod(k-1, div(1)); iy = floor((k-1)/div(1)); h(k) = ft_plot_slice(dat, optarg{:}); % FIXME is it safe to pass all optinoal inputs? xtmp = get(h(k), 'xdata'); ytmp = get(h(k), 'ydata'); ztmp = get(h(k), 'zdata'); siz = size(xtmp); if k==1 && isempty(slicesize) slicesize = siz; end % project the positions onto the xy-plane pos = [xtmp(:) ytmp(:) ztmp(:)]; pos = ft_warp_apply(inv(T), pos); xtmp = reshape(pos(:,1), siz); ytmp = reshape(pos(:,2), siz); ztmp = reshape(pos(:,3), siz); % add some offset in the x and y directions to create the montage offset(1) = iy*(slicesize(1)-1); offset(2) = ix*(slicesize(2)-1); % update the specification of the corners of the montage plot if ~isempty(xtmp) c1 = offset(1) + min(xtmp(:)); c2 = offset(1) + max(xtmp(:)); c3 = offset(2) + min(ytmp(:)); c4 = offset(2) + max(ytmp(:)); c5 = min(ztmp(:)); c6 = max(ztmp(:)); end corners = [min(corners(1),c1) max(corners(2),c2) min(corners(3),c3) max(corners(4),c4) min(corners(5),c5) max(corners(6),c6)]; % update the positions set(h(k), 'ydata', offset(1) + xtmp); set(h(k), 'xdata', offset(2) + ytmp); set(h(k), 'zdata', 0 * ztmp); if dointersect, if ~exist('pprevious', 'var'), pprevious = []; end p = setdiff(findobj(gcf, 'type', 'patch'), pprevious); for kk = 1:numel(p) xtmp = get(p(kk), 'xdata'); ytmp = get(p(kk), 'ydata'); ztmp = get(p(kk), 'zdata'); siz2 = size(xtmp); pos = [xtmp(:) ytmp(:) ztmp(:)]; pos = ft_warp_apply(inv(T), pos); xtmp = reshape(pos(:,1), siz2); ytmp = reshape(pos(:,2), siz2); ztmp = reshape(pos(:,3), siz2); % update the positions set(p(kk), 'ydata', offset(1) + xtmp); set(p(kk), 'xdata', offset(2) + ytmp); set(p(kk), 'zdata', 0.0001 * ztmp); end pprevious = [pprevious(:);p(:)]; end % drawnow; %this statement slows down the process big time on some file %systems. I don't know what's going on there, but the statement is not %really necessary, so commented out. end set(gcf, 'color', backgroundcolor); set(gca, 'zlim', [0 1]); %axis equal; axis off; view([0 90]); axis(corners([3 4 1 2])); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [x, y] = projplane(z) [u, s, v] = svd([eye(3) z(:)]); x = u(:, 2)'; y = u(:, 3)';
github
lcnbeapp/beapp-master
ft_select_point.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/ft_select_point.m
3,409
utf_8
dce9dd259e854da9fb1630782705e4ff
function [selected] = ft_select_point(pos, varargin) % FT_SELECT_POINT helper function for selecting a one or multiple points in the % current figure using the mouse. It returns a list of the [x y] coordinates of the % selected points. % % Use as % [selected] = ft_select_point(pos, ...) % % Optional input arguments should come in key-value pairs and can include % 'multiple' = true/false, make multiple selections, pressing "q" on the keyboard finalizes the selection (default = false) % 'nearest' = true/false (default = true) % % Example % pos = randn(10,2); % figure % plot(pos(:,1), pos(:,2), '.') % ft_select_point(pos) % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % get optional input arguments nearest = ft_getopt(varargin, 'nearest', true); multiple = ft_getopt(varargin, 'multiple', false); % ensure that it is boolean nearest = istrue(nearest); multiple = istrue(multiple); if multiple fprintf('select multiple points by clicking in the figure, press "q" if you are done\n'); end x = []; y = []; done = false; selected = zeros(0,3); % ensure that "q" is not the current character, which happens if you reuse the same figure set(gcf, 'CurrentCharacter', 'x') while ~done k = waitforbuttonpress; point = get(gca,'CurrentPoint'); % button down detected key = get(gcf,'CurrentCharacter'); % which key was pressed (if any)? if strcmp(key, 'q') % we are done with the clicking done = true; else % add the current point x(end+1) = point(1,1); y(end+1) = point(1,2); end if ~multiple done = true; end end if nearest && ~isempty(pos) % determine the points that are the nearest to the displayed points selected = []; % compute the distance between the points to get an estimate of the tolerance dp = dist(pos'); dp = triu(dp, 1); dp = dp(:); dp = dp(dp>0); % allow for some tolerance in the clicking dp = median(dp); tolerance = 0.3*dp; for i=1:length(x) % compute the distance between the clicked position and all points dx = pos(:,1) - x(i); dy = pos(:,2) - y(i); dd = sqrt(dx.^2 + dy.^2); [d, i] = min(dd); if d<tolerance selected(end+1,:) = pos(i,:); end end else selected = [x(:) y(:)]; end % if nearest %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This function serves as a replacement for the dist function in the Neural % Networks toolbox. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [d] = dist(x) n = size(x,2); d = zeros(n,n); for i=1:n for j=(i+1):n d(i,j) = sqrt(sum((x(:,i)-x(:,j)).^2)); d(j,i) = d(i,j); end end
github
lcnbeapp/beapp-master
ft_plot_slice.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/ft_plot_slice.m
15,682
utf_8
f036338d1094cbb7ff4a6ba748e8d3db
function [h, T2] = ft_plot_slice(dat, varargin) % FT_PLOT_SLICE cuts a 2-D slice from a 3-D volume and interpolates if needed % % Use as % ft_plot_slice(dat, ...) % ft_plot_slice(dat, mask, ...) % where dat and mask are equal-sized 3-D arrays. % % Additional options should be specified in key-value pairs and can be % 'transform' = 4x4 homogeneous transformation matrix specifying the mapping from % voxel coordinates to the coordinate system in which the data are plotted. % 'location' = 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' = 1x3 vector specifying the direction orthogonal through the plane % which will be plotted (default = [0 0 1]) % 'unit' = string, can be 'm', 'cm' or 'mm (default is automatic) % 'resolution' = number (default = 1 mm) % 'datmask' = 3D-matrix with the same size as the data matrix, serving as opacitymap % If the second input argument to the function contains a matrix, this % will be used as the mask % 'opacitylim' = 1x2 vector specifying the limits for opacity masking % 'interpmethod' = string specifying the method for the interpolation, see INTERPN (default = 'nearest') % 'style' = string, 'flat' or '3D' % 'colormap' = string, see COLORMAP % 'clim' = 1x2 vector specifying the min and max for the colorscale % % See also FT_PLOT_ORTHO, FT_PLOT_MONTAGE, FT_SOURCEPLOT % undocumented % 'intersectmesh' = triangulated mesh through which the intersection of the plane will be plotted (e.g. cortical sheet) % 'intersectcolor' = color for the intersection % 'plotmarker' = Nx3 matrix with points to be plotted as markers, e.g. dipole positions % Copyrights (C) 2010-2014, Jan-Mathijs Schoffelen % Copyrights (C) 2014, Robert Oostenveld and Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ persistent dim X Y Z if isequal(dim, size(dat)) % reuse the persistent variables to speed up subsequent calls with the same input else dim = size(dat); [X, Y, Z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3)); end % parse first input argument(s). it is either % (dat, varargin) % (dat, msk, varargin) % (dat, [], varargin) if numel(varargin)>0 && (isempty(varargin{1}) || isnumeric(varargin{1}) || islogical(varargin{1})) msk = varargin{1}; varargin = varargin(2:end); end % get the optional input arguments transform = ft_getopt(varargin, 'transform', eye(4)); loc = ft_getopt(varargin, 'location'); ori = ft_getopt(varargin, 'orientation', [0 0 1]); unit = ft_getopt(varargin, 'unit'); % the default will be determined further down resolution = ft_getopt(varargin, 'resolution'); % the default depends on the units and will be determined further down mask = ft_getopt(varargin, 'datmask'); opacitylim = ft_getopt(varargin, 'opacitylim'); interpmethod = ft_getopt(varargin, 'interpmethod', 'nearest'); cmap = ft_getopt(varargin, 'colormap'); clim = ft_getopt(varargin, 'clim'); doscale = ft_getopt(varargin, 'doscale', true); % only scale when necessary (time consuming), i.e. when plotting as grayscale image & when the values are not between 0 and 1 h = ft_getopt(varargin, 'surfhandle', []); mesh = ft_getopt(varargin, 'intersectmesh'); intersectcolor = ft_getopt(varargin, 'intersectcolor', 'yrgbmyrgbm'); intersectlinewidth = ft_getopt(varargin, 'intersectlinewidth', 2); intersectlinestyle = ft_getopt(varargin, 'intersectlinestyle'); plotmarker = ft_getopt(varargin, 'plotmarker'); markersize = ft_getopt(varargin, 'markersize', 'auto'); markercolor = ft_getopt(varargin, 'markercolor', 'w'); % convert from yes/no/true/false/0/1 into a proper boolean doscale = istrue(doscale); if ~isa(dat, 'double') dat = cast(dat, 'double'); end if exist('msk', 'var') && isempty(mask) ft_warning('using the second input argument as mask rather than the one from the varargin list'); mask = msk; clear msk; end % normalise the orientation vector to one ori = ori./sqrt(sum(ori.^2)); % set the default location if isempty(loc) && (isempty(transform) || isequal(transform, eye(4))) loc = (dim+1)./2; elseif isempty(loc) loc = [0 0 0]; end % shift the location to be along the orientation vector loc = ori*dot(loc,ori); % it should be a cell-array if isstruct(mesh) tmp = mesh; mesh = cell(size(tmp)); for i=1:numel(tmp) mesh{i} = tmp(i); end elseif iscell(mesh) % do nothing else mesh = {}; end % replace pnt by pos for k = 1:numel(mesh) mesh{k} = fixpos(mesh{k}); end dointersect = ~isempty(mesh); if dointersect for k = 1:numel(mesh) if ~isfield(mesh{k}, 'pos') || ~isfield(mesh{k}, 'tri') % error('the mesh should be a structure with pos and tri'); mesh{k}.pos = []; mesh{k}.tri = []; end end end % check whether the mask is ok domask = ~isempty(mask); if domask if ~isequal(size(dat), size(mask)) error('the mask data should have the same dimensions as the functional data'); end end % determine the voxel center % voxel_center_vc = [X(:) Y(:) Z(:)]; % voxel_center_hc = ft_warp_apply(transform, voxel_center_vc); % determine the edges, i.e. the corner points of each voxel % [Xe, Ye, Ze] = ndgrid(0:dim(1), 0:dim(2), 0:dim(3)); % Xe = Xe+0.5; % Ye = Ye+0.5; % Ze = Ze+0.5; % voxel_edge_vc = [Xe(:) Ye(:) Ze(:)]; % voxel_edge_hc = ft_warp_apply(transform, voxel_edge_vc); % determine the corner points of the box encompassing the whole data block % extend the box with half a voxel in all directions to get the outer edge corner_vc = [ 0.5 0.5 0.5 0.5+dim(1) 0.5 0.5 0.5+dim(1) 0.5+dim(2) 0.5 0.5 0.5+dim(2) 0.5 0.5 0.5 0.5+dim(3) 0.5+dim(1) 0.5 0.5+dim(3) 0.5+dim(1) 0.5+dim(2) 0.5+dim(3) 0.5 0.5+dim(2) 0.5+dim(3) ]; corner_hc = ft_warp_apply(transform, corner_vc); if isempty(unit) if ~isequal(transform, eye(4)) % estimate the geometrical units we are dealing with unit = ft_estimate_units(norm(range(corner_hc))); else % units are in voxels, these are assumed to be close to mm unit = 'mm'; end end if isempty(resolution) % the default resolution is 1 mm resolution = ft_scalingfactor('mm', unit); end % determine whether interpolation is needed dointerp = false; dointerp = dointerp || sum(sum(transform-eye(4)))~=0; dointerp = dointerp || ~all(round(loc)==loc); dointerp = dointerp || sum(ori)~=1; dointerp = dointerp || ~(resolution==round(resolution)); % 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 && numel(st)>1 && strcmp(st(2).name, 'ft_plot_montage'), dointerp = true; end % define 'x' and 'y' axis in projection plane, the definition of x and y is more or less arbitrary [x, y] = projplane(ori); % z = ori; % project the corner points onto the projection plane corner_pc = zeros(size(corner_hc)); for i=1:8 corner = corner_hc(i, :) - loc(:)'; corner_pc(i,1) = dot(corner, x); corner_pc(i,2) = dot(corner, y); corner_pc(i,3) = 0; end % get the transformation matrix from the projection plane to head coordinates T2 = [x(:) y(:) ori(:) loc(:); 0 0 0 1]; % get the transformation matrix from projection plane to voxel coordinates T3 = transform\T2; min_corner_pc = min(corner_pc, [], 1); max_corner_pc = max(corner_pc, [], 1); % round the bounding box limits to the nearest mm switch unit case 'm' min_corner_pc = ceil(min_corner_pc*100)/100; max_corner_pc = floor(max_corner_pc*100)/100; case 'cm' min_corner_pc = ceil(min_corner_pc*10)/10; max_corner_pc = floor(max_corner_pc*10)/10; case 'mm' min_corner_pc = ceil(min_corner_pc); max_corner_pc = floor(max_corner_pc); end % determine a grid of points in the projection plane xplane = min_corner_pc(1):resolution:max_corner_pc(1); yplane = min_corner_pc(2):resolution:max_corner_pc(2); zplane = 0; [Xi, Yi, Zi] = ndgrid(xplane, yplane, zplane); siz = size(squeeze(Xi)); interp_center_pc = [Xi(:) Yi(:) Zi(:)]; % interp_center_hc = ft_warp_apply(T2, interp_center_pc); % get the positions of the points in the projection plane in voxel coordinates interp_center_vc = ft_warp_apply(T3, interp_center_pc); Xi = reshape(interp_center_vc(:, 1), siz); Yi = reshape(interp_center_vc(:, 2), siz); Zi = reshape(interp_center_vc(:, 3), siz); if isequal(transform, eye(4)) && isequal(interpmethod, 'nearest') && all(isinteger(Xi(:))) && all(isinteger(Yi(:))) && all(isinteger(Zi(:))) % simply look up the values V = dat(sub2ind(dim, Xi(:), Yi(:), Zi(:))); V = reshape(V, siz); else V = interpn(X, Y, Z, dat, Xi, Yi, Zi, interpmethod); end if all(isnan(V(:))) % the projection plane lies completely outside the box spanned by the data else % trim the edges of the projection plane [sel1, sel2] = tight(V); V = V (sel1,sel2); Xi = Xi(sel1,sel2); Yi = Yi(sel1,sel2); Zi = Zi(sel1,sel2); end if domask, Vmask = interpn(X, Y, Z, mask, Xi, Yi, Zi, interpmethod); end interp_center_vc = [Xi(:) Yi(:) Zi(:)]; clear Xi Yi Zi interp_center_pc = ft_warp_apply(inv(T3), interp_center_vc); % determine a grid of points in the projection plane % this reconstruction is needed since the edges may have been trimmed off xplane = min(interp_center_pc(:, 1)):resolution:max(interp_center_pc(:, 1)); yplane = min(interp_center_pc(:, 2)):resolution:max(interp_center_pc(:, 2)); zplane = 0; [Xi, Yi, Zi] = ndgrid(xplane, yplane, zplane); % 2D cartesian grid of projection plane in plane voxels siz = size(squeeze(Xi)); % extend with one voxel along dim 1 Xi = cat(1, Xi, Xi(end,:)+mean(diff(Xi,[],1),1)); Yi = cat(1, Yi, Yi(end,:)+mean(diff(Yi,[],1),1)); Zi = cat(1, Zi, Zi(end,:)+mean(diff(Zi,[],1),1)); % extend with one voxel along dim 2 Xi = cat(2, Xi, Xi(:,end)+mean(diff(Xi,[],2),2)); Yi = cat(2, Yi, Yi(:,end)+mean(diff(Yi,[],2),2)); Zi = cat(2, Zi, Zi(:,end)+mean(diff(Zi,[],2),2)); % shift with half a voxel along dim 1 and 2 Xi = Xi-0.5*resolution; Yi = Yi-0.5*resolution; % Zi = Zi; % do not shift along this direction interp_edge_pc = [Xi(:) Yi(:) Zi(:)]; clear Xi Yi Zi interp_edge_hc = ft_warp_apply(T2, interp_edge_pc); if false % plot all objects in head coordinates ft_plot_mesh(voxel_center_hc, 'vertexmarker', 'o') ft_plot_mesh(voxel_edge_hc, 'vertexmarker', '+') ft_plot_mesh(corner_hc, 'vertexmarker', '*') ft_plot_mesh(interp_center_hc, 'vertexmarker', 'o', 'vertexcolor', 'r') ft_plot_mesh(interp_edge_hc, 'vertexmarker', '+', 'vertexcolor', 'r') axis on grid on xlabel('x') ylabel('y') zlabel('z') end if isempty(cmap), % treat as gray value: scale and convert to rgb if doscale dmin = min(dat(:)); dmax = max(dat(:)); V = (V-dmin)./(dmax-dmin); clear dmin dmax end V(isnan(V)) = 0; % deal with clim for RGB data here, where the purpose is to increase the % contrast range, rather than shift the average grey value if ~isempty(clim) V = (V-clim(1))./clim(2); V(V>1)=1; end % convert into RGB values, e.g. for the plotting of anatomy V = cat(3, V, V, V); end % get positions of the voxels in the interpolation plane in head coordinates Xh = reshape(interp_edge_hc(:,1), siz+1); Yh = reshape(interp_edge_hc(:,2), siz+1); Zh = reshape(interp_edge_hc(:,3), siz+1); if isempty(h), % create surface object h = surface(Xh, Yh, Zh, V); set(h, 'linestyle', 'none'); else % update the colordata in the surface object set(h, 'Cdata', V); set(h, 'Xdata', Xh); set(h, 'Ydata', Yh); set(h, 'Zdata', Zh); end if domask, if islogical(Vmask), Vmask = double(Vmask); end set(h, 'FaceColor', 'texture'); set(h, 'FaceAlpha', 'texturemap'); %flat set(h, 'AlphaDataMapping', 'scaled'); set(h, 'AlphaData', Vmask); if ~isempty(opacitylim) alim(opacitylim) end end if dointersect % determine three points on the plane inplane = eye(3) - (eye(3) * ori') * ori; v1 = loc + inplane(1,:); v2 = loc + inplane(2,:); v3 = loc + inplane(3,:); for k = 1:numel(mesh) [xmesh, ymesh, zmesh] = intersect_plane(mesh{k}.pos, mesh{k}.tri, v1, v2, v3); % draw each individual line segment of the intersection if ~isempty(xmesh), p = patch(xmesh', ymesh', zmesh', nan(1, size(xmesh,1))); if ~isempty(intersectcolor), set(p, 'EdgeColor', intersectcolor(k)); end if ~isempty(intersectlinewidth), set(p, 'LineWidth', intersectlinewidth); end if ~isempty(intersectlinestyle), set(p, 'LineStyle', intersectlinestyle); end end end end if ~isempty(cmap) colormap(cmap); if ~isempty(clim) caxis(clim); end end if ~isempty(plotmarker) % determine three points on the plane inplane = eye(3) - (eye(3) * ori') * ori; v1 = loc + inplane(1,:); v2 = loc + inplane(2,:); v3 = loc + inplane(3,:); pr = nan(size(plotmarker,1), 3); d = nan(size(plotmarker,1), 1); for k = 1:size(plotmarker,1) [pr(k,:), d(k,:)] = ptriprojn(v1, v2, v3, plotmarker(k,:)); end sel = d<eps*1e8; if sum(sel)>0 ft_plot_dipole(pr(sel,:), repmat([0;0;1], 1, size(pr,1)), 'length', 0, 'color', markercolor, 'diameter', markersize); end end % update the axes to ensure that the whole volume fits ax = [min(corner_hc) max(corner_hc)]; axis(ax([1 4 2 5 3 6])); % reorder into [xmin xmax ymin ymaz zmin zmax] st = dbstack; if numel(st)>1 % ft_plot_slice has been called from another function % assume the remainder of the axis settings to be handled there else set(gca,'xlim',[min(Xh(:))-0.5*resolution max(Xh(:))+0.5*resolution]); set(gca,'ylim',[min(Yh(:))-0.5*resolution max(Yh(:))+0.5*resolution]); set(gca,'zlim',[min(Zh(:))-0.5*resolution max(Zh(:))+0.5*resolution]); set(gca,'dataaspectratio',[1 1 1]); % axis equal; % this for some reason does not work robustly when drawing intersections, replaced by the above axis vis3d end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [x, y] = projplane(z) [u, s, v] = svd([eye(3) z(:)]); x = u(:, 2)'; y = u(:, 3)'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [sel1, sel2] = tight(V) % make a selection to cut off the nans at the edges sel1 = sum(~isfinite(V), 2)<size(V, 2); sel2 = sum(~isfinite(V), 1)<size(V, 1);
github
lcnbeapp/beapp-master
ft_select_range.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/ft_select_range.m
14,189
utf_8
302ad7dece8f9e09963ca038ce060824
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. % % The callback function (and it's arguments) specified in callback is called % on a left-click inside a selection, or using the right-click context-menu. % The callback function will have as its first-to-last input argument the range of % all selections. The last input argument is either empty, or, when using the context % menu, a label of the item clicked. % Context menus are shown as the labels presented in the input. When activated, % the callback function is called, with the last input argument being the label of % the selection option. % % Input arguments: % 'event' = string, event used as hook. % 'callback' = function handle or cell-array containing function handle and additional input arguments % 'contextmenu' = cell-array containing labels shown in right-click menu % 'multiple' = boolean, allowing multiple selection boxes or not % 'xrange' = boolean, xrange variable or not % 'yrange' = boolean, yrange variable or not % 'clear' = boolean % % Example % x = randn(10,1); % y = randn(10,1); % figure; plot(x, y, '.'); % % The following example allows multiple horizontal and vertical selections to be made % set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'event', 'WindowButtonDownFcn', 'multiple', true, 'callback', @disp}); % set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'event', 'WindowButtonMotionFcn', 'multiple', true, 'callback', @disp}); % set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'event', 'WindowButtonUpFcn', 'multiple', true, 'callback', @disp}); % % The following example allows a single horizontal selection to be made % set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'event', 'WindowButtonDownFcn', 'multiple', false, 'xrange', true, 'yrange', false, 'callback', @disp}); % set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'event', 'WindowButtonMotionFcn', 'multiple', false, 'xrange', true, 'yrange', false, 'callback', @disp}); % set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'event', 'WindowButtonUpFcn', 'multiple', false, 'xrange', true, 'yrange', false, 'callback', @disp}); % % The following example allows a single point to be selected % set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'event', 'WindowButtonDownFcn', 'multiple', false, 'xrange', false, 'yrange', false, 'callback', @disp}); % set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'event', 'WindowButtonMotionFcn', 'multiple', false, 'xrange', false, 'yrange', false, 'callback', @disp}); % set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'event', 'WindowButtonUpFcn', 'multiple', false, 'xrange', false, 'yrange', false, 'callback', @disp}); % Copyright (C) 2009-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % get the optional arguments event = ft_getopt(varargin, 'event'); callback = ft_getopt(varargin, 'callback'); multiple = ft_getopt(varargin, 'multiple', false); xrange = ft_getopt(varargin, 'xrange', true); yrange = ft_getopt(varargin, 'yrange', true); clear = ft_getopt(varargin, 'clear', false); contextmenu = ft_getopt(varargin, 'contextmenu'); % 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); clear = istrue(clear); % get the figure handle, dependent on MATLAB version if ft_platform_supports('graphics_objects') while ~isa(handle, 'matlab.ui.Figure') handle = p; p = get(handle, 'parent'); end else p = handle; while ~isequal(p, 0) handle = p; p = get(handle, 'parent'); end 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 % setup contextmenu if ~isempty(contextmenu) if isempty(get(handle,'uicontextmenu')) hcmenu = uicontextmenu; hcmenuopt = nan(1,numel(contextmenu)); for icmenu = 1:numel(contextmenu) hcmenuopt(icmenu) = uimenu(hcmenu, 'label', contextmenu{icmenu}, 'callback', {@evalcontextcallback, callback{:}, []}); % empty matrix is placeholder, will be updated to userdata.range end end if ~exist('hcmenuopt','var') hcmenuopt = get(get(handle,'uicontextmenu'),'children'); % uimenu handles, used for switchen on/off and updating end % setting associations for all clickable objects % this out to be pretty fast, if this is still to slow in some cases, the code below has to be reused if ~exist('hcmenu','var') hcmenu = get(handle,'uicontextmenu'); end set(findobj(handle,'hittest','on'), 'uicontextmenu',hcmenu); % to be used if above is too slow % associations only done once. this might be an issue in some cases, cause when a redraw is performed in the original figure (e.g. databrowser), a specific assocations are lost (lines/patches/text) % set(get(handle,'children'),'uicontextmenu',hcmenu); % set(findobj(handle,'type','text'), 'uicontextmenu',hcmenu); % set(findobj(handle,'type','patch'),'uicontextmenu',hcmenu); % set(findobj(handle,'type','line'), 'uicontextmenu',hcmenu); % fixme: add other often used object types that ft_select_range is called upon end % get last-used-mouse-button lastmousebttn = get(gcf,'selectiontype'); switch lower(event) case lower('WindowButtonDownFcn') switch lastmousebttn case 'normal' % left click 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'); if ~isempty(contextmenu) && ~pointonly set(hcmenuopt,'enable','off') end 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 end case lower('WindowButtonUpFcn') switch lastmousebttn case 'normal' % left click 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 % update contextmenu callbacks if ~isempty(contextmenu) updateContextCallback(hcmenuopt, callback, userData.range) 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 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'); if ~isempty(contextmenu) set(hcmenuopt,'enable','on') end else set(handle, 'Pointer', 'crosshair'); if ~isempty(contextmenu) set(hcmenuopt,'enable','off') end 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) % no context menu item was clicked, set to empty cmenulab = []; if ~isempty(callback) if isa(callback, 'cell') % the callback specifies a function and additional arguments funhandle = callback{1}; funargs = callback(2:end); feval(funhandle, funargs{:}, val, cmenulab); else % the callback only specifies a function funhandle = callback; feval(funhandle, val); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function updateContextCallback(hcmenuopt, callback, val) if ~isempty(callback) if isa(callback, 'cell') % the callback specifies a function and additional arguments funhandle = callback{1}; funargs = callback(2:end); callback = {funhandle, funargs{:}, val}; else % the callback only specifies a function funhandle = callback; callback = {funhandle, val}; end for icmenu = 1:numel(hcmenuopt) set(hcmenuopt(icmenu),'callback',{@evalcontextcallback, callback{:}}) end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function evalcontextcallback(hcmenuopt, eventdata, varargin) % delete selection box if present % get parent (uimenu -> uicontextmenu -> parent) parent = get(get(hcmenuopt,'parent'),'parent'); % fixme: isn't the parent handle always input provided in the callback? userData = getappdata(parent, 'select_range_m'); if ishandle(userData.box) if any(~isnan([get(userData.box,'ydata') get(userData.box,'xdata')])) delete(userData.box(ishandle(userData.box))); userData.range = []; userData.box = []; set(parent, 'Pointer', 'crosshair'); setappdata(parent, 'select_range_m', userData); end end % get contextmenu name cmenulab = get(hcmenuopt,'label'); if numel(varargin)>1 % the callback specifies a function and additional arguments funhandle = varargin{1}; funargs = varargin(2:end); feval(funhandle, funargs{:}, cmenulab); else % the callback only specifies a function funhandle = varargin{1}; feval(funhandle, val, cmenulab); end
github
lcnbeapp/beapp-master
ft_plot_axes.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/ft_plot_axes.m
5,531
utf_8
2d76425ace6d8a6d80c3d90c26650c78
function ft_plot_axes(object, varargin) % FT_PLOT_AXES adds three axes of 150 mm and a 10 mm sphere at the origin to the % present 3-D figure. The axes and sphere are scaled according to the units of the % geometrical object that is passed to this function. Furthermore, when possible, % the axes labels will represent the aanatomical labels corresponding to the % specified coordinate system. % % Use as % ft_plot_axes(object) % % Additional optional input arguments should be specified as key-value pairs % and can include % axisscale = scaling factor for the reference axes and sphere (default = 1) % fontcolor = string (default = 'y') % % See also FT_PLOT_SENS, FT_PLOT_MESH, FT_PLOT_ORTHO, FT_PLOT_HEADSHAPE, FT_PLOT_DIPOLE, FT_PLOT_VOL % Copyright (C) 2015, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ axisscale = ft_getopt(varargin, 'axisscale', 1); % this is used to scale the axmax and rbol fontcolor = ft_getopt(varargin, 'fontcolor', 'y'); % default is yellow if isfield(object, 'unit') unit = object.unit; else warning('units are not known, not plotting axes') return end if isfield(object, 'coordsys') coordsys = object.coordsys; else % this is not a problem per see coordsys = 'unknown'; end axmax = 150 * ft_scalingfactor('mm', unit); rbol = 5 * ft_scalingfactor('mm', unit); % this is useful if the anatomy is from a non-human primate or rodent axmax = axisscale*axmax; rbol = axisscale*rbol; fprintf('The axes are %g %s long in each direction\n', axmax, unit); fprintf('The diameter of the sphere at the origin is %g %s\n', 2*rbol, unit); % get the xyz-axes xdat = [-axmax 0 0; axmax 0 0]; ydat = [0 -axmax 0; 0 axmax 0]; zdat = [0 0 -axmax; 0 0 axmax]; % get the xyz-axes dotted xdatdot = (-axmax:(axmax/15):axmax); xdatdot = xdatdot(1:floor(numel(xdatdot)/2)*2); xdatdot = reshape(xdatdot, [2 numel(xdatdot)/2]); n = size(xdatdot,2); ydatdot = [zeros(2,n) xdatdot zeros(2,n)]; zdatdot = [zeros(2,2*n) xdatdot]; xdatdot = [xdatdot zeros(2,2*n)]; prevhold = ishold; hold on % plot axes hl = line(xdat, ydat, zdat); set(hl(1), 'linewidth', 1, 'color', 'r'); set(hl(2), 'linewidth', 1, 'color', 'g'); set(hl(3), 'linewidth', 1, 'color', 'b'); hld = line(xdatdot, ydatdot, zdatdot); for k = 1:n set(hld(k ), 'linewidth', 3, 'color', 'r'); set(hld(k+n*1), 'linewidth', 3, 'color', 'g'); set(hld(k+n*2), 'linewidth', 3, 'color', 'b'); end % create the ball at the origin [O.pos, O.tri] = icosahedron42; O.pos = O.pos.*rbol; ft_plot_mesh(O, 'edgecolor', 'none'); % create the labels that are to be plotted along the axes [labelx, labely, labelz] = xyz2label(coordsys); % add the labels to the axis text(xdat(1,1), ydat(1,1), zdat(1,1), labelx{1}, 'color', fontcolor, 'fontsize', 15, 'linewidth', 2); text(xdat(1,2), ydat(1,2), zdat(1,2), labely{1}, 'color', fontcolor, 'fontsize', 15, 'linewidth', 2); text(xdat(1,3), ydat(1,3), zdat(1,3), labelz{1}, 'color', fontcolor, 'fontsize', 15, 'linewidth', 2); text(xdat(2,1), ydat(2,1), zdat(2,1), labelx{2}, 'color', fontcolor, 'fontsize', 15, 'linewidth', 2); text(xdat(2,2), ydat(2,2), zdat(2,2), labely{2}, 'color', fontcolor, 'fontsize', 15, 'linewidth', 2); text(xdat(2,3), ydat(2,3), zdat(2,3), labelz{2}, 'color', fontcolor, 'fontsize', 15, 'linewidth', 2); if ~prevhold hold off end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % % NOTE this should be kept consistent with the longer axes labels in FT_DETERMINE_COORDSYS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [labelx, labely, labelz] = xyz2label(str) if ~isempty(str) && ~strcmp(str, 'unknown') % the first part is important for the orientations % the second part optionally contains information on the origin strx = tokenize(str, '_'); switch lower(strx{1}) case {'ras' 'itab' 'neuromag' 'spm' 'mni' 'tal'} labelx = {'-X (left)' '+X (right)' }; labely = {'-Y (posterior)' '+Y (anterior)'}; labelz = {'-Z (inferior)' '+Z (superior)'}; case {'als' 'ctf' '4d', 'bti'} labelx = {'-X (posterior)' '+X (anterior)'}; labely = {'-Y (right)' '+Y (left)'}; labelz = {'-Z (inferior)' '+Z (superior)'}; case {'paxinos'} labelx = {'-X (left)' '+X (right)'}; labely = {'-Y (inferior)' '+Y (superior)'}; labelz = {'-Z (anterior)' '+Z (posterior)'}; case {'lps'} labelx = {'-X (right)' '+X (left)'}; labely = {'-Y (anterior)' '+Y (posterior)'}; labelz = {'-Z (inferior)' '+Z (superior)'}; otherwise error('unknown coordsys'); end else labelx = {'-X (unknown)' '+X (unknown)'}; labely = {'-Y (unknown)' '+Y (unknown)'}; labelz = {'-Z (unknown)' '+Z (unknown)'}; end
github
lcnbeapp/beapp-master
ft_select_channel.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/ft_select_channel.m
5,700
utf_8
ba3d1a96f9f4cecda939faa6f1298b81
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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % get optional input arguments multiple = ft_getopt(varargin, 'multiple', false); callback = ft_getopt(varargin, 'callback'); if istrue(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(callback,range,cmenulab) % last input is context menu label, see ft_select_range 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
lcnbeapp/beapp-master
ft_datatype_sens.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/private/ft_datatype_sens.m
22,743
utf_8
fab01996ef9a98c643827fb2767fbaf3
function [sens] = ft_datatype_sens(sens, varargin) % FT_DATATYPE_SENS describes the FieldTrip structure that represents an EEG, ECoG, or % MEG sensor array. This structure is commonly called "elec" for EEG, "grad" for MEG, % "opto" for NIRS, or general "sens" for either one. % % For all sensor types a distinction should be made between the channel (i.e. the % output of the transducer that is A/D converted) and the sensor, which may have some % spatial extent. E.g. with EEG you can have a bipolar channel, where the position of % the channel can be represented as in between the position of the two electrodes. % % The structure for MEG gradiometers and/or magnetometers contains % sens.label = Mx1 cell-array with channel labels % sens.chanpos = Mx3 matrix with channel positions % sens.chanori = Mx3 matrix with channel orientations, used for synthetic planar gradient computation % sens.tra = MxN matrix to combine coils into channels % sens.coilpos = Nx3 matrix with coil positions % sens.coilori = Nx3 matrix with coil orientations % sens.balance = structure containing info about the balancing, See FT_APPLY_MONTAGE % and optionally % sens.chanposold = Mx3 matrix with original channel positions (in case % sens.chanpos has been updated to contain NaNs, e.g. % after ft_componentanalysis) % sens.chanoriold = Mx3 matrix with original channel orientations % sens.labelold = Mx1 cell-array with original channel labels % % The structure for EEG or ECoG channels contains % sens.label = Mx1 cell-array with channel labels % sens.elecpos = Nx3 matrix with electrode positions % sens.chanpos = Mx3 matrix with channel positions (often the same as electrode positions) % sens.tra = MxN matrix to combine electrodes into channels % In case sens.tra is not present in the EEG sensor array, the channels % are assumed to be average referenced. % % The structure for NIRS channels contains % sens.optopos = contains information about the position of the optodes % sens.optotype = contains information about the type of optode (receiver or transmitter) % sens.chanpos = contains information about the position of the channels (i.e. average of optopos) % sens.tra = NxC matrix, boolean, contains information about how receiver and transmitter form channels % sens.wavelength = 1xM vector of all wavelengths that were used % sens.transmits = NxM matrix, boolean, where N is the number of optodes and M the number of wavelengths per transmitter. Specifies what optode is transmitting at what wavelength (or nothing at all, which indicates that it is a receiver) % sens.laserstrength = 1xM vector of the strength of the emitted light of the lasers % % The following fields apply to MEG and EEG % sens.chantype = Mx1 cell-array with the type of the channel, see FT_CHANTYPE % sens.chanunit = Mx1 cell-array with the units of the channel signal, e.g. 'V', 'fT' or 'T/cm', see FT_CHANUNIT % % The following fields are optional % sens.type = string with the type of acquisition system, see FT_SENSTYPE % sens.fid = structure with fiducial information % % Historical fields: % pnt, pos, ori, pnt1, pnt2 % % Revision history: % (2016/latest) The chantype and chanunit have become required fields. % Original channel details are specified with the suffix "old" rather than "org". % All numeric values are represented in double precision. % It is possible to convert the amplitude and distance units (e.g. from T to fT and % from m to mm) and it is possible to express planar and axial gradiometer channels % either in units of amplitude or in units of amplitude/distance (i.e. proper % gradient). % % (2011v2) The chantype and chanunit have been added for MEG. % % (2011v1) To facilitate determining the position of channels (e.g. for plotting) % in case of balanced MEG or bipolar EEG, an explicit distinction has been made % between chanpos+chanori and coilpos+coilori (for MEG) and chanpos and elecpos % (for EEG). The pnt and ori fields are removed % % (2010) Added support for bipolar or otherwise more complex linear combinations % of EEG electrodes using sens.tra, similar to MEG. % % (2009) Noice reduction has been added for MEG systems in the balance field. % % (2006) The optional fields sens.type and sens.unit were added. % % (2003) The initial version was defined, which looked like this for EEG % sens.pnt = Mx3 matrix with electrode positions % sens.label = Mx1 cell-array with channel labels % and like this for MEG % sens.pnt = Nx3 matrix with coil positions % sens.ori = Nx3 matrix with coil orientations % sens.tra = MxN matrix to combine coils into channels % sens.label = Mx1 cell-array with channel labels % % See also FT_READ_SENS, FT_SENSTYPE, FT_CHANTYPE, FT_APPLY_MONTAGE, CTF2GRAD, FIF2GRAD, % BTI2GRAD, YOKOGAWA2GRAD, ITAB2GRAD % Copyright (C) 2011-2016, Robert Oostenveld & Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % undocumented options for the 2016 format % amplitude = string, can be 'T' or 'fT' % distance = string, can be 'm', 'cm' or 'mm' % scaling = string, can be 'amplitude' or 'amplitude/distance' % these are for remembering the type on subsequent calls with the same input arguments persistent previous_argin previous_argout current_argin = [{sens} varargin]; if isequal(current_argin, previous_argin) % don't do the whole cheking again, but return the previous output from cache sens = previous_argout{1}; return end % get the optional input arguments, which should be specified as key-value pairs version = ft_getopt(varargin, 'version', 'latest'); amplitude = ft_getopt(varargin, 'amplitude'); % should be 'V' 'uV' 'T' 'mT' 'uT' 'nT' 'pT' 'fT' distance = ft_getopt(varargin, 'distance'); % should be 'm' 'dm' 'cm' 'mm' scaling = ft_getopt(varargin, 'scaling'); % should be 'amplitude' or 'amplitude/distance', the default depends on the senstype if ~isempty(amplitude) && ~any(strcmp(amplitude, {'V' 'uV' 'T' 'mT' 'uT' 'nT' 'pT' 'fT'})) error('unsupported unit of amplitude "%s"', amplitude); end if ~isempty(distance) && ~any(strcmp(distance, {'m' 'dm' 'cm' 'mm'})) error('unsupported unit of distance "%s"', distance); end if strcmp(version, 'latest') version = '2016'; end if isempty(sens) return; end % this is needed further down nchan = length(sens.label); % there are many cases which deal with either eeg or meg ismeg = ft_senstype(sens, 'meg'); switch version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case '2016' % update it to the previous standard version sens = ft_datatype_sens(sens, 'version', '2011v2'); % ensure that all numbers are represented in double precision sens = ft_struct2double(sens); % use "old/new" rather than "org/new" if isfield(sens, 'labelorg') sens.labelold = sens.labelorg; sens = rmfield(sens, 'labelorg'); end if isfield(sens, 'chantypeorg') sens.chantypeold = sens.chantypeorg; sens = rmfield(sens, 'chantypeorg'); end if isfield(sens, 'chanuniteorg') sens.chanunitold = sens.chanunitorg; sens = rmfield(sens, 'chanunitorg'); end if isfield(sens, 'chanposorg') sens.chanposold = sens.chanposorg; sens = rmfield(sens, 'chanposorg'); end if isfield(sens, 'chanoriorg') sens.chanoriold = sens.chanoriorg; sens = rmfield(sens, 'chanoriorg'); end % in version 2011v2 this was optional, now it is required if ~isfield(sens, 'chantype') || all(strcmp(sens.chantype, 'unknown')) sens.chantype = ft_chantype(sens); end % in version 2011v2 this was optional, now it is required if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown')) sens.chanunit = ft_chanunit(sens); end if ~isempty(distance) % update the units of distance, this also updates the tra matrix sens = ft_convert_units(sens, distance); else % determine the default, this may be needed to set the scaling distance = sens.unit; end if ~isempty(amplitude) && isfield(sens, 'tra') % update the tra matrix for the units of amplitude, this ensures that % the leadfield values remain consistent with the units for i=1:nchan if ~isempty(regexp(sens.chanunit{i}, 'm$', 'once')) % this channel is expressed as amplitude per distance sens.tra(i,:) = sens.tra(i,:) * ft_scalingfactor(sens.chanunit{i}, [amplitude '/' distance]); sens.chanunit{i} = [amplitude '/' distance]; elseif ~isempty(regexp(sens.chanunit{i}, '[T|V]$', 'once')) % this channel is expressed as amplitude sens.tra(i,:) = sens.tra(i,:) * ft_scalingfactor(sens.chanunit{i}, amplitude); sens.chanunit{i} = amplitude; else error('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i); end end else % determine the default amplityde, this may be needed to set the scaling if any(~cellfun(@isempty, regexp(sens.chanunit, '^T'))) % one of the channel units starts with T amplitude = 'T'; elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^fT'))) % one of the channel units starts with fT amplitude = 'fT'; elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^V'))) % one of the channel units starts with V amplitude = 'V'; elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^uV'))) % one of the channel units starts with uV amplitude = 'uV'; else % this unknown amplitude will cause a problem if the scaling needs to be changed between amplitude and amplitude/distance amplitude = 'unknown'; end end % perform some sanity checks if ismeg sel_m = ~cellfun(@isempty, regexp(sens.chanunit, '/m$')); sel_dm = ~cellfun(@isempty, regexp(sens.chanunit, '/dm$')); sel_cm = ~cellfun(@isempty, regexp(sens.chanunit, '/cm$')); sel_mm = ~cellfun(@isempty, regexp(sens.chanunit, '/mm$')); if strcmp(sens.unit, 'm') && (any(sel_dm) || any(sel_cm) || any(sel_mm)) error('inconsistent units in input gradiometer'); elseif strcmp(sens.unit, 'dm') && (any(sel_m) || any(sel_cm) || any(sel_mm)) error('inconsistent units in input gradiometer'); elseif strcmp(sens.unit, 'cm') && (any(sel_m) || any(sel_dm) || any(sel_mm)) error('inconsistent units in input gradiometer'); elseif strcmp(sens.unit, 'mm') && (any(sel_m) || any(sel_dm) || any(sel_cm)) error('inconsistent units in input gradiometer'); end % the default should be amplitude/distance for neuromag and amplitude for all others if isempty(scaling) if ft_senstype(sens, 'neuromag') scaling = 'amplitude/distance'; elseif ft_senstype(sens, 'yokogawa440') warning('asuming that the default scaling should be amplitude rather than amplitude/distance'); scaling = 'amplitude'; else scaling = 'amplitude'; end end % update the gradiometer scaling if strcmp(scaling, 'amplitude') && isfield(sens, 'tra') for i=1:nchan if strcmp(sens.chanunit{i}, [amplitude '/' distance]) % this channel is expressed as amplitude per distance coil = find(abs(sens.tra(i,:))~=0); if length(coil)~=2 error('unexpected number of coils contributing to channel %d', i); end baseline = norm(sens.coilpos(coil(1),:) - sens.coilpos(coil(2),:)); sens.tra(i,:) = sens.tra(i,:)*baseline; % scale with the baseline distance sens.chanunit{i} = amplitude; elseif strcmp(sens.chanunit{i}, amplitude) % no conversion needed else % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3144 ft_warning(sprintf('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i)); end % if end % for elseif strcmp(scaling, 'amplitude/distance') && isfield(sens, 'tra') for i=1:nchan if strcmp(sens.chanunit{i}, amplitude) % this channel is expressed as amplitude coil = find(abs(sens.tra(i,:))~=0); if length(coil)==1 || strcmp(sens.chantype{i}, 'megmag') % this is a magnetometer channel, no conversion needed continue elseif length(coil)~=2 error('unexpected number of coils (%d) contributing to channel %s (%d)', length(coil), sens.label{i}, i); end baseline = norm(sens.coilpos(coil(1),:) - sens.coilpos(coil(2),:)); sens.tra(i,:) = sens.tra(i,:)/baseline; % scale with the baseline distance sens.chanunit{i} = [amplitude '/' distance]; elseif strcmp(sens.chanunit{i}, [amplitude '/' distance]) % no conversion needed else % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3144 ft_warning(sprintf('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i)); end % if end % for end % if strcmp scaling else sel_m = ~cellfun(@isempty, regexp(sens.chanunit, '/m$')); sel_dm = ~cellfun(@isempty, regexp(sens.chanunit, '/dm$')); sel_cm = ~cellfun(@isempty, regexp(sens.chanunit, '/cm$')); sel_mm = ~cellfun(@isempty, regexp(sens.chanunit, '/mm$')); if any(sel_m | sel_dm | sel_cm | sel_mm) error('scaling of amplitude/distance has not been considered yet for EEG'); end end % if iseeg or ismeg %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case '2011v2' if ~isempty(amplitude) || ~isempty(distance) || ~isempty(scaling) warning('amplitude, distance and scaling are not supported for version "%s"', version); end % This speeds up subsequent calls to ft_senstype and channelposition. % However, if it is not more precise than MEG or EEG, don't keep it in % the output (see further down). if ~isfield(sens, 'type') sens.type = ft_senstype(sens); end if isfield(sens, 'pnt') if ismeg % sensor description is a MEG sensor-array, containing oriented coils sens.coilpos = sens.pnt; sens = rmfield(sens, 'pnt'); sens.coilori = sens.ori; sens = rmfield(sens, 'ori'); else % sensor description is something else, EEG/ECoG etc sens.elecpos = sens.pnt; sens = rmfield(sens, 'pnt'); end end if ~isfield(sens, 'chanpos') if ismeg % sensor description is a MEG sensor-array, containing oriented coils [chanpos, chanori, lab] = channelposition(sens); % the channel order can be different in the two representations [selsens, selpos] = match_str(sens.label, lab); sens.chanpos = nan(length(sens.label), 3); sens.chanori = nan(length(sens.label), 3); % insert the determined position/orientation on the appropriate rows sens.chanpos(selsens,:) = chanpos(selpos,:); sens.chanori(selsens,:) = chanori(selpos,:); if length(selsens)~=length(sens.label) warning('cannot determine the position and orientation for all channels'); end else % sensor description is something else, EEG/ECoG etc % note that chanori will be all NaNs [chanpos, chanori, lab] = channelposition(sens); % the channel order can be different in the two representations [selsens, selpos] = match_str(sens.label, lab); sens.chanpos = nan(length(sens.label), 3); % insert the determined position/orientation on the appropriate rows sens.chanpos(selsens,:) = chanpos(selpos,:); if length(selsens)~=length(sens.label) warning('cannot determine the position and orientation for all channels'); end end end if ~isfield(sens, 'chantype') || all(strcmp(sens.chantype, 'unknown')) if ismeg sens.chantype = ft_chantype(sens); else % for EEG it is not required end end if ~isfield(sens, 'unit') % this should be done prior to calling ft_chanunit, since ft_chanunit uses this for planar neuromag channels sens = ft_convert_units(sens); end if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown')) if ismeg sens.chanunit = ft_chanunit(sens); else % for EEG it is not required end end if any(strcmp(sens.type, {'meg', 'eeg', 'magnetometer', 'electrode', 'unknown'})) % this is not sufficiently informative, so better remove it % see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=1806 sens = rmfield(sens, 'type'); end if size(sens.chanpos,1)~=length(sens.label) || ... isfield(sens, 'tra') && size(sens.tra,1)~=length(sens.label) || ... isfield(sens, 'tra') && isfield(sens, 'elecpos') && size(sens.tra,2)~=size(sens.elecpos,1) || ... isfield(sens, 'tra') && isfield(sens, 'coilpos') && size(sens.tra,2)~=size(sens.coilpos,1) || ... isfield(sens, 'tra') && isfield(sens, 'coilori') && size(sens.tra,2)~=size(sens.coilori,1) || ... isfield(sens, 'chanpos') && size(sens.chanpos,1)~=length(sens.label) || ... isfield(sens, 'chanori') && size(sens.chanori,1)~=length(sens.label) error('inconsistent number of channels in sensor description'); end if ismeg % ensure that the magnetometer/gradiometer balancing is specified if ~isfield(sens, 'balance') || ~isfield(sens.balance, 'current') sens.balance.current = 'none'; end % try to add the chantype and chanunit to the CTF G1BR montage if isfield(sens, 'balance') && isfield(sens.balance, 'G1BR') && ~isfield(sens.balance.G1BR, 'chantype') sens.balance.G1BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G1BR.labelorg)); sens.balance.G1BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G1BR.labelorg)); sens.balance.G1BR.chantypenew = repmat({'unknown'}, size(sens.balance.G1BR.labelnew)); sens.balance.G1BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G1BR.labelnew)); % the synthetic gradient montage does not fundamentally change the chantype or chanunit [sel1, sel2] = match_str(sens.balance.G1BR.labelorg, sens.label); sens.balance.G1BR.chantypeorg(sel1) = sens.chantype(sel2); sens.balance.G1BR.chanunitorg(sel1) = sens.chanunit(sel2); [sel1, sel2] = match_str(sens.balance.G1BR.labelnew, sens.label); sens.balance.G1BR.chantypenew(sel1) = sens.chantype(sel2); sens.balance.G1BR.chanunitnew(sel1) = sens.chanunit(sel2); end % idem for G2BR if isfield(sens, 'balance') && isfield(sens.balance, 'G2BR') && ~isfield(sens.balance.G2BR, 'chantype') sens.balance.G2BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G2BR.labelorg)); sens.balance.G2BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G2BR.labelorg)); sens.balance.G2BR.chantypenew = repmat({'unknown'}, size(sens.balance.G2BR.labelnew)); sens.balance.G2BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G2BR.labelnew)); % the synthetic gradient montage does not fundamentally change the chantype or chanunit [sel1, sel2] = match_str(sens.balance.G2BR.labelorg, sens.label); sens.balance.G2BR.chantypeorg(sel1) = sens.chantype(sel2); sens.balance.G2BR.chanunitorg(sel1) = sens.chanunit(sel2); [sel1, sel2] = match_str(sens.balance.G2BR.labelnew, sens.label); sens.balance.G2BR.chantypenew(sel1) = sens.chantype(sel2); sens.balance.G2BR.chanunitnew(sel1) = sens.chanunit(sel2); end % idem for G3BR if isfield(sens, 'balance') && isfield(sens.balance, 'G3BR') && ~isfield(sens.balance.G3BR, 'chantype') sens.balance.G3BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G3BR.labelorg)); sens.balance.G3BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G3BR.labelorg)); sens.balance.G3BR.chantypenew = repmat({'unknown'}, size(sens.balance.G3BR.labelnew)); sens.balance.G3BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G3BR.labelnew)); % the synthetic gradient montage does not fundamentally change the chantype or chanunit [sel1, sel2] = match_str(sens.balance.G3BR.labelorg, sens.label); sens.balance.G3BR.chantypeorg(sel1) = sens.chantype(sel2); sens.balance.G3BR.chanunitorg(sel1) = sens.chanunit(sel2); [sel1, sel2] = match_str(sens.balance.G3BR.labelnew, sens.label); sens.balance.G3BR.chantypenew(sel1) = sens.chantype(sel2); sens.balance.G3BR.chanunitnew(sel1) = sens.chanunit(sel2); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% otherwise error('converting to version %s is not supported', version); end % switch % this makes the display with the "disp" command look better sens = sortfieldnames(sens); % remember the current input and output arguments, so that they can be % reused on a subsequent call in case the same input argument is given current_argout = {sens}; previous_argin = current_argin; previous_argout = current_argout; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function b = sortfieldnames(a) fn = sort(fieldnames(a)); for i=1:numel(fn) b.(fn{i}) = a.(fn{i}); end
github
lcnbeapp/beapp-master
ptriside.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/private/ptriside.m
1,257
utf_8
f52f0beb3731b653116c217b37b673d2
function [side] = ptriside(v1, v2, v3, r, tolerance) % PTRISIDE determines the side of a plane on which a set of points lie. it % returns 0 for the points that lie on the plane % % [side] = ptriside(v1, v2, v3, r) % % the side of points r is determined relative to the plane spanned by % vertices v1, v2 and v3. v1,v2 and v3 should be 1x3 vectors. r should be a % Nx3 matrix % Copyright (C) 2002, Robert Oostenveld % % $Log: ptriside.m,v $ % Revision 1.3 2003/03/11 15:35:20 roberto % converted all files from DOS to UNIX % % Revision 1.2 2003/03/04 21:46:19 roberto % added CVS log entry and synchronized all copyright labels % if nargin<5 tolerance = 100*eps; end n = size(r,1); a = r - ones(n,1)*v1; b = v2 - v1; c = v3 - v1; d = crossproduct(b, c); val = dotproduct(a, d); side = zeros(n, 1); side(val > tolerance) = 1; side(val < -tolerance) = -1; %if val>tolerance % side=1; %elseif val<-tolerance % side=-1; %else % side=0; %end % subfunction without overhead to speed up function c = crossproduct(a, b) c(1) = a(2)*b(3)-a(3)*b(2); c(2) = a(3)*b(1)-a(1)*b(3); c(3) = a(1)*b(2)-a(2)*b(1); % subfunction without overhead to speed up, input a can be a matrix function d = dotproduct(a, b) d = a(:,1)*b(1)+a(:,2)*b(2)+a(:,3)*b(3);
github
lcnbeapp/beapp-master
ft_convert_units.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/private/ft_convert_units.m
10,207
utf_8
d3c04f1222517baf2f069d68e3dd6abe
function [obj] = ft_convert_units(obj, target, varargin) % 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 geometrical objects are supported as inputs % electrode or gradiometer array, see FT_DATATYPE_SENS % volume conductor, see FT_DATATYPE_HEADMODEL % anatomical mri, see FT_DATATYPE_VOLUME % segmented mri, see FT_DATATYPE_SEGMENTATION % dipole grid definition, see FT_DATATYPE_SOURCE % % Possible target units are 'm', 'dm', 'cm ' or 'mm'. If no target units % are specified, this function will only determine the native geometrical % units of the object. % % See also FT_ESTIMATE_UNITS, FT_READ_VOL, FT_READ_SENS % Copyright (C) 2005-2016, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % This 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 feedback = ft_getopt(varargin, 'feedback', false); if isstruct(obj) && numel(obj)>1 % deal with a structure array for i=1:numel(obj) if nargin>1 tmp(i) = ft_convert_units(obj(i), target, varargin{:}); else tmp(i) = ft_convert_units(obj(i)); end end obj = tmp; return elseif iscell(obj) && numel(obj)>1 % deal with a cell array % this might represent combined EEG, ECoG and/or MEG for i=1:numel(obj) obj{i} = ft_convert_units(obj{i}, target, varargin{:}); end return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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; elseif isfield(obj, 'bnd') && isfield(obj.bnd, 'unit') unit = unique({obj.bnd.unit}); if ~all(strcmp(unit, unit{1})) error('inconsistent units in the individual boundaries'); else unit = unit{1}; end % keep one representation of the units rather than keeping it with each boundary % the units will be reassigned further down obj.bnd = rmfield(obj.bnd, 'unit'); else % try to determine the units by looking at the size of the object if isfield(obj, 'chanpos') && ~isempty(obj.chanpos) siz = norm(idrange(obj.chanpos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'elecpos') && ~isempty(obj.elecpos) siz = norm(idrange(obj.elecpos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'coilpos') && ~isempty(obj.coilpos) siz = norm(idrange(obj.coilpos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'pnt') && ~isempty(obj.pnt) siz = norm(idrange(obj.pnt)); unit = ft_estimate_units(siz); elseif isfield(obj, 'pos') && ~isempty(obj.pos) siz = norm(idrange(obj.pos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'transform') && ~isempty(obj.transform) % construct the corner points of the volume in voxel and in head coordinates [pos_voxel, pos_head] = cornerpoints(obj.dim, obj.transform); siz = norm(idrange(pos_head)); unit = ft_estimate_units(siz); elseif isfield(obj, 'fid') && isfield(obj.fid, 'pnt') && ~isempty(obj.fid.pnt) siz = norm(idrange(obj.fid.pnt)); unit = ft_estimate_units(siz); elseif isfield(obj, 'fid') && isfield(obj.fid, 'pos') && ~isempty(obj.fid.pos) siz = norm(idrange(obj.fid.pos)); unit = ft_estimate_units(siz); elseif ft_voltype(obj, 'infinite') % this is an infinite medium volume conductor, which does not care about units unit = 'm'; elseif ft_voltype(obj,'singlesphere') siz = obj.r; unit = ft_estimate_units(siz); elseif ft_voltype(obj,'localspheres') siz = median(obj.r); unit = ft_estimate_units(siz); elseif ft_voltype(obj,'concentricspheres') siz = max(obj.r); unit = ft_estimate_units(siz); elseif isfield(obj, 'bnd') && isstruct(obj.bnd) && isfield(obj.bnd(1), 'pnt') && ~isempty(obj.bnd(1).pnt) siz = norm(idrange(obj.bnd(1).pnt)); unit = ft_estimate_units(siz); elseif isfield(obj, 'bnd') && isstruct(obj.bnd) && isfield(obj.bnd(1), 'pos') && ~isempty(obj.bnd(1).pos) siz = norm(idrange(obj.bnd(1).pos)); unit = ft_estimate_units(siz); elseif isfield(obj, 'nas') && isfield(obj, 'lpa') && isfield(obj, 'rpa') pnt = [obj.nas; obj.lpa; obj.rpa]; siz = norm(idrange(pnt)); unit = ft_estimate_units(siz); else error('cannot determine geometrical units'); end % recognized type of volume conduction model or sensor array end % determine input units if nargin<2 || isempty(target) % 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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute the scaling factor from the input units to the desired ones %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% scale = ft_scalingfactor(unit, target); if istrue(feedback) % give some information about the conversion fprintf('converting units from ''%s'' to ''%s''\n', unit, target) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % apply the scaling factor %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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') && isfield(obj.bnd, 'pnt') for i=1:length(obj.bnd) obj.bnd(i).pnt = scale * obj.bnd(i).pnt; end end if isfield(obj, 'bnd') && isfield(obj.bnd, 'pos') for i=1:length(obj.bnd) obj.bnd(i).pos = scale * obj.bnd(i).pos; end end % old-fashioned 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 if isfield(obj, 'pos'), obj.pos = scale * obj.pos; end if isfield(obj, 'chanpos'), obj.chanpos = scale * obj.chanpos; end if isfield(obj, 'chanposorg'), obj.chanposold = scale * obj.chanposorg; end % pre-2016 version if isfield(obj, 'chanposold'), obj.chanposold = scale * obj.chanposold; end % 2016 version and later if isfield(obj, 'coilpos'), obj.coilpos = scale * obj.coilpos; end if isfield(obj, 'elecpos'), obj.elecpos = scale * obj.elecpos; end % gradiometer array that combines multiple coils in one channel if isfield(obj, 'tra') && isfield(obj, 'chanunit') % find the gradiometer channels that are expressed as unit of field strength divided by unit of distance, e.g. T/cm for i=1:length(obj.chanunit) tok = tokenize(obj.chanunit{i}, '/'); if ~isempty(regexp(obj.chanunit{i}, 'm$', 'once')) % assume that it is T/m or so obj.tra(i,:) = obj.tra(i,:) / scale; obj.chanunit{i} = [tok{1} '/' target]; elseif ~isempty(regexp(obj.chanunit{i}, '[T|V]$', 'once')) % assume that it is T or V, don't do anything elseif strcmp(obj.chanunit{i}, 'unknown') % assume that it is T or V, don't do anything else error('unexpected units %s', obj.chanunit{i}); end end % for end % if % fiducials if isfield(obj, 'fid') && isfield(obj.fid, 'pnt'), obj.fid.pnt = scale * obj.fid.pnt; end if isfield(obj, 'fid') && isfield(obj.fid, 'pos'), obj.fid.pos = scale * obj.fid.pos; end % dipole grid if isfield(obj, 'resolution'), obj.resolution = scale * obj.resolution; end % x,y,zgrid can also be 'auto' if isfield(obj, 'xgrid') && ~ischar(obj.xgrid), obj.xgrid = scale * obj.xgrid; end if isfield(obj, 'ygrid') && ~ischar(obj.ygrid), obj.ygrid = scale * obj.ygrid; end if isfield(obj, 'zgrid') && ~ischar(obj.zgrid), obj.zgrid = scale * obj.zgrid; 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 % sourcemodel obtained through mne also has a orig-field with the high % number of vertices if isfield(obj, 'orig') if isfield(obj.orig, 'pnt') obj.orig.pnt = scale * obj.orig.pnt; end if isfield(obj.orig, 'pos') obj.orig.pos = scale * obj.orig.pos; end end % remember the unit obj.unit = target; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % IDRANGE interdecile range for more robust range estimation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function r = idrange(x) keeprow=true(size(x,1),1); for l=1:size(x,2) keeprow = keeprow & isfinite(x(:,l)); end sx = sort(x(keeprow,:), 1); ii = round(interp1([0, 1], [1, size(x(keeprow,:), 1)], [.1, .9])); % indices for 10 & 90 percentile r = diff(sx(ii, :));
github
lcnbeapp/beapp-master
ft_apply_montage.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/private/ft_apply_montage.m
21,632
utf_8
44431986d20b2a03b833ec06858af91d
function [input] = ft_apply_montage(input, 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 input EEG or MEG sensor array, which 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, ...) % [freq] = ft_apply_montage(freq, montage, ...) % [montage] = ft_apply_montage(montage1, montage2, ...) % % A montage is specified as a structure with the fields % montage.tra = MxN matrix % montage.labelold = Nx1 cell-array % montage.labelnew = Mx1 cell-array % % As an example, a bipolar montage could look like this % bipolar.labelold = {'1', '2', '3', '4'} % bipolar.labelnew = {'1-2', '2-3', '3-4'} % bipolar.tra = [ % +1 -1 0 0 % 0 +1 -1 0 % 0 0 +1 -1 % ]; % % The montage can optionally also specify the channel type and unit of the input % and output data with % montage.chantypeold = Nx1 cell-array % montage.chantypenew = Mx1 cell-array % montage.chanunitold = Nx1 cell-array % montage.chanunitnew = Mx1 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') % 'balancename' string, name of the montage (default = '') % 'feedback' string, see FT_PROGRESS (default = 'text') % 'warning' boolean, whether to show warnings (default = true) % % If the first input is a montage, then the second input montage will be % applied to the first. In effect, the output montage will first do % montage1, then montage2. % % See also FT_READ_SENS, FT_TRANSFORM_SENS % Copyright (C) 2008-2016, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if iscell(input) && iscell(input) % this represents combined EEG, ECoG and/or MEG for i=1:numel(input) input{i} = ft_apply_montage(input{i}, montage, varargin{:}); end return end % use "old/new" instead of "org/new" montage = fixmontage(montage); input = fixmontage(input); % the input might also be a montage % get optional input arguments keepunused = ft_getopt(varargin, 'keepunused', 'no'); inverse = ft_getopt(varargin, 'inverse', 'no'); feedback = ft_getopt(varargin, 'feedback', 'text'); showwarning = ft_getopt(varargin, 'warning', true); bname = ft_getopt(varargin, 'balancename', ''); if istrue(showwarning) warningfun = @warning; else warningfun = @nowarning; end % these are optional, at the end we will clean up the output in case they did not exist haschantype = (isfield(input, 'chantype') || isfield(input, 'chantypenew')) && all(isfield(montage, {'chantypeold', 'chantypenew'})); haschanunit = (isfield(input, 'chanunit') || isfield(input, 'chanunitnew')) && all(isfield(montage, {'chanunitold', 'chanunitnew'})); % make sure they always exist to facilitate the remainder of the code if ~isfield(montage, 'chantypeold') montage.chantypeold = repmat({'unknown'}, size(montage.labelold)); if isfield(input, 'chantype') && ~istrue(inverse) warning('copying input chantype to montage'); [sel1, sel2] = match_str(montage.labelold, input.label); montage.chantypeold(sel1) = input.chantype(sel2); end end if ~isfield(montage, 'chantypenew') montage.chantypenew = repmat({'unknown'}, size(montage.labelnew)); if isfield(input, 'chantype') && istrue(inverse) warning('copying input chantype to montage'); [sel1, sel2] = match_str(montage.labelnew, input.label); montage.chantypenew(sel1) = input.chantype(sel2); end end if ~isfield(montage, 'chanunitold') montage.chanunitold = repmat({'unknown'}, size(montage.labelold)); if isfield(input, 'chanunit') && ~istrue(inverse) warning('copying input chanunit to montage'); [sel1, sel2] = match_str(montage.labelold, input.label); montage.chanunitold(sel1) = input.chanunit(sel2); end end if ~isfield(montage, 'chanunitnew') montage.chanunitnew = repmat({'unknown'}, size(montage.labelnew)); if isfield(input, 'chanunit') && istrue(inverse) warning('copying input chanunit to montage'); [sel1, sel2] = match_str(montage.labelnew, input.label); montage.chanunitnew(sel1) = input.chanunit(sel2); end end if ~isfield(input, 'label') && isfield(input, 'labelnew') % the input data structure is also a montage inputlabel = input.labelnew; if isfield(input, 'chantypenew') inputchantype = input.chantypenew; else inputchantype = repmat({'unknown'}, size(input.labelnew)); end if isfield(input, 'chanunitnew') inputchanunit = input.chanunitnew; else inputchanunit = repmat({'unknown'}, size(input.labelnew)); end else % the input should describe the channel labels, and optionally the type and unit inputlabel = input.label; if isfield(input, 'chantype') inputchantype = input.chantype; else inputchantype = repmat({'unknown'}, size(input.label)); end if isfield(input, 'chanunit') inputchanunit = input.chanunit; else inputchanunit = repmat({'unknown'}, size(input.label)); end end % check the consistency of the montage if ~iscell(montage.labelold) || ~iscell(montage.labelnew) error('montage labels need to be specified in cell-arrays'); end % check the consistency of the montage if ~all(isfield(montage, {'tra', 'labelold', 'labelnew'})) error('the second input argument does not correspond to a montage'); 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.labelold) error('the number of channels in the montage is inconsistent'); end % use a default unit transfer from sensors to channels if not otherwise specified if ~isfield(input, 'tra') && isfield(input, 'label') if isfield(input, 'elecpos') && length(input.label)==size(input.elecpos, 1) nchan = length(input.label); input.tra = eye(nchan); elseif isfield(input, 'coilpos') && length(input.label)==size(input.coilpos, 1) nchan = length(input.label); input.tra = eye(nchan); elseif isfield(input, 'chanpos') && length(input.label)==size(input.chanpos, 1) nchan = length(input.label); input.tra = eye(nchan); end end if istrue(inverse) % swap the role of the original and new channels tmp.labelnew = montage.labelold; tmp.labelold = montage.labelnew; tmp.chantypenew = montage.chantypeold; tmp.chantypeold = montage.chantypenew; tmp.chanunitnew = montage.chanunitold; tmp.chanunitold = montage.chanunitnew; % apply the inverse montage, this can be used to undo a previously % applied montage tmp.tra = full(montage.tra); if rank(tmp.tra) < length(tmp.tra) warningfun('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 % 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.labelold = montage.labelold(selcol); montage.chantypeold = montage.chantypeold(selcol); montage.chanunitold = montage.chanunitold(selcol); clear selcol % select and remove the columns corresponding to channels that are not present in the % original data remove = setdiff(montage.labelold, intersect(montage.labelold, inputlabel)); selcol = match_str(montage.labelold, 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.labelold)); % remove rows and columns montage.labelold = montage.labelold(~selcol); montage.labelnew = montage.labelnew(~selrow); montage.chantypeold = montage.chantypeold(~selcol); montage.chantypenew = montage.chantypenew(~selrow); montage.chanunitold = montage.chanunitold(~selcol); montage.chanunitnew = montage.chanunitnew(~selrow); montage.tra = montage.tra(~selrow, ~selcol); clear remove selcol selrow i % add columns for channels that are present in the input data but not specified in % the montage, stick to the original order in the data [dum, ix] = setdiff(inputlabel, montage.labelold); addlabel = inputlabel(sort(ix)); addchantype = inputchantype(sort(ix)); addchanunit = inputchanunit(sort(ix)); m = size(montage.tra,1); n = size(montage.tra,2); k = length(addlabel); % check for NaNs in unused channels; these will be mixed in with the rest % of the channels and result in NaNs in the output even when multiplied % with zeros or identity if k > 0 && isfield(input, 'trial') % check for raw data now only cfg = []; cfg.channel = addlabel; data_unused = ft_selectdata(cfg, input); % use an anonymous function to test for the presence of NaNs in the input data hasnan = @(x) any(isnan(x(:))); if any(cellfun(hasnan, data_unused.trial)) error('FieldTrip:NaNsinInputData', ['Your input data contains NaNs in channels that are unused '... 'in the supplied montage. This would result in undesired NaNs in the '... 'output data. Please remove these channels from the input data (using '... 'ft_selectdata) before attempting to apply the montage.']); end end if istrue(keepunused) % add the channels that are not rereferenced to the input and output of the % montage montage.tra((m+(1:k)),(n+(1:k))) = eye(k); montage.labelold = cat(1, montage.labelold(:), addlabel(:)); montage.labelnew = cat(1, montage.labelnew(:), addlabel(:)); montage.chantypeold = cat(1, montage.chantypeold(:), addchantype(:)); montage.chantypenew = cat(1, montage.chantypenew(:), addchantype(:)); montage.chanunitold = cat(1, montage.chanunitold(:), addchanunit(:)); montage.chanunitnew = cat(1, montage.chanunitnew(:), addchanunit(:)); else % add the channels that are not rereferenced to the input of the montage only montage.tra(:,(n+(1:k))) = zeros(m,k); montage.labelold = cat(1, montage.labelold(:), addlabel(:)); montage.chantypeold = cat(1, montage.chantypeold(:), addchantype(:)); montage.chanunitold = cat(1, montage.chanunitold(:), addchanunit(:)); end clear addlabel addchantype addchanunit 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.labelold))~=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(inputlabel, montage.labelold))~=length(montage.labelold) error('not all channels that are required in the montage are available in the data'); end % reorder the columns of the montage matrix [selinput, selmontage] = match_str(inputlabel, montage.labelold); montage.tra = montage.tra(:,selmontage); montage.labelold = montage.labelold(selmontage); montage.chantypeold = montage.chantypeold(selmontage); montage.chanunitold = montage.chanunitold(selmontage); % ensure that the montage is double precision montage.tra = double(montage.tra); % making the tra matrix sparse will speed up subsequent multiplications, but should % not result in a sparse matrix % note that this only makes sense for matrices with a lot of zero elements, for dense % matrices keeping it full will be much quicker if size(montage.tra,1)>1 && nnz(montage.tra)/numel(montage.tra) < 0.3 montage.tra = sparse(montage.tra); else montage.tra = full(montage.tra); end % update the channel scaling if the input has different units than the montage expects if isfield(input, 'chanunit') && ~isequal(input.chanunit, montage.chanunitold) scale = ft_scalingfactor(input.chanunit, montage.chanunitold); montage.tra = montage.tra * diag(scale); montage.chanunitold = input.chanunit; elseif isfield(input, 'chanunitnew') && ~isequal(input.chanunitnew, montage.chanunitold) scale = ft_scalingfactor(input.chanunitnew, montage.chanunitold); montage.tra = montage.tra * diag(scale); montage.chanunitold = input.chanunitnew; end if isfield(input, 'chantype') && ~isequal(input.chantype, montage.chantypeold) error('inconsistent chantype in data and montage'); elseif isfield(input, 'chantypenew') && ~isequal(input.chantypenew, montage.chantypeold) error('inconsistent chantype in data and montage'); end if isfield(input, 'labelold') && isfield(input, 'labelnew') inputtype = 'montage'; elseif isfield(input, 'tra') inputtype = 'sens'; elseif isfield(input, 'trial') inputtype = 'raw'; elseif isfield(input, 'fourierspctrm') inputtype = 'freq'; else inputtype = 'unknown'; end switch inputtype case 'montage' % apply the montage on top of the other montage if isa(input.tra, 'single') % sparse matrices and single precision do not match input.tra = full(montage.tra) * input.tra; else input.tra = montage.tra * input.tra; end input.labelnew = montage.labelnew; input.chantypenew = montage.chantypenew; input.chanunitnew = montage.chanunitnew; case 'sens' % apply the montage to an electrode or gradiometer description sens = input; clear input % apply the montage to the inputor array if isa(sens.tra, 'single') % sparse matrices and single precision do not match sens.tra = full(montage.tra) * sens.tra; else sens.tra = montage.tra * sens.tra; end % The montage operates on the coil weights in sens.tra, but the output channels % can be different. If possible, we want to keep the original channel positions % and orientations. [sel1, sel2] = match_str(montage.labelnew, inputlabel); keepchans = length(sel1)==length(montage.labelnew); if isfield(sens, 'chanpos') if keepchans sens.chanpos = sens.chanpos(sel2,:); else if ~isfield(sens, 'chanposold') % add a chanposold only if it is not there yet sens.chanposold = sens.chanpos; end sens.chanpos = nan(numel(montage.labelnew),3); end end if isfield(sens, 'chanori') if keepchans sens.chanori = sens.chanori(sel2,:); else if ~isfield(sens, 'chanoriold') sens.chanoriold = sens.chanori; end sens.chanori = nan(numel(montage.labelnew),3); end end sens.label = montage.labelnew; sens.chantype = montage.chantypenew; sens.chanunit = montage.chanunitnew; % keep the % original label, % type and unit % for reference if ~isfield(sens, 'labelold') sens.labelold = inputlabel; end if ~isfield(sens, 'chantypeold') sens.chantypeold = inputchantype; end if ~isfield(sens, 'chanunitold') sens.chanunitold = inputchanunit; end % keep track of the order of the balancing and which one is the current one if istrue(inverse) 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 ~istrue(inverse) && ~isempty(bname) if isfield(sens, 'balance'), % check whether a balancing montage with name bname already exist, % and if so, how many mnt = fieldnames(sens.balance); sel = strmatch(bname, mnt); if numel(sel)==0, % bname can stay the same elseif numel(sel)==1 % the original should be renamed to 'bname1' and the new one should % be 'bname2' sens.balance.([bname, '1']) = sens.balance.(bname); sens.balance = rmfield(sens.balance, bname); if isfield(sens.balance, 'current') && strcmp(sens.balance.current, bname) sens.balance.current = [bname, '1']; end if isfield(sens.balance, 'previous') sel2 = strmatch(bname, sens.balance.previous); if ~isempty(sel2) sens.balance.previous{sel2} = [bname, '1']; end end bname = [bname, '2']; else bname = [bname, num2str(length(sel)+1)]; end end 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 % rename the output variable input = sens; clear sens case 'raw'; % apply the montage to the raw data that was preprocessed using fieldtrip data = input; clear input 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; data.chantype = montage.chantypenew; data.chanunit = montage.chanunitnew; % rename the output variable input = data; clear data case 'freq' % apply the montage to the spectrally decomposed data freq = input; clear input 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 freq.fourierspctrm = output; % replace the original Fourier spectrum 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 freq.fourierspctrm = output; % replace the original Fourier spectrum else error('unsupported dimord in frequency data (%s)', freq.dimord); end freq.label = montage.labelnew; freq.chantype = montage.chantypenew; freq.chanunit = montage.chanunitnew; % rename the output variable input = freq; clear freq otherwise error('unrecognized input'); end % switch inputtype % only retain the chantype and/or chanunit if they were present in the input if ~haschantype input = removefields(input, {'chantype', 'chantypeold', 'chantypenew'}); end if ~haschanunit input = removefields(input, {'chanunit', 'chanunitold', 'chanunitnew'}); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = indx2logical(x, n) y = false(1,n); y(x) = true; function nowarning(varargin) return function s = removefields(s, fn) for i=1:length(fn) if isfield(s, fn{i}) s = rmfield(s, fn{i}); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTION use "old/new" instead of "org/new" %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function montage = fixmontage(montage) if isfield(montage, 'labelorg') montage.labelold = montage.labelorg; montage = rmfield(montage, 'labelorg'); end if isfield(montage, 'chantypeorg') montage.chantypeold = montage.chantypeorg; montage = rmfield(montage, 'chantypeorg'); end if isfield(montage, 'chanunitorg') montage.chanunitold = montage.chanunitorg; montage = rmfield(montage, 'chanunitorg'); end
github
lcnbeapp/beapp-master
select3dtool.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/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
lcnbeapp/beapp-master
ft_platform_supports.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/private/ft_platform_supports.m
9,557
utf_8
eb0e55d84d57e6873cce8df6cad90d96
function tf = ft_platform_supports(what,varargin) % FT_PLATFORM_SUPPORTS returns a boolean indicating whether the current platform % supports a specific capability % % Usage: % tf = ft_platform_supports(what) % tf = ft_platform_supports('matlabversion', min_version, max_version) % % The following values are allowed for the 'what' parameter: % value means that the following is supported: % % 'which-all' which(...,'all') % 'exists-in-private-directory' exists(...) will look in the /private % subdirectory to see if a file exists % 'onCleanup' onCleanup(...) % 'alim' alim(...) % 'int32_logical_operations' bitand(a,b) with a, b of type int32 % 'graphics_objects' graphics sysem is object-oriented % 'libmx_c_interface' libmx is supported through mex in the % C-language (recent Matlab versions only % support C++) % 'stats' all statistical functions in % FieldTrip's external/stats directory % 'program_invocation_name' program_invocation_name() (GNU Octave) % 'singleCompThread' start Matlab with -singleCompThread % 'nosplash' -nosplash % 'nodisplay' -nodisplay % 'nojvm' -nojvm % 'no-gui' start GNU Octave with --no-gui % 'RandStream.setGlobalStream' RandStream.setGlobalStream(...) % 'RandStream.setDefaultStream' RandStream.setDefaultStream(...) % 'rng' rng(...) % 'rand-state' rand('state') % 'urlread-timeout' urlread(..., 'Timeout', t) % 'griddata-vector-input' griddata(...,...,...,a,b) with a and b % vectors % 'griddata-v4' griddata(...,...,...,...,...,'v4'), % that is v4 interpolation support % 'uimenu' uimenu(...) if ~ischar(what) error('first argument must be a string'); end switch what case 'matlabversion' tf = is_matlab() && matlabversion(varargin{:}); case 'exists-in-private-directory' tf = is_matlab(); case 'which-all' tf = is_matlab(); case 'onCleanup' tf = is_octave() || matlabversion(7.8, Inf); case 'alim' tf = is_matlab(); case 'int32_logical_operations' % earlier version of Matlab don't support bitand (and similar) % operations on int32 tf = is_octave() || ~matlabversion(-inf, '2012a'); case 'graphics_objects' % introduced in Matlab 2014b, graphics is handled through objects; % previous versions use numeric handles tf = is_matlab() && matlabversion('2014b', Inf); case 'libmx_c_interface' % removed after 2013b tf = matlabversion(-Inf, '2013b'); case 'stats' root_dir=fileparts(which('ft_defaults')); external_stats_dir=fullfile(root_dir,'external','stats'); % these files are only used by other functions in the external/stats % directory exclude_mfiles={'common_size.m',... 'iscomplex.m',... 'lgamma.m'}; tf = has_all_functions_in_dir(external_stats_dir,exclude_mfiles); case 'program_invocation_name' % Octave supports program_invocation_name, which returns the path % of the binary that was run to start Octave tf = is_octave(); case 'singleCompThread' tf = is_matlab() && matlabversion(7.8, inf); case {'nosplash','nodisplay','nojvm'} % Only on Matlab tf = is_matlab(); case 'no-gui' % Only on Octave tf = is_octave(); case 'RandStream.setDefaultStream' tf = is_matlab() && matlabversion('2008b', '2011b'); case 'RandStream.setGlobalStream' tf = is_matlab() && matlabversion('2012a', inf); case 'randomized_PRNG_on_startup' tf = is_octave() || ~matlabversion(-Inf,'7.3'); case 'rng' % recent Matlab versions tf = is_matlab() && matlabversion('7.12',Inf); case 'rand-state' % GNU Octave tf = is_octave(); case 'urlread-timeout' tf = is_matlab() && matlabversion('2012b',Inf); case 'griddata-vector-input' tf = is_matlab(); case 'griddata-v4' tf = is_matlab() && matlabversion('2009a',Inf); case 'uimenu' tf = is_matlab(); otherwise error('unsupported value for first argument: %s', what); end % switch end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_matlab() tf = ~is_octave(); end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_octave() persistent cached_tf; if isempty(cached_tf) cached_tf = logical(exist('OCTAVE_VERSION', 'builtin')); end tf = cached_tf; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = has_all_functions_in_dir(in_dir, exclude_mfiles) % returns true if all functions in in_dir are already provided by the % platform m_files=dir(fullfile(in_dir,'*.m')); n=numel(m_files); for k=1:n m_filename=m_files(k).name; if isempty(which(m_filename)) && ... isempty(strmatch(m_filename,exclude_mfiles)) tf=false; return; end end tf=true; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 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(6, '7.10') % is version between 6 and 7.10? (note: '7.10', not 7.10) % matlabversion(-Inf, 7.6) % is version <= 7.6? % matlabversion('2009b') % exactly 2009b % matlabversion('2008b', '2010a') % between two versions % matlabversion('2008b', Inf) % from a version onwards % etc. % % See also VERSION, VER, VERLESSTHAN % Copyright (C) 2006, Robert Oostenveld % Copyright (C) 2010, Eelke Spaak % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this does not change over subsequent calls, making it persistent speeds it up persistent curVer if nargin<2 max = min; end if isempty(curVer) curVer = version(); end 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 end % function 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 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 % function % 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 % function
github
lcnbeapp/beapp-master
ft_warning.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/private/ft_warning.m
7,789
utf_8
d832a7ad5e2f9bb42995e6e5d4caa198
function [ws, warned] = ft_warning(varargin) % FT_WARNING will throw a warning for every unique point in the % stacktrace only, e.g. in a for-loop a warning is thrown only once. % % Use as one of the following % ft_warning(string) % ft_warning(id, string) % Alternatively, you can use ft_warning using a timeout % ft_warning(string, timeout) % ft_warning(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. % % Use as ft_warning('-clear') to clear old warnings from the current % stack % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = ft_warning(...) % or as % ft_warning(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, ft_warning accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = ft_warning(...) % where w is a boolean that indicates whether a warning as been thrown or not. % % Please note that you can NOT use it like this % ft_warning('the value is %d', 10) % instead you should do % ft_warning(sprintf('the value is %d', 10)) % Copyright (C) 2012-2016, Robert Oostenveld, J?rn M. Horschig % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ global ft_default warned = false; ws = []; stack = dbstack; if any(strcmp({stack(2:end).file}, 'ft_warning.m')) % don't call FT_WARNING recursively, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3068 return; end if nargin < 1 error('You need to specify at least a warning message'); end if isstruct(varargin{1}) warning(varargin{1}); return; end if ~isfield(ft_default, 'warning') ft_default.warning = []; end if ~isfield(ft_default.warning, 'stopwatch') ft_default.warning.stopwatch = []; end if ~isfield(ft_default.warning, 'identifier') ft_default.warning.identifier = []; end if ~isfield(ft_default.warning, 'ignore') ft_default.warning.ignore = {}; end % put the arguments we will pass to warning() in this cell array warningArgs = {}; if nargin==3 % calling syntax (id, msg, timeout) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); msg = warningArgs{1}; timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && isequal(varargin{1}, 'off') ft_default.warning.ignore = union(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && isequal(varargin{1}, 'on') ft_default.warning.ignore = setdiff(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = inf; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); msg = warningArgs{1}; timeout = inf; % default timeout in seconds fname = [warningArgs{1}]; end if ismember(msg, ft_default.warning.ignore) % do not show this warning return; end if isempty(timeout) error('Timeout ill-specified'); end if timeout ~= inf fname = fixname(fname); % make a nice string that is allowed as fieldname in a structures line = []; else % here, we create the fieldname functionA.functionB.functionC... [tmpfname, ft_default.warning.identifier, line] = fieldnameFromStack(ft_default.warning.identifier); if ~isempty(tmpfname), fname = tmpfname; clear tmpfname; end end if nargin==1 && ischar(varargin{1}) && strcmp('-clear', varargin{1}) if strcmp(fname, '-clear') % reset all fields if called outside a function ft_default.warning.identifier = []; ft_default.warning.stopwatch = []; else if issubfield(ft_default.warning.identifier, fname) ft_default.warning.identifier = rmsubfield(ft_default.warning.identifier, fname); end end return; end % and add the line number to make this unique for the last function fname = horzcat(fname, line); if ~issubfield('ft_default.warning.stopwatch', fname) ft_default.warning.stopwatch = setsubfield(ft_default.warning.stopwatch, fname, tic); end now = toc(getsubfield(ft_default.warning.stopwatch, fname)); % measure time since first function call if ~issubfield(ft_default.warning.identifier, fname) || ... (issubfield(ft_default.warning.identifier, fname) && now>getsubfield(ft_default.warning.identifier, [fname '.timeout'])) % create or reset field ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, fname, []); % warning never given before or timed out ws = warning(warningArgs{:}); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.timeout'], now+timeout); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.ws'], msg); warned = true; else % the warning has been issued before, but has not timed out yet ws = getsubfield(ft_default.warning.identifier, [fname '.ws']); end end % function ft_warning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fname, ft_previous_warnings, line] = fieldnameFromStack(ft_previous_warnings) % stack(1) is this function, stack(2) is ft_warning stack = dbstack('-completenames'); if size(stack) < 3 fname = []; line = []; return; end i0 = 3; % ignore ft_preamble while strfind(stack(i0).name, 'ft_preamble') i0=i0+1; end fname = horzcat(fixname(stack(end).name)); if ~issubfield(ft_previous_warnings, fixname(stack(end).name)) ft_previous_warnings.(fixname(stack(end).name)) = []; % iteratively build up structure fields end for i=numel(stack)-1:-1:(i0) % skip postamble scripts if strncmp(stack(i).name, 'ft_postamble', 12) break; end fname = horzcat(fname, '.', horzcat(fixname(stack(i).name))); % , stack(i).file if ~issubfield(ft_previous_warnings, fname) % iteratively build up structure fields setsubfield(ft_previous_warnings, fname, []); end end % line of last function call line = ['.line', int2str(stack(i0).line)]; end % function outcome = issubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % outcome = eval(['isfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % outcome = isfield(strct, fname); % end % end % function strct = rmsubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % strct = eval(['rmfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % strct = rmfield(strct, fname); % end % end
github
lcnbeapp/beapp-master
mesh2edge.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/private/mesh2edge.m
3,713
utf_8
410baaa2ca114acab82443de9a844a68
function [newbnd] = mesh2edge(bnd) % MESH2EDGE finds the edge lines from a triangulated mesh or the edge % surfaces from a tetrahedral or hexahedral mesh. An edge is defined as an % element that does not border any other element. This also implies that a % closed triangulated surface has no edges. % % Use as % [edge] = mesh2edge(mesh) % % See also POLY2TRI % Copyright (C) 2013-2015, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if isfield(bnd, 'tri') % make a list of all edges edge1 = bnd.tri(:, [1 2]); edge2 = bnd.tri(:, [2 3]); edge3 = bnd.tri(:, [3 1]); edge = cat(1, edge1, edge2, edge3); elseif isfield(bnd, 'tet') % make a list of all triangles that form the tetraheder tri1 = bnd.tet(:, [1 2 3]); tri2 = bnd.tet(:, [2 3 4]); tri3 = bnd.tet(:, [3 4 1]); tri4 = bnd.tet(:, [4 1 2]); edge = cat(1, tri1, tri2, tri3, tri4); elseif isfield(bnd, 'hex') % make a list of all "squares" that form the cube/hexaheder % FIXME should be checked, this is impossible without a drawing square1 = bnd.hex(:, [1 2 3 4]); square2 = bnd.hex(:, [5 6 7 8]); square3 = bnd.hex(:, [1 2 6 5]); square4 = bnd.hex(:, [2 3 7 6]); square5 = bnd.hex(:, [3 4 8 7]); square6 = bnd.hex(:, [4 1 5 8]); edge = cat(1, square1, square2, square3, square4, square5, square6); end % isfield(bnd) % soort all polygons in the same direction % keep the original as "edge" and the sorted one as "sedge" sedge = sort(edge, 2); % % find the edges that are not shared -> count the number of occurences % n = size(sedge,1); % occurences = ones(n,1); % for i=1:n % for j=(i+1):n % if all(sedge(i,:)==sedge(j,:)) % occurences(i) = occurences(i)+1; % occurences(j) = occurences(j)+1; % end % end % end % % % make the selection in the original, not the sorted version of the edges % % otherwise the orientation of the edges might get flipped % edge = edge(occurences==1,:); % find the edges that are not shared indx = findsingleoccurringrows(sedge); edge = edge(indx, :); % replace pnt by pos bnd = fixpos(bnd); % the naming of the output edges depends on what they represent newbnd.pos = bnd.pos; if isfield(bnd, 'tri') % these have two vertices in each edge element newbnd.line = edge; elseif isfield(bnd, 'tet') % these have three vertices in each edge element newbnd.tri = edge; elseif isfield(bnd, 'hex') % these have four vertices in each edge element newbnd.poly = edge; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION, see http://bugzilla.fcdonders.nl/show_bug.cgi?id=1833#c12 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function indx = findsingleoccurringrows(X) [X, indx] = sortrows(X); sel = any(diff([X(1,:)-1; X],1),2) & any(diff([X; X(end,:)+1],1),2); indx = indx(sel); function indx = finduniquerows(X) [X, indx] = sortrows(X); sel = any(diff([X(1,:)-1; X],1),2); indx = indx(sel);
github
lcnbeapp/beapp-master
intersect_plane.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/private/intersect_plane.m
2,842
utf_8
b975e248e2a82787c16084c79547fd9d
function [X, Y, Z, pnt1, tri1, pnt2, tri2] = intersect_plane(pnt, tri, v1, v2, v3) % INTERSECT_PLANE intersection between a triangulated surface and a plane % it returns the coordinates of the vertices which form a contour % % Use as % [X, Y, Z] = intersect_plane(pnt, tri, v1, v2, v3) % % where the intersecting plane is spanned by the vertices v1, v2, v3 % and the return values are each Nx2 for the N line segments. % Copyright (C) 2002-2012, Robert Oostenveld % % $Id$ npnt = size(pnt,1); ntri = size(tri,1); % side = zeros(npnt,1); % for i=1:npnt % side(i) = ptriside(v1, v2, v3, pnt(i,:)); % end side = ptriside(v1, v2, v3, pnt); % find the triangles which have vertices on both sides of the plane indx = find(abs(sum(side(tri),2))~=3); cnt1 = zeros(length(indx), 3); cnt2 = zeros(length(indx), 3); for i=1:length(indx) cur = tri(indx(i),:); tmp = side(cur); l1 = pnt(cur(1),:); l2 = pnt(cur(2),:); l3 = pnt(cur(3),:); if tmp(1)==tmp(2) % plane intersects two sides of the triangle cnt1(i,:) = ltrisect(v1, v2, v3, l3, l1); cnt2(i,:) = ltrisect(v1, v2, v3, l3, l2); elseif tmp(1)==tmp(3) cnt1(i,:) = ltrisect(v1, v2, v3, l2, l1); cnt2(i,:) = ltrisect(v1, v2, v3, l2, l3); elseif tmp(2)==tmp(3) cnt1(i,:) = ltrisect(v1, v2, v3, l1, l2); cnt2(i,:) = ltrisect(v1, v2, v3, l1, l3); elseif tmp(1)==0 && tmp(2)==0 % two vertices of the triangle lie on the plane cnt1(i,:) = l1; cnt2(i,:) = l2; elseif tmp(1)==0 && tmp(3)==0 cnt1(i,:) = l1; cnt2(i,:) = l3; elseif tmp(2)==0 && tmp(3)==0 cnt1(i,:) = l2; cnt2(i,:) = l3; elseif tmp(1)==0 && tmp(2)~=tmp(3) % one vertex of the triangle lies on the plane cnt1(i,:) = l1; cnt2(i,:) = ltrisect(v1, v2, v3, l2, l3); elseif tmp(2)==0 && tmp(3)~=tmp(1) cnt1(i,:) = l2; cnt2(i,:) = ltrisect(v1, v2, v3, l3, l1); elseif tmp(3)==0 && tmp(1)~=tmp(2) cnt1(i,:) = l3; cnt2(i,:) = ltrisect(v1, v2, v3, l1, l2); elseif tmp(1)==0 cnt1(i,:) = l1; cnt2(i,:) = l1; elseif tmp(2)==0 cnt1(i,:) = l2; cnt2(i,:) = l2; elseif tmp(3)==0 cnt1(i,:) = l3; cnt2(i,:) = l3; end end X = [cnt1(:,1) cnt2(:,1)]; Y = [cnt1(:,2) cnt2(:,2)]; Z = [cnt1(:,3) cnt2(:,3)]; if nargout>3 % also output the two meshes on either side of the plane indx1 = find(side==1); pnt1 = pnt(indx1,:); sel1 = sum(ismember(tri, indx1), 2)==3; tri1 = tri(sel1,:); tri1 = tri_reindex(tri1); indx2 = find(side==-1); pnt2 = pnt(indx2,:); sel2 = sum(ismember(tri, indx2), 2)==3; tri2 = tri(sel2,:); tri2 = tri_reindex(tri2); end function [newtri] = tri_reindex(tri) %this function reindexes tri such that they run from 1:number of unique vertices newtri = tri; [srt, indx] = sort(tri(:)); tmp = cumsum(double(diff([0;srt])>0)); newtri(indx) = tmp;
github
lcnbeapp/beapp-master
inside_contour.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/plotting/private/inside_contour.m
1,105
utf_8
6554af9f8bc2dc7512e8ca962a63688b
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
lcnbeapp/beapp-master
enginecellfun.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/engine/enginecellfun.m
11,478
utf_8
3cd2f39f096029c7a0cdfa80414a36bf
function varargout = enginecellfun(fname, varargin) % ENGINECELLFUN applies a function to each element of a cell-array. The function % execution is done in parallel on locally or remotely running MATLAB engines. % % Use as % argout = enginecellfun(fname, x1, x2, ...) % % Optional arguments can be specified in key-value pairs and can include % UniformOutput = boolean (default = false) % StopOnError = boolean (default = true) % diary = string, can be 'always', 'never', 'warning', 'error' (default = 'error') % order = string, can be 'random' or 'original' (default = 'random') % % Example % x1 = {1, 2, 3, 4, 5}; % x2 = {2, 2, 2, 2, 2}; % enginepool open 4 % y = enginecellfun(@power, x1, x2); % enginepool close % % See also ENGINEPOOL, ENGINEFEVAL, ENGINEGET % ----------------------------------------------------------------------- % Copyright (C) 2012, Robert Oostenveld % % This program is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program. If not, see <http://www.gnu.org/licenses/ % % $Id$ % ----------------------------------------------------------------------- if ft_platform_supports('onCleanup') % switch to zombie when finished or when ctrl-c gets pressed % the onCleanup function does not exist for older versions onCleanup(@cleanupfun); end % locate the begin of the optional key-value arguments optbeg = find(cellfun(@ischar, varargin)); optarg = varargin(optbeg:end); % get the optional input arguments UniformOutput = ft_getopt(optarg, 'UniformOutput', false ); StopOnError = ft_getopt(optarg, 'StopOnError', true ); diary = ft_getopt(optarg, 'diary', 'error' ); % 'always', 'never', 'warning', 'error' order = ft_getopt(optarg, 'order', 'original'); % 'random', 'original' % convert from 'yes'/'no' into boolean value UniformOutput = istrue(UniformOutput); % skip the optional key-value arguments if ~isempty(optbeg) varargin = varargin(1:(optbeg-1)); end if isa(fname, 'function_handle') % convert the function handle back into a string (e.g. @plus should be 'plus') fname = func2str(fname); end % there are potentially errors to catch from the which() function if isempty(which(fname)) error('Not a valid M-file (%s).', fname); end % determine the number of input arguments and the number of jobs numargin = numel(varargin); numjob = numel(varargin{1}); % it can be difficult to determine the number of output arguments try numargout = nargout(fname); catch % the "catch me" syntax is broken on MATLAB74, this fixes it nargout_err = lasterror; if strcmp(nargout_err.identifier, 'MATLAB:narginout:doesNotApply') % e.g. in case of nargin('plus') numargout = 1; else rethrow(nargout_err); end end if numargout<0 % the nargout function returns -1 in case of a variable number of output arguments numargout = 1; elseif numargout>nargout % the number of output arguments is constrained by the users' call to this function numargout = nargout; elseif nargout>numargout error('Too many output arguments.'); end % check the input arguments for i=1:numargin if ~isa(varargin{i}, 'cell') error('input argument #%d should be a cell-array', i+1); end if numel(varargin{i})~=numjob error('inconsistent number of elements in input #%d', i+1); end end % check the availability of the engines pool = enginepool('info'); pool = enginepool('info'); isbusy = false(1,numel(pool)); hasjob = false(1,numel(pool)); for i=1:numel(pool) isbusy(i) = engine('isbusy', i); hasjob(i) = ~isempty(pool{i}); end if isempty(pool) error('the engine pool is empty'); end if all(isbusy) warning('there is no engine available, reverting to local cellfun'); % prepare the output arguments varargout = cell(1,numargout); % use the standard cellfun [varargout{:}] = cellfun(str2func(fname), varargin{:}, 'UniformOutput', UniformOutput); return end % prepare some arrays that are used for bookkeeping jobid = nan(1, numjob); puttime = nan(1, numjob); timused = nan(1, numjob); memused = nan(1, numjob); submitted = false(1, numjob); collected = false(1, numjob); busy = false(1, numjob); lastseen = inf(1, numjob); submittime = inf(1, numjob); collecttime = inf(1, numjob); % remove any remains from an aborted previous call cleanupfun % start the timer stopwatch = tic; % these are used for printing feedback on screen prevnumsubmitted = 0; prevnumcollected = 0; prevnumbusy = 0; % determine the initial job order, small numbers are submitted first if strcmp(order, 'random') priority = randperm(numjob); elseif strcmp(order, 'original') priority = 1:numjob; else error('unsupported order'); end % post all jobs and gather their results while ~all(submitted) || ~all(collected) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % PART 1: submit the jobs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% pool = enginepool('info'); isbusy = false(1,numel(pool)); hasjob = false(1,numel(pool)); for i=1:numel(pool) isbusy(i) = engine('isbusy', i); hasjob(i) = ~isempty(pool{i}); end % try to submit as many jobs as possible for submit = find(~submitted); if all(hasjob | isbusy) % all engines are busy, we have to wait for and collect some results before submitting new jobs break end % redistribute the input arguments argin = cell(1, numargin); for j=1:numargin argin{j} = varargin{j}{submit}; end % submit the job for execution [curjobid curputtime] = enginefeval(fname, argin{:}, 'diary', diary, 'nargout', numargout); if ~isempty(curjobid) % fprintf('submitted job %d\n', submit); jobid(submit) = curjobid; puttime(submit) = curputtime; submitted(submit) = true; submittime(submit) = toc(stopwatch); clear curjobid curputtime end clear argin % check the availability of the engines pool = enginepool('info'); isbusy = false(1,numel(pool)); hasjob = false(1,numel(pool)); for i=1:numel(pool) isbusy(i) = engine('isbusy', i); hasjob(i) = ~isempty(pool{i}); end end % while not all engines are busy if sum(collected)>prevnumcollected || sum(isbusy)~=prevnumbusy % give an update of the progress fprintf('submitted %d/%d, collected %d/%d, busy %d, speedup %.1f\n', sum(submitted), numel(submitted), sum(collected), numel(collected), sum(isbusy), nansum(timused(collected))/toc(stopwatch)); end prevnumcollected = sum(collected); prevnumbusy = sum(isbusy); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % PART 2: collect the job results that have finished sofar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % try to collect as many jobs as possible for ready = find(hasjob & ~isbusy) % figure out to which job this engines result belong collect = find(jobid == pool{ready}); % collect the output arguments ws = warning('Off','Backtrace'); [argout, options] = engineget(pool{ready}, 'output', 'cell', 'diary', diary, 'StopOnError', StopOnError); warning(ws); % fprintf('collected job %d\n', collect); collected(collect) = true; collecttime(collect) = toc(stopwatch); % redistribute the output arguments for j=1:numargout varargout{j}{collect} = argout{j}; end % gather the job statistics % these are empty in case an error happened during remote evaluation, therefore the default value of NaN is specified timused(collect) = ft_getopt(options, 'timused', nan); memused(collect) = ft_getopt(options, 'memused', nan); end % collect the selected job if sum(collected)>prevnumcollected % give an update of the progress fprintf('submitted %d/%d, collected %d/%d, busy %d, speedup %.1f\n', sum(submitted), numel(submitted), sum(collected), numel(collected), sum(isbusy), nansum(timused(collected))/toc(stopwatch)); end if all(isbusy) % wait a little bit for the running jobs to complete pause(0.1); end prevnumcollected = sum(collected); prevnumbusy = sum(isbusy); end % while not all jobs have finished if numargout>0 && UniformOutput % check whether the output can be converted to a uniform one for i=1:numel(varargout) for j=1:numel(varargout{i}) if numel(varargout{i}{j})~=1 % this error message is consistent with the one from cellfun error('Non-scalar in Uniform output, at index %d, output %d. Set ''UniformOutput'' to false.', j, i); end end end % convert the output to a uniform one for i=1:numargout varargout{i} = [varargout{i}{:}]; end end % ensure the output to have the same size/dimensions as the input for i=1:numargout varargout{i} = reshape(varargout{i}, size(varargin{1})); end % compare the time used inside this function with the total execution time fprintf('computational time = %.1f sec, elapsed = %.1f sec, speedup %.1f x\n', nansum(timused), toc(stopwatch), nansum(timused)/toc(stopwatch)); if all(puttime>timused) % FIXME this could be detected in the loop above, and the strategy could automatically % be adjusted from using the engines to local execution warning('copying the jobs over the network took more time than their execution'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cleanupfun pool = enginepool('info'); for i=1:length(pool) enginepool('release', i); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nanmax(x) y = max(x(~isnan(x(:)))); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nanmin(x) y = min(x(~isnan(x(:)))); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nanmean(x) x = x(~isnan(x(:))); y = mean(x); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nanstd(x) x = x(~isnan(x(:))); y = std(x); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = nansum(x) x = x(~isnan(x(:))); y = sum(x);
github
lcnbeapp/beapp-master
ft_platform_supports.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/engine/private/ft_platform_supports.m
9,557
utf_8
eb0e55d84d57e6873cce8df6cad90d96
function tf = ft_platform_supports(what,varargin) % FT_PLATFORM_SUPPORTS returns a boolean indicating whether the current platform % supports a specific capability % % Usage: % tf = ft_platform_supports(what) % tf = ft_platform_supports('matlabversion', min_version, max_version) % % The following values are allowed for the 'what' parameter: % value means that the following is supported: % % 'which-all' which(...,'all') % 'exists-in-private-directory' exists(...) will look in the /private % subdirectory to see if a file exists % 'onCleanup' onCleanup(...) % 'alim' alim(...) % 'int32_logical_operations' bitand(a,b) with a, b of type int32 % 'graphics_objects' graphics sysem is object-oriented % 'libmx_c_interface' libmx is supported through mex in the % C-language (recent Matlab versions only % support C++) % 'stats' all statistical functions in % FieldTrip's external/stats directory % 'program_invocation_name' program_invocation_name() (GNU Octave) % 'singleCompThread' start Matlab with -singleCompThread % 'nosplash' -nosplash % 'nodisplay' -nodisplay % 'nojvm' -nojvm % 'no-gui' start GNU Octave with --no-gui % 'RandStream.setGlobalStream' RandStream.setGlobalStream(...) % 'RandStream.setDefaultStream' RandStream.setDefaultStream(...) % 'rng' rng(...) % 'rand-state' rand('state') % 'urlread-timeout' urlread(..., 'Timeout', t) % 'griddata-vector-input' griddata(...,...,...,a,b) with a and b % vectors % 'griddata-v4' griddata(...,...,...,...,...,'v4'), % that is v4 interpolation support % 'uimenu' uimenu(...) if ~ischar(what) error('first argument must be a string'); end switch what case 'matlabversion' tf = is_matlab() && matlabversion(varargin{:}); case 'exists-in-private-directory' tf = is_matlab(); case 'which-all' tf = is_matlab(); case 'onCleanup' tf = is_octave() || matlabversion(7.8, Inf); case 'alim' tf = is_matlab(); case 'int32_logical_operations' % earlier version of Matlab don't support bitand (and similar) % operations on int32 tf = is_octave() || ~matlabversion(-inf, '2012a'); case 'graphics_objects' % introduced in Matlab 2014b, graphics is handled through objects; % previous versions use numeric handles tf = is_matlab() && matlabversion('2014b', Inf); case 'libmx_c_interface' % removed after 2013b tf = matlabversion(-Inf, '2013b'); case 'stats' root_dir=fileparts(which('ft_defaults')); external_stats_dir=fullfile(root_dir,'external','stats'); % these files are only used by other functions in the external/stats % directory exclude_mfiles={'common_size.m',... 'iscomplex.m',... 'lgamma.m'}; tf = has_all_functions_in_dir(external_stats_dir,exclude_mfiles); case 'program_invocation_name' % Octave supports program_invocation_name, which returns the path % of the binary that was run to start Octave tf = is_octave(); case 'singleCompThread' tf = is_matlab() && matlabversion(7.8, inf); case {'nosplash','nodisplay','nojvm'} % Only on Matlab tf = is_matlab(); case 'no-gui' % Only on Octave tf = is_octave(); case 'RandStream.setDefaultStream' tf = is_matlab() && matlabversion('2008b', '2011b'); case 'RandStream.setGlobalStream' tf = is_matlab() && matlabversion('2012a', inf); case 'randomized_PRNG_on_startup' tf = is_octave() || ~matlabversion(-Inf,'7.3'); case 'rng' % recent Matlab versions tf = is_matlab() && matlabversion('7.12',Inf); case 'rand-state' % GNU Octave tf = is_octave(); case 'urlread-timeout' tf = is_matlab() && matlabversion('2012b',Inf); case 'griddata-vector-input' tf = is_matlab(); case 'griddata-v4' tf = is_matlab() && matlabversion('2009a',Inf); case 'uimenu' tf = is_matlab(); otherwise error('unsupported value for first argument: %s', what); end % switch end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_matlab() tf = ~is_octave(); end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_octave() persistent cached_tf; if isempty(cached_tf) cached_tf = logical(exist('OCTAVE_VERSION', 'builtin')); end tf = cached_tf; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = has_all_functions_in_dir(in_dir, exclude_mfiles) % returns true if all functions in in_dir are already provided by the % platform m_files=dir(fullfile(in_dir,'*.m')); n=numel(m_files); for k=1:n m_filename=m_files(k).name; if isempty(which(m_filename)) && ... isempty(strmatch(m_filename,exclude_mfiles)) tf=false; return; end end tf=true; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 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(6, '7.10') % is version between 6 and 7.10? (note: '7.10', not 7.10) % matlabversion(-Inf, 7.6) % is version <= 7.6? % matlabversion('2009b') % exactly 2009b % matlabversion('2008b', '2010a') % between two versions % matlabversion('2008b', Inf) % from a version onwards % etc. % % See also VERSION, VER, VERLESSTHAN % Copyright (C) 2006, Robert Oostenveld % Copyright (C) 2010, Eelke Spaak % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this does not change over subsequent calls, making it persistent speeds it up persistent curVer if nargin<2 max = min; end if isempty(curVer) curVer = version(); end 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 end % function 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 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 % function % 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 % function
github
lcnbeapp/beapp-master
ft_warning.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/engine/private/ft_warning.m
7,789
utf_8
d832a7ad5e2f9bb42995e6e5d4caa198
function [ws, warned] = ft_warning(varargin) % FT_WARNING will throw a warning for every unique point in the % stacktrace only, e.g. in a for-loop a warning is thrown only once. % % Use as one of the following % ft_warning(string) % ft_warning(id, string) % Alternatively, you can use ft_warning using a timeout % ft_warning(string, timeout) % ft_warning(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. % % Use as ft_warning('-clear') to clear old warnings from the current % stack % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = ft_warning(...) % or as % ft_warning(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, ft_warning accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = ft_warning(...) % where w is a boolean that indicates whether a warning as been thrown or not. % % Please note that you can NOT use it like this % ft_warning('the value is %d', 10) % instead you should do % ft_warning(sprintf('the value is %d', 10)) % Copyright (C) 2012-2016, Robert Oostenveld, J?rn M. Horschig % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ global ft_default warned = false; ws = []; stack = dbstack; if any(strcmp({stack(2:end).file}, 'ft_warning.m')) % don't call FT_WARNING recursively, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3068 return; end if nargin < 1 error('You need to specify at least a warning message'); end if isstruct(varargin{1}) warning(varargin{1}); return; end if ~isfield(ft_default, 'warning') ft_default.warning = []; end if ~isfield(ft_default.warning, 'stopwatch') ft_default.warning.stopwatch = []; end if ~isfield(ft_default.warning, 'identifier') ft_default.warning.identifier = []; end if ~isfield(ft_default.warning, 'ignore') ft_default.warning.ignore = {}; end % put the arguments we will pass to warning() in this cell array warningArgs = {}; if nargin==3 % calling syntax (id, msg, timeout) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); msg = warningArgs{1}; timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && isequal(varargin{1}, 'off') ft_default.warning.ignore = union(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && isequal(varargin{1}, 'on') ft_default.warning.ignore = setdiff(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = inf; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); msg = warningArgs{1}; timeout = inf; % default timeout in seconds fname = [warningArgs{1}]; end if ismember(msg, ft_default.warning.ignore) % do not show this warning return; end if isempty(timeout) error('Timeout ill-specified'); end if timeout ~= inf fname = fixname(fname); % make a nice string that is allowed as fieldname in a structures line = []; else % here, we create the fieldname functionA.functionB.functionC... [tmpfname, ft_default.warning.identifier, line] = fieldnameFromStack(ft_default.warning.identifier); if ~isempty(tmpfname), fname = tmpfname; clear tmpfname; end end if nargin==1 && ischar(varargin{1}) && strcmp('-clear', varargin{1}) if strcmp(fname, '-clear') % reset all fields if called outside a function ft_default.warning.identifier = []; ft_default.warning.stopwatch = []; else if issubfield(ft_default.warning.identifier, fname) ft_default.warning.identifier = rmsubfield(ft_default.warning.identifier, fname); end end return; end % and add the line number to make this unique for the last function fname = horzcat(fname, line); if ~issubfield('ft_default.warning.stopwatch', fname) ft_default.warning.stopwatch = setsubfield(ft_default.warning.stopwatch, fname, tic); end now = toc(getsubfield(ft_default.warning.stopwatch, fname)); % measure time since first function call if ~issubfield(ft_default.warning.identifier, fname) || ... (issubfield(ft_default.warning.identifier, fname) && now>getsubfield(ft_default.warning.identifier, [fname '.timeout'])) % create or reset field ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, fname, []); % warning never given before or timed out ws = warning(warningArgs{:}); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.timeout'], now+timeout); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.ws'], msg); warned = true; else % the warning has been issued before, but has not timed out yet ws = getsubfield(ft_default.warning.identifier, [fname '.ws']); end end % function ft_warning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fname, ft_previous_warnings, line] = fieldnameFromStack(ft_previous_warnings) % stack(1) is this function, stack(2) is ft_warning stack = dbstack('-completenames'); if size(stack) < 3 fname = []; line = []; return; end i0 = 3; % ignore ft_preamble while strfind(stack(i0).name, 'ft_preamble') i0=i0+1; end fname = horzcat(fixname(stack(end).name)); if ~issubfield(ft_previous_warnings, fixname(stack(end).name)) ft_previous_warnings.(fixname(stack(end).name)) = []; % iteratively build up structure fields end for i=numel(stack)-1:-1:(i0) % skip postamble scripts if strncmp(stack(i).name, 'ft_postamble', 12) break; end fname = horzcat(fname, '.', horzcat(fixname(stack(i).name))); % , stack(i).file if ~issubfield(ft_previous_warnings, fname) % iteratively build up structure fields setsubfield(ft_previous_warnings, fname, []); end end % line of last function call line = ['.line', int2str(stack(i0).line)]; end % function outcome = issubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % outcome = eval(['isfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % outcome = isfield(strct, fname); % end % end % function strct = rmsubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % strct = eval(['rmfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % strct = rmfield(strct, fname); % end % end
github
lcnbeapp/beapp-master
ft_specest_mtmconvol.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/specest/ft_specest_mtmconvol.m
21,073
utf_8
b5608f0bb24aca60fd1c5df6e8299018
function [spectrum,ntaper,freqoi,timeoi] = ft_specest_mtmconvol(dat, time, varargin) % FT_SPECEST_MTMCONVOL performs wavelet convolution in the time domain by % multiplication in the frequency domain. % % Use as % [spectrum,ntaper,freqoi,timeoi] = ft_specest_mtmconvol(dat,time,...) % where input % dat = matrix of chan*sample % time = vector, containing time in seconds for each sample % and output % 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 % padtype = string, indicating type of padding to be used (see ft_preproc_padding, default: zero) % 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) % taperopt = additional taper options to be used in the WINDOW function, see WINDOW % polyorder = number, the order of the polynomial to fitted to and removed from the data prior to the fourier transform (default = 0 -> remove DC-component) % % See also FT_FREQANALYSIS, FT_SPECEST_MTMFFT, FT_SPECEST_TFR, FT_SPECEST_HILBERT, FT_SPECEST_WAVELET % Copyright (C) 2010, Donders Institute for Brain, Cognition and Behaviour % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are for speeding up computation of tapers on subsequent calls persistent previous_argin previous_wltspctrm % get the optional input arguments taper = ft_getopt(varargin, 'taper', 'dpss'); pad = ft_getopt(varargin, 'pad'); padtype = ft_getopt(varargin, 'padtype', 'zero'); timeoi = ft_getopt(varargin, 'timeoi', 'all'); timwin = ft_getopt(varargin, 'timwin'); freqoi = ft_getopt(varargin, 'freqoi', 'all'); tapsmofrq = ft_getopt(varargin, 'tapsmofrq'); dimord = ft_getopt(varargin, 'dimord', 'tap_chan_freq_time'); fbopt = ft_getopt(varargin, 'feedback'); verbose = ft_getopt(varargin, 'verbose', true); polyorder = ft_getopt(varargin, 'polyorder', 0); tapopt = ft_getopt(varargin, 'taperopt'); 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); % This does not work on integer data typ = class(dat); if ~strcmp(typ, 'double') && ~strcmp(typ, 'single') dat = cast(dat, 'double'); end % 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./mean(diff(time)); 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 = 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 freqoiinput = freqoi; if isnumeric(freqoi) % if input is a vector freqboi = round(freqoi ./ (fsample ./ endnsample)) + 1; % is equivalent to: round(freqoi .* endtime) + 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); % throw a warning if input freqoi is different from output freqoi if isnumeric(freqoiinput) % check whether padding is appropriate for the requested frequency resolution rayl = 1/endtime; if any(rem(freqoiinput,rayl)) ft_warning('padding not sufficient for requested frequency resolution, for more information please see the FAQs on www.ru.nl/neuroimaging/fieldtrip'); end if numel(freqoiinput) ~= numel(freqoi) % freqoi will not contain double frequency bins when requested ft_warning('output frequencies are different from input frequencies, multiples of the same bin were requested but not given'); else if any(abs(freqoiinput-freqoi) >= eps*1e6) ft_warning('output frequencies are different from input frequencies'); end end end % Set timeboi and timeoi timeoiinput = timeoi; offset = round(time(1)*fsample); if isnumeric(timeoi) % if input is a vector timeoi = unique(round(timeoi .* fsample) ./ fsample); timeboi = round(timeoi .* fsample - offset) + 1; ntimeboi = length(timeboi); elseif strcmp(timeoi,'all') % if input was 'all' timeboi = 1:length(time); ntimeboi = length(timeboi); timeoi = time; end % throw a warning if input timeoi is different from output timeoi if isnumeric(timeoiinput) if numel(timeoiinput) ~= numel(timeoi) % timeoi will not contain double time-bins when requested ft_warning('output time-bins are different from input time-bins, multiples of the same bin were requested but not given'); else if any(abs(timeoiinput-timeoi) >= eps*1e6) ft_warning('output time-bins are different from input time-bins'); end end end % set number of samples per time-window (timwin is in seconds) if numel(timwin)==1 && nfreqoi~=1 timwin = repmat(timwin,[1 nfreqoi]); end timwinsample = round(timwin .* fsample); % determine whether tapers need to be recomputed current_argin = {time, postpad, taper, timwinsample, tapsmofrq, freqoi, timeoi, tapopt}; % reasoning: if time and postpad are equal, it's the same length trial, if the rest is equal then the requested output is equal if isequal(current_argin, previous_argin) % don't recompute tapers wltspctrm = previous_wltspctrm; ntaper = cellfun(@size,wltspctrm,repmat({1},[1 nfreqoi])'); else % recompute 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 if isempty(tapopt) % some windowing functions don't support nargin>1, and window.m doesn't check it tap = window(taper, timwinsample(ifreqoi))'; else tap = window(taper, timwinsample(ifreqoi),tapopt)'; end 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 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 = fft(ft_preproc_padding(dat, padtype, 0, postpad), [], 2); 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(ifft(datspectrum .* repmat(wltspctrm{ifreqoi}(itap,:),[nchan 1]), [], 2),2); % fftshift is necessary to implement zero-phase/acyclic/acausal convolution (either here, or the wavelet should be wrapped around sample=0) 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 = cell(1,nfreqoi); tempntaper = [0; cumsum(ntaper(:))]; for ifreqoi = 1:nfreqoi freqtapind{ifreqoi} = tempntaper(ifreqoi)+1:tempntaper(ifreqoi+1); end % start fft'ing datspectrum = fft(ft_preproc_padding(dat, padtype, 0, postpad), [], 2); 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(ifft(datspectrum .* repmat(wltspctrm{ifreqoi}(itap,:),[nchan 1]), [], 2),2); % fftshift is necessary to implement zero-phase/acyclic/acausal convolution (either here, or the wavelet should be wrapped around sample=0) 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 % remember the current input arguments, so that they can be % reused on a subsequent call in case the same input argument is given previous_argin = current_argin; previous_wltspctrm = wltspctrm; % % 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 % % NOTE: double explicit transpose around fft is not faster than using fft % with dim argument (in fact, it is slower) % 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)); % %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
lcnbeapp/beapp-master
ft_specest_mtmfft.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/specest/ft_specest_mtmfft.m
14,511
utf_8
b163b64586570687c72bc376ea856ea1
function [spectrum,ntaper,freqoi] = ft_specest_mtmfft(dat, time, varargin) % FT_SPECEST_MTMFFT computes a fast Fourier transform using multitapering with % multiple tapers from the DPSS sequence or using a variety of single tapers. % % Use as % [spectrum,ntaper,freqoi] = ft_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) % padtype = string, indicating type of padding to be used (see ft_preproc_padding, default: zero) % 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 % dimord = 'tap_chan_freq' (default) or 'chan_time_freqtap' for memory efficiency (only when use variable number slepian tapers) % polyorder = number, the order of the polynomial to fitted to and removed from the data prior to the fourier transform (default = 0 -> remove DC-component) % taperopt = additional taper options to be used in the WINDOW function, see WINDOW % verbose = output progress to console (0 or 1, default 1) % % See also FT_FREQANALYSIS, FT_SPECEST_MTMCONVOL, FT_SPECEST_TFR, FT_SPECEST_HILBERT, FT_SPECEST_WAVELET % Copyright (C) 2010, Donders Institute for Brain, Cognition and Behaviour % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are for speeding up computation of tapers on subsequent calls persistent previous_argin previous_tap % get the optional input arguments taper = ft_getopt(varargin, 'taper'); if isempty(taper), error('You must specify a taper'); end pad = ft_getopt(varargin, 'pad'); padtype = ft_getopt(varargin, 'padtype', 'zero'); freqoi = ft_getopt(varargin, 'freqoi', 'all'); tapsmofrq = ft_getopt(varargin, 'tapsmofrq'); dimord = ft_getopt(varargin, 'dimord', 'tap_chan_freq'); fbopt = ft_getopt(varargin, 'feedback'); verbose = ft_getopt(varargin, 'verbose', true); polyorder = ft_getopt(varargin, 'polyorder', 0); tapopt = ft_getopt(varargin, 'taperopt'); 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 % this does not work on integer data dat = cast(dat, 'double'); % Set n's [nchan,ndatsample] = size(dat); % This does not work on integer data typ = class(dat); if ~strcmp(typ, 'double') && ~strcmp(typ, 'single') dat = cast(dat, 'double'); end % 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./mean(diff(time)); 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 = 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 freqoiinput = freqoi; if isnumeric(freqoi) % if input is a vector freqboi = round(freqoi ./ (fsample ./ endnsample)) + 1; % is equivalent to: round(freqoi .* endtime) + 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); if strcmp(taper, 'dpss') && numel(tapsmofrq)~=1 && (numel(tapsmofrq)~=nfreqoi) error('tapsmofrq needs to contain a smoothing parameter for every frequency when requesting variable number of slepian tapers') end % throw a warning if input freqoi is different from output freqoi if isnumeric(freqoiinput) % check whether padding is appropriate for the requested frequency resolution rayl = 1/endtime; if any(rem(freqoiinput,rayl)) % not always the case when they mismatch ft_warning('padding not sufficient for requested frequency resolution, for more information please see the FAQs on www.ru.nl/neuroimaging/fieldtrip'); end if numel(freqoiinput) ~= numel(freqoi) % freqoi will not contain double frequency bins when requested ft_warning('output frequencies are different from input frequencies, multiples of the same bin were requested but not given'); else if any(abs(freqoiinput-freqoi) >= eps*1e6) ft_warning('output frequencies are different from input frequencies'); end end end % determine whether tapers need to be recomputed current_argin = {time, postpad, taper, tapsmofrq, freqoi, tapopt, dimord}; % reasoning: if time and postpad are equal, it's the same length trial, if the rest is equal then the requested output is equal if isequal(current_argin, previous_argin) % don't recompute tapers tap = previous_tap; else % recompute tapers switch taper case 'dpss' if numel(tapsmofrq)==1 % 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 ft_warning('using only one taper for specified smoothing'); end elseif numel(tapsmofrq)>1 tap = cell(1,nfreqoi); for ifreqoi = 1:nfreqoi % create a sequence of DPSS tapers, ensure that the input arguments are double precision currtap = double_dpss(ndatsample, ndatsample .* (tapsmofrq(ifreqoi) ./ fsample))'; % remove the last taper because the last slepian taper is always messy currtap = currtap(1:(end-1), :); % give error/warning about number of tapers if isempty(currtap) error('%.3f Hz: datalength to short for specified smoothing\ndatalength: %.3f s, smoothing: %.3f Hz, minimum smoothing: %.3f Hz',freqoi(ifreqoi), ndatsample/fsample,tapsmofrq(ifreqoi),fsample/ndatsample(ifreqoi)); elseif size(currtap,1) == 1 disp([num2str(freqoi(ifreqoi)) ' Hz: WARNING: using only one taper for specified smoothing']) end tap{ifreqoi} = currtap; end 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 if isempty(tapopt) % some windowing functions don't support nargin>1, and window.m doesn't check it tap = window(taper, ndatsample)'; else tap = window(taper, ndatsample, tapopt)'; end tap = tap ./ norm(tap,'fro'); end % switch taper end % isequal currargin % set ntaper if ~(strcmp(taper,'dpss') && numel(tapsmofrq)>1) % variable number of slepian tapers not requested ntaper = repmat(size(tap,1),nfreqoi,1); else % variable number of slepian tapers requested ntaper = cellfun(@size,tap,repmat({1},[1 nfreqoi])); 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) = atan2(sinwav, coswav); end angletransform = repmat(angletransform,[nchan,1]); end % compute fft if ~(strcmp(taper,'dpss') && numel(tapsmofrq)>1) % ariable number of slepian tapers not requested 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); elseif verbose fprintf([str, '\n']); end spectrum = cell(ntaper(1),1); for itap = 1:ntaper(1) dum = fft(ft_preproc_padding(bsxfun(@times,dat,tap(itap,:)), padtype, 0, postpad),[], 2); 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]); else % variable number of slepian tapers requested switch dimord case 'tap_chan_freq' % default % start fft'ing spectrum = complex(NaN([max(ntaper) nchan nfreqoi])); for ifreqoi = 1:nfreqoi str = sprintf('nfft: %d samples, datalength: %d samples, frequency %d (%.2f Hz), %d tapers',endnsample,ndatsample,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, ['processing trial %d, ',str,'\n'], fbopt.i); elseif verbose fprintf([str, '\n']); end for itap = 1:ntaper(ifreqoi) dum = fft(ft_preproc_padding(bsxfun(@times,dat,tap{ifreqoi}(itap,:)), padtype, 0, postpad), [], 2); dum = dum(:,freqboi(ifreqoi)); % phase-shift according to above angles if timedelay ~= 0 dum = dum .* exp(-1i*angletransform(:,ifreqoi)); end dum = dum .* sqrt(2 ./ endnsample); spectrum(itap,:,ifreqoi) = dum; end end % for nfreqoi case 'chan_freqtap' % memory efficient representation % create tapfreqind freqtapind = cell(1,nfreqoi); tempntaper = [0; cumsum(ntaper(:))]; for ifreqoi = 1:nfreqoi freqtapind{ifreqoi} = tempntaper(ifreqoi)+1:tempntaper(ifreqoi+1); end % start fft'ing spectrum = complex(zeros([nchan sum(ntaper)])); for ifreqoi = 1:nfreqoi str = sprintf('nfft: %d samples, datalength: %d samples, frequency %d (%.2f Hz), %d tapers',endnsample,ndatsample,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, ['processing trial %d, ',str,'\n'], fbopt.i); elseif verbose fprintf([str, '\n']); end for itap = 1:ntaper(ifreqoi) dum = fft(ft_preproc_padding(bsxfun(@times,dat,tap{ifreqoi}(itap,:)), padtype, 0, postpad), [], 2); dum = dum(:,freqboi(ifreqoi)); % phase-shift according to above angles if timedelay ~= 0 dum = dum .* exp(-1i*angletransform(:,ifreqoi)); end dum = dum .* sqrt(2 ./ endnsample); spectrum(:,freqtapind{ifreqoi}(itap)) = dum; end end % for nfreqoi end % switch dimord end % remember the current input arguments, so that they can be % reused on a subsequent call in case the same input argument is given previous_argin = current_argin; previous_tap = tap; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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
lcnbeapp/beapp-master
ft_warning.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/specest/private/ft_warning.m
7,789
utf_8
d832a7ad5e2f9bb42995e6e5d4caa198
function [ws, warned] = ft_warning(varargin) % FT_WARNING will throw a warning for every unique point in the % stacktrace only, e.g. in a for-loop a warning is thrown only once. % % Use as one of the following % ft_warning(string) % ft_warning(id, string) % Alternatively, you can use ft_warning using a timeout % ft_warning(string, timeout) % ft_warning(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. % % Use as ft_warning('-clear') to clear old warnings from the current % stack % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = ft_warning(...) % or as % ft_warning(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, ft_warning accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = ft_warning(...) % where w is a boolean that indicates whether a warning as been thrown or not. % % Please note that you can NOT use it like this % ft_warning('the value is %d', 10) % instead you should do % ft_warning(sprintf('the value is %d', 10)) % Copyright (C) 2012-2016, Robert Oostenveld, J?rn M. Horschig % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ global ft_default warned = false; ws = []; stack = dbstack; if any(strcmp({stack(2:end).file}, 'ft_warning.m')) % don't call FT_WARNING recursively, see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3068 return; end if nargin < 1 error('You need to specify at least a warning message'); end if isstruct(varargin{1}) warning(varargin{1}); return; end if ~isfield(ft_default, 'warning') ft_default.warning = []; end if ~isfield(ft_default.warning, 'stopwatch') ft_default.warning.stopwatch = []; end if ~isfield(ft_default.warning, 'identifier') ft_default.warning.identifier = []; end if ~isfield(ft_default.warning, 'ignore') ft_default.warning.ignore = {}; end % put the arguments we will pass to warning() in this cell array warningArgs = {}; if nargin==3 % calling syntax (id, msg, timeout) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); msg = warningArgs{1}; timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && isequal(varargin{1}, 'off') ft_default.warning.ignore = union(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && isequal(varargin{1}, 'on') ft_default.warning.ignore = setdiff(ft_default.warning.ignore, varargin{2}); return elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); msg = warningArgs{2}; timeout = inf; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); msg = warningArgs{1}; timeout = inf; % default timeout in seconds fname = [warningArgs{1}]; end if ismember(msg, ft_default.warning.ignore) % do not show this warning return; end if isempty(timeout) error('Timeout ill-specified'); end if timeout ~= inf fname = fixname(fname); % make a nice string that is allowed as fieldname in a structures line = []; else % here, we create the fieldname functionA.functionB.functionC... [tmpfname, ft_default.warning.identifier, line] = fieldnameFromStack(ft_default.warning.identifier); if ~isempty(tmpfname), fname = tmpfname; clear tmpfname; end end if nargin==1 && ischar(varargin{1}) && strcmp('-clear', varargin{1}) if strcmp(fname, '-clear') % reset all fields if called outside a function ft_default.warning.identifier = []; ft_default.warning.stopwatch = []; else if issubfield(ft_default.warning.identifier, fname) ft_default.warning.identifier = rmsubfield(ft_default.warning.identifier, fname); end end return; end % and add the line number to make this unique for the last function fname = horzcat(fname, line); if ~issubfield('ft_default.warning.stopwatch', fname) ft_default.warning.stopwatch = setsubfield(ft_default.warning.stopwatch, fname, tic); end now = toc(getsubfield(ft_default.warning.stopwatch, fname)); % measure time since first function call if ~issubfield(ft_default.warning.identifier, fname) || ... (issubfield(ft_default.warning.identifier, fname) && now>getsubfield(ft_default.warning.identifier, [fname '.timeout'])) % create or reset field ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, fname, []); % warning never given before or timed out ws = warning(warningArgs{:}); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.timeout'], now+timeout); ft_default.warning.identifier = setsubfield(ft_default.warning.identifier, [fname '.ws'], msg); warned = true; else % the warning has been issued before, but has not timed out yet ws = getsubfield(ft_default.warning.identifier, [fname '.ws']); end end % function ft_warning %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fname, ft_previous_warnings, line] = fieldnameFromStack(ft_previous_warnings) % stack(1) is this function, stack(2) is ft_warning stack = dbstack('-completenames'); if size(stack) < 3 fname = []; line = []; return; end i0 = 3; % ignore ft_preamble while strfind(stack(i0).name, 'ft_preamble') i0=i0+1; end fname = horzcat(fixname(stack(end).name)); if ~issubfield(ft_previous_warnings, fixname(stack(end).name)) ft_previous_warnings.(fixname(stack(end).name)) = []; % iteratively build up structure fields end for i=numel(stack)-1:-1:(i0) % skip postamble scripts if strncmp(stack(i).name, 'ft_postamble', 12) break; end fname = horzcat(fname, '.', horzcat(fixname(stack(i).name))); % , stack(i).file if ~issubfield(ft_previous_warnings, fname) % iteratively build up structure fields setsubfield(ft_previous_warnings, fname, []); end end % line of last function call line = ['.line', int2str(stack(i0).line)]; end % function outcome = issubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % outcome = eval(['isfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % outcome = isfield(strct, fname); % end % end % function strct = rmsubfield(strct, fname) % substrindx = strfind(fname, '.'); % if numel(substrindx) > 0 % % separate the last fieldname from all former % strct = eval(['rmfield(strct.' fname(1:substrindx(end)-1) ', ''' fname(substrindx(end)+1:end) ''')']); % else % % there is only one fieldname % strct = rmfield(strct, fname); % end % end
github
lcnbeapp/beapp-master
ft_nonlinearassociation.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/misc/ft_nonlinearassociation.m
13,980
utf_8
8eddc691a3520b09cedcd32f211f3e34
function [association] = nonlinearassociation(cfg, data) % NONLINEARASSOCIATION calculate the association coefficient as a % function of delay. % % In order to estimate the amount of association between all possible % pairs of MEG sensors the nonlinear association analysis is used. % It was first developed for EEG data analysis by Pijn and co-workers % (Lopes da Silva, et al. 1989; Pijn, et al. 1990). The basic principle % is similar to that of coherence and (cross) correlation, with the % exception that this nonlinear association method can be applied % independent of the type of relationship (linear or nonlinear) in % the data. % % The method is based on the idea that if two signals x and y are % correlated, a nonlinear regression curve can be calculated that % represents their relationship. In practice, that regression curve % is estimated by creating a scatterplot of y versus x, dividing the % data in segments and describing each segment with a linear regression % curve. The estimated correlation ratio h2, which gives the reduction % in variance of y as a result of predicting its values according to % the regression curve, can be calculated as follows: % % h^2 = (sum(Yi - mean(Y))^2 - sum(Yi - f(Xi))^2) / sum(Yi - mean(Y))^2 % % With the sum going over N samples and f(Xi) the estimated value of % Yi according to the regression line. The h2 coefficient has values % between 0 (y is completely independent of x) and 1 (y is completely % determined by x). In the case of a linear relationship between x % and y, h2 is equal to the well known Pearson correlation coefficient % (r2). As is the case with cross-correlation, it is possible to % estimate h2 as a function of time shift () between the signals. The % h2 is then iteratively calculated for different values of , by % shifting the signals in comparison to each other, and the value for % which the maximal h2 is reached can be used as an estimate of the % time lag between both signals. In deciding what epoch length to use % in the association analysis, a trade-off has to be made between % successfully determining the correct delay and h2-value (for which % large epoch lengths are necessary) and a small enough time-resolution % (for which small epoch lengths are necessary). % % Use as % [association] = nonlinearassociation(cfg, data) % % The input data should be organised in a structure as obtained from % the PREPROCESSING function. % % The configuration should contain % cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), see CHANNELSELECTION for details % cfg.keeptrials = 'yes' or 'no', process the individual trials or the concatenated data (default = 'no') % cfg.trials = 'all' or a selection given as a 1xN vector (default = 'all') % cfg.fsample = 1200 % cfg.maxdelay = 32/cfg.fsample % cfg.delaystep = 2/cfg.fsample % cfg.nr_bins = 7 % cfg.offset = 0 % cfg.order = 'Hxy' % cfg.timwin = 0.2 % cfg.toi = [] % % References % - Lopes da Silva F, Pijn JP, Boeijinga P. (1989): Interdependence of % EEG signals: linear vs. nonlinear associations and the significance % of time delays and phase shifts. Brain Topogr 2(1-2):9-18. % - Pijn JP, Vijn PC, Lopes da Silva FH, Van Ende Boas W, Blanes W. % (1990): Localization of epileptogenic foci using a new signal % analytical approach. Neurophysiol Clin 20(1):1-11. % Copyright (C) 2007, Inge Westmijse ft_defaults % set the defaults if ~isfield(cfg, 'trials'), cfg.trials = 'all'; end if ~isfield(cfg, 'keeptrials'), cfg.keeptrials = 'no'; end if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end if ~isfield(cfg, 'toi'), cfg.toi = []; end if ~isfield(cfg, 'timwin'), cfg.timwin = 0.2; end if ~isfield(cfg, 'fsample'), cfg.fsample = 1200; end if ~isfield(cfg, 'delaystep'), cfg.delaystep = 2/cfg.fsample; end if ~isfield(cfg, 'maxdelay'), cfg.maxdelay = 32/cfg.fsample; end if ~isfield(cfg, 'offset'), cfg.offset = 0; end if ~isfield(cfg, 'nr_bins'), cfg.nr_bins = 7; end if ~isfield(cfg, 'order'), cfg.order = 'Hxy'; end if ~isfield(cfg, 'feedback'), cfg.feedback = 'textbar'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % do some bookkeeping on the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % select trials of interest if ~strcmp(cfg.trials, 'all') if islogical(cfg.trials), cfg.trials=find(cfg.trials); end fprintf('selecting %d trials\n', length(cfg.trials)); data.trial = data.trial(cfg.trials); data.time = data.time(cfg.trials); end Ntrials = numel(data.trial); % select channels of interest cfg.channel = channelselection(cfg.channel, data.label); chansel = match_str(data.label, cfg.channel); fprintf('selecting %d channels\n', length(chansel)); for trial=1:Ntrials data.trial{trial} = data.trial{trial}(chansel,:); end data.label = data.label(chansel); Nchans = length(chansel); % determine the size of each trial, they can be variable length Nsamples = zeros(1,Ntrials); for trial=1:Ntrials Nsamples(trial) = size(data.trial{trial},2); end if strcmp(cfg.keeptrials, 'no') % concatenate all the data into a 2D matrix fprintf('concatenating data'); dat = zeros(Nchans, sum(Nsamples)); for trial=1:Ntrials fprintf('.'); begsample = sum(Nsamples(1:(trial-1))) + 1; endsample = sum(Nsamples(1:trial)); dat(:,begsample:endsample) = data.trial{trial}; end fprintf('\n'); fprintf('concatenated data matrix size %dx%d\n', size(dat,1), size(dat,2)); time = [1/cfg.fsample : size(dat,1)/cfg.fsample : size(dat,1)]; data.trial = {dat}; data.time = {time}; Ntrials = 1; else % replace the time axis, since shifted time-axes over trials are not supported for i = 1:Ntrials data.time{i} = [1/cfg.fsample : 1/cfg.fsample : size(data.trial{i},2) / cfg.fsample]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % prepare all data selection %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % item 1: channel combinations numchannelcmb = Nchans*(Nchans-1)/2; channelcmb = zeros(numchannelcmb, 2); k = 1; if (strcmp(cfg.order, 'Hxy')) for i=1:Nchans for j=(i+1):Nchans channelcmb(k, :) = [i j]; k = k+1; end end elseif (strcmp(cfg.order, 'Hyx')) for i = Nchans:-1:1 for j = Nchans : -1:(i+1) channelcmb(k,:) = [i j]; k = k+1; end end end numchannelcmb = size(channelcmb,1); % item 2: time windows % this requires % cfg.toi = [t1 t2 t3 t4] center time of each window % cfg.timwin = 0.2 in seconds % TODO implement "time, offset, fsample" for j = 1:Ntrials time = data.time{j}; numtimwin = size(cfg.toi,2); % initial guess, not all might fit in this trial timwin = zeros(numtimwin,2); sel = zeros(numtimwin,1); for i=1:numtimwin timwin(i,1) = cfg.toi(i) - cfg.timwin/2; % begin of time window timwin(i,2) = cfg.toi(i) + cfg.timwin/2; % end of time window sel(i) = timwin(i,1)>=time(1) && timwin(i,2)<=time(end); % does it fit in? end timwin = timwin(find(sel==1),:); toi_mat{j} = cfg.toi(find(sel == 1)); % update the configuration timwin_mat{j} = round((timwin - cfg.offset) * cfg.fsample); % convert to samples end timwin = timwin_mat; cfg.toi = toi_mat; % item 3: delays within each timewindow % this requires % cfg.delaystep % cfg.maxdelay delay = -cfg.maxdelay:cfg.delaystep:cfg.maxdelay; numdelay = length(delay); % convert to samples delay = round(delay * cfg.fsample); if strcmp(cfg.keeptrials, 'yes') for trllop=1:Ntrials association.trial(trllop) = Do_Association_Calculation( trllop , Ntrials , cfg , timwin , numchannelcmb , numdelay , data , channelcmb , delay ); end % for each trial else trllop = 1; association = Do_Association_Calculation( trllop , Ntrials , cfg , timwin , numchannelcmb , numdelay , data , channelcmb , delay ); end % add the version details of this function call to the configuration try % get the full name of the function cfg.version.name = mfilename('fullpath'); catch % required for compatibility with Matlab versions prior to release 13 (6.5) [st, i] = dbstack; cfg.version.name = st(i); end cfg.version.id = '$Id$'; % remember the configuration details of the input data try, cfg.previous = data.cfg; end % remember the exact configuration details in the output association.cfg = cfg; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that does the computation for each trial function [association] = Do_Association_Calculation( trllop , Ntrials , cfg , timwin , numchannelcmb , numdelay , data , channelcmb , delay ) fprintf('\nprocessing trial %d from %d\n', trllop, Ntrials); association = []; numtimwin = size(timwin{trllop},1); h2 = zeros(numchannelcmb, numtimwin, numdelay); l = 0; maxl = numchannelcmb*numtimwin*numdelay; progress('init', cfg.feedback, 'Computing nonlinear association for each delay'); for i=1:numchannelcmb dat1_chan = data.trial{trllop}(channelcmb(i,1),:); dat2_chan = data.trial{trllop}(channelcmb(i,2),:); progress(l/maxl,'Computing nonlinear association %d from %d', l, maxl); for j=1:numtimwin dat1_timwin = dat1_chan(timwin{trllop}(j,1):timwin{trllop}(j,2)); dat2_timwin = dat2_chan(timwin{trllop}(j,1):timwin{trllop}(j,2)); for k=1:numdelay if delay(k)==0 % select the complete (unshifted) window dat1_delay = dat1_timwin; dat2_delay = dat2_timwin; elseif delay(k)<0 % channel 1 is shifted w.r.t. channel 2 dat1_delay = dat1_timwin((abs(delay(k))+1):end); dat2_delay = dat2_timwin(1:(end-abs(delay(k)))); elseif delay(k)>0 % channel 2 is shifted w.r.t. channel 1 dat1_delay = dat1_timwin(1:(end-delay(k))); dat2_delay = dat2_timwin((delay(k)+1):end); end % remove the mean of each snippet of data dat1_delay = dat1_delay - mean(dat1_delay); dat2_delay = dat2_delay - mean(dat2_delay); % do the computation [sorted_data1,id] = sort(dat1_delay); sorted_data2 = dat2_delay(id); data_is = sorted_data1; data_js = sorted_data2; % divided data_i in bins [H,mp_i] = hist(data_is,cfg.nr_bins); % Divide data_i and data_j in bins bp = 1; gem_j = zeros (cfg.nr_bins,1); for s = 1:cfg.nr_bins gem_j(s) = mean(data_js(bp:bp+H(s)-1)); bp = bp + H(s); end % Calculation of line segment and variance per bin p=1; sp = 1; clear unex_var tot_var; for u = 1:cfg.nr_bins data_is_bin = data_is(sp:sp+H(u)-1)'; data_js_bin = data_js(sp:sp+H(u)-1)'; if u == 1 fx1 = gem_j(u) + (gem_j(u+1) - gem_j(u))/(mp_i(u+1) - mp_i(u))*(data_is_bin(1:round(length(data_is_bin)/2)) - mp_i(u)); else fx1 = gem_j(u-1) + (gem_j(u) - gem_j(u-1))/(mp_i(u) - mp_i(u-1))*(data_is_bin(1:round(length(data_is_bin)/2)) - mp_i(u-1)); end if u == cfg.nr_bins fx2 = gem_j(u-1) + (gem_j(u) - gem_j(u-1))/(mp_i(u) - mp_i(u-1))*(data_is_bin(round(length(data_is_bin)/2)+1:end) - mp_i(u-1)); else fx2 = gem_j(u) + (gem_j(u+1) - gem_j(u))/(mp_i(u+1) - mp_i(u))*(data_is_bin(round(length(data_is_bin)/2)+1:end) - mp_i(u)); end % calculation unexplained variance ftot = [fx1; fx2]; unex_var(p:p+length(data_js_bin)-1,:) = (data_js_bin - ftot).^2; % calculation total variance tot_var(p:p+length(data_js_bin)-1,:) = (data_js_bin - mean(data_js)).^2; p = p+length(data_is_bin); sp = sp + H(u); end % Calculation of association coefficient h2 h2(i,j,k) = ((sum(tot_var) - sum(unex_var)) / sum(tot_var))*100; l=l+1; end end end progress('close'); % collect the results if (size(h2, 1) ~= numchannelcmb) error('number of channel combinations is not right'); end if (size(h2, 2) ~= numtimwin) error('number of timewindows does not match input'); end if (size(h2, 3) ~= numdelay) error('number of delays does not match input'); end h2 = reshape(h2, numchannelcmb*numtimwin, numdelay); [m, indx] = max(h2, [], 2); h2 = reshape(m, numchannelcmb, numtimwin); d = (delay(indx)./cfg.fsample)*1000; % convert to miliseconds (to compare with original method) d = reshape(d, numchannelcmb, numtimwin); % FIXME this does not work: one is not supposed to rely on data.cfg.trl, use data.time please! % association.time = cfg.toi{trllop} + data.cfg.trl(trllop,1); association.h2 = h2; association.delay = d; return % from Do_Association_Calculation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that computes the mean over all values without checking the dimensions % this function is approximately 2x faster on 1 dimensional data than the matlab version function y = mean(x) y = sum(x(:))./numel(x); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that bins the elements of Y into equally spaced containers % this function is approximately 2x faster on 1 dimensional data than the matlab version function [nn, x] = hist(y, x) miny = min(y); maxy = max(y); binwidth = (maxy - miny) ./ x; xx = miny:binwidth:maxy; x = xx(1:(end-1)) + binwidth/2; % Shift bins so the interval is ( ] instead of [ ). xx = full(real(xx)); y = full(real(y)); % For compatibility bins = xx + eps(xx); nn = histc(y',[-inf bins],1); % Combine first bin with 2nd bin and last bin with next to last bin nn(2,:) = nn(2,:)+nn(1,:); nn(end-1,:) = nn(end-1,:)+nn(end,:); nn = nn(2:end-1,:);
github
lcnbeapp/beapp-master
ft_spike_psth.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spike_psth.m
12,842
utf_8
e308e4099a5a08933fde13a8aa72fffd
function [psth] = ft_spike_psth(cfg,spike) % FT_SPIKE_PSTH computes the peristimulus histogram of spiketrains. % % Use as % [psth] = ft_spike_psth(cfg, spike) % % The input SPIKE should be organised as a) the spike datatype, obtained % from FT_SPIKE_MAKETRIALS b) the raw datatype, containing binary spike % trains, obtained from FT_APPENDSPIKE or FT_CHECKDATA. In this case the % raw datatype is converted to the spike datatype. % % Configurations: % cfg.binsize = [binsize] in sec or string. % If 'scott', we estimate the optimal bin width % using Scott's formula (1979). If 'sqrt', we take % the number of bins as the square root of the % number of observations. The optimal bin width is % derived over all neurons; thus, this procedure % works best if the input contains only one neuron % at a time. % cfg.outputunit = 'rate' (default) or 'spikecount' or % 'proportion'. If 'rate', we % convert the output per trial to firing rates % (spikes/sec). If 'spikecount', we count the % number spikes per trial. If 'proportion', we % normalize the area under the PSTH to 1. % cfg.spikechannel = See FT_CHANNELSELECTION for details. cfg.trials % is vector of indices (e.g., 1:2:10) % logical selection of trials (e.g., [1010101010]) % 'all' (default), selects all trials % cfg.vartriallen = 'yes' (default) % Accept variable trial lengths and use all % available trials and the samples in every trial. % Missing values will be ignored in the % computation of the average and the variance and % stored as NaNs in the output psth.trial. 'no' % Only select those trials that fully cover the % window as specified by cfg.latency and discard % those trials that do not. % cfg.latency = [begin end] in seconds % 'maxperiod' (default), i.e., maximum period % available 'minperiod', i.e., the minimal period % all trials share, 'prestim' (all t<=0) 'poststim' % (all t>=0). % cfg.keeptrials = 'yes' or 'no' (default). % cfg.trials = numeric or logical selection of trials (default = 'all') % % Outputs: % Psth is a timelock datatype (see FT_DATATYPE_TIMELOCK) % Psth.time = center histogram bin points % Psth.fsample = 1/binsize; % Psth.avg = contains average PSTH per unit % Psth.trial = contains PSTH per unit per trial % Psth.var = contains variance of PSTH per unit across trials % % For subsequent processing you can use % FT_SPIKE_PLOT_PSTH : plot only the PSTH, for a single neuron % FT_TIMELOCKSTATISTICS : compute statistics on the PSTH % FT_SPIKE_PLOT_RASTER : plot PSTH with raster for one or more neurons % FT_SPIKE_JPSTH : compute the JPSTH % Copyright (C) 2010-2013, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % control input spike structure and convert to spike if raw structure spike = ft_checkdata(spike,'datatype', 'spike', 'feedback', 'yes'); % get the default options cfg.outputunit = ft_getopt(cfg, 'outputunit','rate'); cfg.binsize = ft_getopt(cfg, 'binsize','scott'); cfg.spikechannel = ft_getopt(cfg, 'spikechannel', 'all'); cfg.trials = ft_getopt(cfg, 'trials', 'all'); cfg.latency = ft_getopt(cfg, 'latency','maxperiod'); cfg.vartriallen = ft_getopt(cfg, 'vartriallen', 'yes'); cfg.keeptrials = ft_getopt(cfg, 'keeptrials', 'yes'); % ensure that the options are valid cfg = ft_checkopt(cfg,'outputunit', 'char', {'rate', 'spikecount'}); cfg = ft_checkopt(cfg,'binsize', {'char', 'doublescalar'}); cfg = ft_checkopt(cfg,'spikechannel',{'cell', 'char', 'double'}); cfg = ft_checkopt(cfg,'latency', {'char', 'ascendingdoublebivector'}); cfg = ft_checkopt(cfg,'trials', {'char', 'doublevector', 'logical'}); cfg = ft_checkopt(cfg,'vartriallen' , 'char', {'yes', 'no'}); cfg = ft_checkopt(cfg,'keeptrials' , 'char', {'yes', 'no'}); cfg = ft_checkconfig(cfg, 'allowed', {'outputunit', 'binsize', 'spikechannel', 'trials', 'latency', 'vartriallen', 'keeptrials'}); % get the number of trials or convert to indices cfg = trialselection(cfg,spike); % select the unit - this should be done with channelselection function cfg.spikechannel = ft_channelselection(cfg.spikechannel, spike.label); spikesel = match_str(spike.label, cfg.spikechannel); nUnits = length(spikesel); if nUnits==0, error('no spikechannel selected by means of cfg.spikechannel'); end % determine the duration of each trial begTrialLatency = spike.trialtime(cfg.trials,1); % remember: already selected on trial here endTrialLatency = spike.trialtime(cfg.trials,2); trialDur = endTrialLatency - begTrialLatency; % select the latencies, use the same modular function in all the scripts cfg = latencyselection(cfg,begTrialLatency,endTrialLatency); % compute the optimal bin width if desired if ischar(cfg.binsize) h = zeros(1,nUnits); for iUnit = 1:nUnits unitIndx = spikesel(iUnit); % select the unit spikesInWin = spike.time{unitIndx}>=cfg.latency(1) & spike.time{unitIndx}<=cfg.latency(2); % get spikes in trial % automatically determine an 'optimal' binwidth N = sum(spikesInWin); if strcmp(cfg.binsize,'scott') sd = nanstd(spike.time{unitIndx}(spikesInWin)); h(iUnit) = 3.49*sd./(N^(1/3)); elseif strcmp(cfg.binsize,'sqrt') k = ceil(sqrt(N)); h(iUnit) = (cfg.latency(2)-cfg.latency(1))/k; else error('unsupported option for cfg.binsize'); end end cfg.binsize = nanmean(h); end % do some error checking on the binsize if cfg.binsize<=0 || cfg.binsize>(cfg.latency(2)-cfg.latency(1)), error('cfg.binsize should be greater than zero and not exceed the trialduration'); end % end of trial should be late enough, beginning should be early enough fullDur = trialDur>=cfg.binsize; % trials which have full duration overlaps = endTrialLatency>=(cfg.latency(1)+cfg.binsize) & begTrialLatency<=(cfg.latency(2)-cfg.binsize); if strcmp(cfg.vartriallen,'no') % only select trials that fully cover our latency window startsLater = single(begTrialLatency) > (single(cfg.latency(1)) + 0.0001); % last factor just for rounding errors endsEarlier = single(endTrialLatency) < (single(cfg.latency(2)) - 0.0001); hasWindow = ~(startsLater | endsEarlier); % it should not start later or end earlier else hasWindow = ones(1,length(cfg.trials)); end trialSel = fullDur(:) & overlaps(:) & hasWindow(:); cfg.trials = cfg.trials(trialSel); % note that endTrialLatency was of length cfg.trials if isempty(cfg.trials), warning('No trials were selected after latency selection'); end nTrials = length(cfg.trials); begTrialLatency = begTrialLatency(trialSel); % note that begTrialLatency was of length cfg.trials here endTrialLatency = endTrialLatency(trialSel); % create the bins, we start arbitrarily at cfg.latency(1) bins = cfg.latency(1) : cfg.binsize : cfg.latency(end); nBins = length(bins); % preallocate before computing the psth, otherwise, compute stuff 'on the run' if strcmp(cfg.keeptrials,'yes'), singleTrials = NaN(nTrials,nUnits,nBins-1); end [s,ss] = deal(zeros(nUnits, nBins-1)); %sum, and sum of squared in the loop, to get mean & var % preallocate and compute degrees of freedom allStartEarlier = all(begTrialLatency<=cfg.latency(1)); allEndLater = all(endTrialLatency>=cfg.latency(2)); if ~ (allStartEarlier && allEndLater), dof = zeros(1,nBins-1); else dof = ones(1,nBins-1)*nTrials; % if all exceed latency, then this is dof end for iTrial = 1:nTrials origTrial = cfg.trials(iTrial); if ~ (allStartEarlier && allEndLater) % select bins and count dof + 1 binSel = begTrialLatency(iTrial)<=bins(1:end-1) & endTrialLatency(iTrial)>=bins(2:end); dof(binSel) = dof(binSel) + 1; else binSel = 1:(nBins-1); % always deselect the last bin end for iUnit = 1:nUnits unitIndx = spikesel(iUnit); % select the unit spikesInTrial = (spike.trial{unitIndx}==origTrial); % get spikes in trial spikeTimes = spike.time{unitIndx}(spikesInTrial); % compute the psth trialPsth = histc(spikeTimes(:), bins); % we deselect the last bin per default trialPsth = trialPsth(:)'; % force into row vec if isempty(trialPsth), trialPsth = zeros(1,length(bins)); end % convert to firing rates if requested, with spikecount do nothing if strcmp(cfg.outputunit,'rate'), trialPsth = trialPsth/cfg.binsize; elseif strcmp(cfg.outputunit,'proportion'), trialPsth = trialPsth./nansum(trialPsth); end % compute the sum and the sum of squares for the var and the mean on the fly s(iUnit,binSel) = s(iUnit,binSel) + trialPsth(binSel); % last bin is single value ss(iUnit,binSel) = ss(iUnit,binSel) + trialPsth(binSel).^2; if strcmp(cfg.keeptrials,'yes'), singleTrials(iTrial,iUnit,binSel) = trialPsth(binSel); end end end % get the results dof = dof(ones(nUnits,1),:); psth.avg = s ./ dof; psth.var = (ss - s.^2./dof)./(dof-1); % since sumPsth.^2 ./ dof = dof .* (sumPsth/dof).^2 psth.dof = dof; % combined with psth.var we can get SEM psth.fsample = 1/(cfg.binsize); % might be more compatible with feeding psth in other funcs psth.time = bins(1:end-1) + 0.5*cfg.binsize; psth.label = spike.label(spikesel); if (strcmp(cfg.keeptrials,'yes')) psth.trial = singleTrials; psth.dimord = 'rpt_chan_time'; else psth.dimord = 'chan_time'; end if isfield(spike,'sampleinfo'), psth.sampleinfo = spike.sampleinfo(cfg.trials,:); end if isfield(spike,'trialinfo'), psth.trialinfo = spike.trialinfo(cfg.trials,:); end % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous spike ft_postamble history psth %%%%%%%%% SUB FUNCTIONS %%%%%%%%% function [cfg] = latencyselection(cfg,begTrialLatency,endTrialLatency) if strcmp(cfg.latency,'minperiod') cfg.latency = [max(begTrialLatency) min(endTrialLatency)]; elseif strcmp(cfg.latency,'maxperiod') cfg.latency = [min(begTrialLatency) max(endTrialLatency)]; elseif strcmp(cfg.latency,'prestim') cfg.latency = [min(begTrialLatency) 0]; elseif strcmp(cfg.latency,'poststim') cfg.latency = [0 max(endTrialLatency)]; end % check whether the time window fits with the data if (cfg.latency(1) < min(begTrialLatency)), cfg.latency(1) = min(begTrialLatency); warning('Correcting begin latency because it is before all trial beginnings'); end if (cfg.latency(2) > max(endTrialLatency)), cfg.latency(2) = max(endTrialLatency); warning('Correcting end latency because it is after all trial ends'); end function [cfg] = trialselection(cfg,spike) nTrials = size(spike.trialtime,1); if strcmp(cfg.trials,'all') cfg.trials = 1:nTrials; elseif islogical(cfg.trials) cfg.trials = find(cfg.trials); end cfg.trials = sort(cfg.trials(:)); if max(cfg.trials)>nTrials, error('maximum trial number in cfg.trials should not exceed number of rows of spike.trialtime'); end if isempty(cfg.trials), error('No trials were selected by you, rien ne va plus'); end
github
lcnbeapp/beapp-master
ft_spikesimulation.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spikesimulation.m
4,725
utf_8
d2f166296318bfe9177298cc049edc35
function data = ft_spikesimulation(cfg) % FT_SPIKESIMULATION simulates a spiketrain with a structures timing of the % neuronal firing. % % Use as % data = ft_spikesimulation(cfg) % and please look in the code for the cfg details. % % See also FT_DIPOLESIMULATION, FT_FREQSIMULATION % Copyright (C) 2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % set the defaults if ~isfield(cfg, 'trlduration'), cfg.trlduration = 1; end % in seconds if ~isfield(cfg, 'nlfpchan'), cfg.nlfpchan = 10; end if ~isfield(cfg, 'nspikechan'), cfg.nspikechan = 10; end if ~isfield(cfg, 'spikerate'), cfg.spikerate = ones(cfg.nspikechan,1)*10; end if ~isfield(cfg, 'ntrial'), cfg.ntrial = 10; end if ~isfield(cfg, 'bpfreq'), cfg.bpfreq = [40 80]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % define the parameters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % cfg.spikerate = [ 10 50 100 200]; % cfg.nspikechan = 4; % nlfpchan = 2; % cfg.ntrial = 10; % cfg.bpfreq = [40 80]; % cfg.trlduration = 1; spikemix = eye(cfg.nspikechan, cfg.nlfpchan); spikemix(5,1:2) = [0.5 0.5]; % mix with lfp chan 1 and 2 spikemix(6,1:2) = [0.5 0.5]; % mix with lfp chan 1 and 2 % cfg.spikerate = 100*ones(1,cfg.nspikechan); % for each channel, per second % cfg.spikerate = [100 100 300 300 100 300]; fsample = 1000; nsample = cfg.trlduration*fsample; nchan = cfg.nlfpchan + cfg.nspikechan; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % create the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % start with empty data data = []; data.fsample = fsample; % create channel labels k = 1; for i=1:cfg.nlfpchan, data.label{k} = sprintf('lfp%02d', i); k=k+1; end for i=1:cfg.nspikechan, data.label{k} = sprintf('spike%02d', i); k=k+1; end data.label = data.label(:); for t=1:cfg.ntrial fprintf('creating trial %d\n', t); data.time{t} = (1:nsample)./fsample; lfp = zeros(cfg.nlfpchan, nsample); spike = zeros(cfg.nspikechan, nsample); for i=1:cfg.nlfpchan, lfp(i,:) = ft_preproc_bandpassfilter(randn(1,nsample), fsample, cfg.bpfreq); end for i=1:cfg.nspikechan % the spikes are generated from a probabilistic mix of the LFP channels x = spikemix(i,:) * lfp; % apply a non-linear mapping to the spike probablility, output should be defined between 0 and 1 x = mapping(x); % normalize the total probability to one x = x./sum(x); % randomly assign the spikes over the time series spike(i,:) = ((cfg.spikerate(i)*nsample/fsample)*x)>=rand(size(x)); end data.time{t} = (1:nsample)./fsample; data.trial{t} = [lfp; spike]; clear lfp spike end % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble history data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to strengthen the temporal strucure in the spike train % by a non-linear modulation of the spike probability %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = mapping(x) x = 6*(x-mean(x))/std(x); y = 1./(1+exp(-x)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % IIRFILTER simple brick wall filter in the frequency domain %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function s = myiirfilter(s, fs, fb, a) f = fft(s); ax = linspace(0, fs, length(s)); fl = nearest(ax, fb(1))-1; fh = nearest(ax, fb(2))+1; f(1:fl) = a.*f(1:fl); f(fh:end) = a.*f(fh:end); s = real(ifft(f));
github
lcnbeapp/beapp-master
ft_spikedensity.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spikedensity.m
16,902
utf_8
ec80282516f911e5c7b17ae91dbafcaf
function [sdf, sdfdata] = ft_spikedensity(cfg,data) % FT_SPIKEDENSITY computes the spike density function of the spike trains by % convolving the data with a window. % % Use as % [sdf] = ft_spike_density(cfg, data) % [sdf, sdfdata] = ft_spike_density(cfg, data) % % If you specify one output argument, only the average and variance of spike density % function across trials will be computed and individual trials are not kept. See % cfg.winfunc below for more information on the smoothing kernel to use. % % Inputs: % DATA should be organised in a RAW structure with binary spike % representations obtained from FT_APPENDSPIKE or FT_CHECKDATA, or % a SPIKE structure. % % Configurations: % cfg.timwin = [begin end], time of the smoothing kernel (default = [-0.05 0.05]) % If cfg.winfunc = @alphawin, cfg.timwin(1) will be % set to 0. Hence, it is possible to use asymmetric % kernels. % cfg.outputunit = 'rate' (default) or 'spikecount'. This determines the physical unit % of our spikedensityfunction, either in firing rate or in spikecount. % cfg.winfunc = (a) string or function handle, type of window to convolve with (def = 'gauss'). % - 'gauss' (default) % - 'alphawin', given by win = x*exp(-x/timeconstant) % - For standard window functions in the signal processing toolbox see % WINDOW. % (b) vector of length nSamples, used directly as window % cfg.winfuncopt = options that go with cfg.winfunc % For cfg.winfunc = 'alpha': the timeconstant in seconds (default = 0.005s) % For cfg.winfunc = 'gauss': the standard deviation in seconds (default = % 1/4 of window duration in seconds) % For cfg.winfunc = 'wname' with 'wname' any standard window function % see window opts in that function and add as cell array % If cfg.winfunctopt = [], default opts are taken. % cfg.latency = [begin end] in seconds, 'maxperiod' (default), 'minperiod', % 'prestim'(t>=0), or 'poststim' (t>=0). % cfg.vartriallen = 'yes' (default) or 'no'. % 'yes' - accept variable trial lengths and use all available trials % and the samples in every trial. Missing values will be ignored in % the computation of the average and the variance. % 'no' - only select those trials that fully cover the window as % specified by cfg.latency. % cfg.spikechannel = cell-array ,see FT_CHANNELSELECTION for details % cfg.trials = numeric or logical selection of trials (default = 'all') % cfg.keeptrials = 'yes' or 'no' (default). If 'yes', we store the trials in a matrix % in the output SDF as well % cfg.fsample = additional user input that can be used when input % is a SPIKE structure, in that case a continuous % representation is created using cfg.fsample % (default = 1000) % % The SDF output is a data structure similar to the TIMELOCK structure from FT_TIMELOCKANALYSIS. % For subsequent processing you can use for example % FT_TIMELOCKSTATISTICS: Compute statistics on SDF % FT_SPIKE_PLOT_RASTER: Plot together with the raster plots % FT_SINGLEPLOTER and FT_MULTIPLOTER Plot spike-density alone % % The SDFDATA output is a data structure similar to DATA type structure from FT_PREPROCESSING. % For subsequent processing you can use for example % FT_TIMELOCKANALYSIS Compute time-locked average and variance % FT_FREQANALYSIS Compute frequency and time-ferquency spectrum. % Copyright (C) 2010-2012, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % get the default options if isfield(cfg,'trials') && isempty(cfg.trials), error('no trials were selected'); end % empty should result in error, not in default cfg.outputunit = ft_getopt(cfg,'outputunit','rate'); cfg.timwin = ft_getopt(cfg,'timwin',[-0.05 0.05]); cfg.trials = ft_getopt(cfg,'trials', 'all'); cfg.latency = ft_getopt(cfg,'latency','maxperiod'); cfg.spikechannel = ft_getopt(cfg,'spikechannel', 'all'); cfg.vartriallen = ft_getopt(cfg,'vartriallen', 'yes'); cfg.keeptrials = ft_getopt(cfg,'keeptrials', 'yes'); cfg.winfunc = ft_getopt(cfg,'winfunc', 'gauss'); cfg.winfuncopt = ft_getopt(cfg,'winfuncopt', []); cfg.fsample = ft_getopt(cfg,'fsample', 1000); % ensure that the options are valid cfg = ft_checkopt(cfg, 'outputunit','char', {'rate', 'spikecount'}); cfg = ft_checkopt(cfg, 'spikechannel',{'cell', 'char', 'double'}); cfg = ft_checkopt(cfg, 'latency', {'char', 'ascendingdoublebivector'}); cfg = ft_checkopt(cfg, 'trials', {'char', 'doublevector', 'logical'}); cfg = ft_checkopt(cfg, 'vartriallen', 'char', {'yes', 'no'}); cfg = ft_checkopt(cfg, 'keeptrials', 'char', {'yes', 'no'}); cfg = ft_checkopt(cfg, 'timwin', 'ascendingdoublebivector'); cfg = ft_checkopt(cfg, 'winfunc', {'char', 'function_handle', 'doublevector'}); cfg = ft_checkopt(cfg, 'winfuncopt', {'cell', 'double', 'empty'}); cfg = ft_checkopt(cfg, 'fsample', 'double'); if strcmp(class(cfg.winfunc), 'function_handle'), cfg.winfunc = func2str(cfg.winfunc); end cfg = ft_checkconfig(cfg, 'allowed', {'outputunit', 'spikechannel', 'latency', 'trials', 'vartriallen', 'keeptrials', 'timwin', 'winfunc', 'winfuncopt', 'fsample'}); % check input data structure data = ft_checkdata(data, 'datatype', 'raw', 'feedback', 'yes', 'fsample', cfg.fsample); [spikechannel] = detectspikechan(data); if strcmp(cfg.spikechannel, 'all'), cfg.spikechannel = spikechannel; else cfg.spikechannel = ft_channelselection(cfg.spikechannel, data.label); if ~all(ismember(cfg.spikechannel,spikechannel)), warning('some selected spike channels no not appear spike channels'); end end spikesel = match_str(data.label, cfg.spikechannel); nUnits = length(spikesel); % number of spike channels if nUnits==0, error('no spikechannel selected by means of cfg.spikechannel'); end % get the number of trials or change DATA according to cfg.trials if strcmp(cfg.trials,'all') cfg.trials = 1:length(data.trial); elseif islogical(cfg.trials) cfg.trials = find(cfg.trials); end cfg.trials = sort(cfg.trials(:)); if max(cfg.trials)>length(data.trial),error('maximum trial number in cfg.trials should not exceed length of data.trial'), end if isempty(cfg.trials), error('no trials were selected in cfg.trials'); end % determine the duration of each trial begTrialLatency = cellfun(@min,data.time(cfg.trials)); endTrialLatency = cellfun(@max,data.time(cfg.trials)); % select the latencies if strcmp(cfg.latency,'minperiod') cfg.latency = [max(begTrialLatency) min(endTrialLatency)]; elseif strcmp(cfg.latency,'maxperiod') cfg.latency = [min(begTrialLatency) max(endTrialLatency)]; elseif strcmp(cfg.latency,'prestim') cfg.latency = [min(begTrialLatency) 0]; elseif strcmp(cfg.latency,'poststim') cfg.latency = [0 max(endTrialLatency)]; end if (cfg.latency(1) < min(begTrialLatency)), cfg.latency(1) = min(begTrialLatency); warning('correcting begin latency of averaging window'); end if (cfg.latency(2) > max(endTrialLatency)), cfg.latency(2) = max(endTrialLatency); warning('correcting end latency of averaging window'); end % start processing the window information if strcmp(cfg.winfunc,'alphawin') % now force start of window to be positive. warning('cfg.timwin(1) should be a non-negative number if cfg.winfunc = @alphawin, correcting') cfg.timwin(1) = 0; end if cfg.timwin(1)>0 || cfg.timwin(2)<0, error('Please specify cfg.timwin(1)<=0 and cfg.timwin(2)>=0'); end % construct the window and the time axis of the window fsample = data.fsample; sampleTime = 1/fsample; nLeftSamples = round(-cfg.timwin(1)/sampleTime); nRightSamples = round(cfg.timwin(2)/sampleTime); winTime = -nLeftSamples*sampleTime : sampleTime : nRightSamples*sampleTime; % this is uneven if cfg.timwin symmetric cfg.timwin = [winTime(1) winTime(end)]; nSamplesWin = length(winTime); if nSamplesWin==1, warning('Number of samples in selected window is exactly one, so no smoothing applied'); end % construct the window if ~iscell(cfg.winfuncopt), cfg.winfuncopt = {cfg.winfuncopt}; end if strcmp(cfg.winfunc,'gauss') if isempty(cfg.winfuncopt{1}), cfg.winfuncopt{1} = 0.25*diff(cfg.timwin); end win = exp(-(winTime.^2)/(2*cfg.winfuncopt{1}^2)); % here we could compute the optimal SD elseif strcmp(cfg.winfunc,'alphawin') if isempty(cfg.winfuncopt{1}), cfg.winfuncopt{1} = 0.005; end win = winTime.*exp(-winTime/cfg.winfuncopt{1}); elseif ischar(cfg.winfunc) if isempty(cfg.winfuncopt{1}) win = feval(cfg.winfunc,nSamplesWin); else win = feval(cfg.winfunc,nSamplesWin, cfg.winfuncopt{:}); end else % must be a double vector then if length(cfg.winfunc)~=nSamplesWin, error('Length of cfg.winfunc vector should be %d', nSamplesWin); end end win = win(:).'./sum(win); % normalize the window to 1 winDur = max(winTime) - min(winTime); % duration of the window % create the time axis for the spike density time = cfg.latency(1):(1/fsample):cfg.latency(2); cfg.latency(2) = time(end); % this is the used latency that should be stored in cfg again maxNumSamples = length(time); % check which trials will be used based on the latency overlaps = endTrialLatency>=(cfg.latency(1)+winDur) & begTrialLatency<=(cfg.latency(2)-winDur); if strcmp(cfg.vartriallen,'no') % only select trials that fully cover our latency window hasWindow = false(length(begTrialLatency),1); for iTrial = 1:length(begTrialLatency) timeTrial = data.time{cfg.trials(iTrial)}; nSamplesTrial = length(timeTrial); hasLaterStart = (begTrialLatency(iTrial)-cfg.latency(1))>(0.5*sampleTime); hasEarlierEnd = (cfg.latency(2)-endTrialLatency(iTrial))>(0.5*sampleTime); hasWindow(iTrial) = ~hasLaterStart & ~hasEarlierEnd & nSamplesTrial>=maxNumSamples; end else hasWindow = true(length(cfg.trials),1); % in case vartriallen = "yes" end trialSel = overlaps(:) & hasWindow(:); % trials from cfg.trials we select further cfg.trials = cfg.trials(trialSel); % cut down further on cfg.trials begTrialLatency = begTrialLatency(trialSel); % on this variable as well endTrialLatency = endTrialLatency(trialSel); % on this variable as well nTrials = length(cfg.trials); % the actual number of trials we will use if isempty(cfg.trials),warning('no trials were selected, please check cfg.trials'), end % calculates the samples we are shifted wrt latency(1) samplesShift = zeros(1,nTrials); sel = (begTrialLatency-cfg.latency(1))>(0.5*sampleTime); % otherwise 0 samples to be padded samplesShift(sel) = round(fsample*(begTrialLatency(sel)-cfg.latency(1))); % preallocate the sum, squared sum and degrees of freedom [s,ss] = deal(NaN(nUnits, maxNumSamples)); % sum and sum of squares dof = zeros(nUnits, length(s)); % preallocate, depending on whether nargout is 1 or 2 if (strcmp(cfg.keeptrials,'yes')), singleTrials = zeros(nTrials,nUnits,size(s,2)); end if nargout==2, [sdfdata.trial(1:nTrials) sdfdata.time(1:nTrials)] = deal({[]}); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute the spike density %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for iTrial = 1:nTrials origTrial = cfg.trials(iTrial); % this is the original trial we use for DATA input timeAxis = data.time{origTrial}; % get the time axis for this trial begSample = nearest(timeAxis, cfg.latency(1)); sampleSel = begSample : (begSample + maxNumSamples - samplesShift(iTrial) - 1); sampleSel(sampleSel>length(timeAxis)) = []; % delete the indices that should not be there nSamples = length(sampleSel); trialTime = timeAxis(sampleSel); % select the relevant portion of time % handle every unit separately for iUnit = 1:nUnits unitIndx = spikesel(iUnit); % index in data.label dat = data.trial{origTrial}(unitIndx,sampleSel); % get the data if any(dat) y = conv(full(dat),win); % use convolution to get the raw spike density else y = zeros(1,nSamples + nSamplesWin - 1); % no spikes; no convolution needed end if strcmp(cfg.outputunit, 'rate') y = y*fsample; % normalize to the sampling rate, to get it in Hz. else y = y*nSamplesWin; % now maximum becomes N (length window) end % restrict to the relevant portion of output conv y = y(nLeftSamples+1 : end-nRightSamples); % delete additional points we get with conv y([1:nLeftSamples end-nRightSamples+1:end]) = NaN; % assign NaN at borders % write a raw data structure if nargout==2 sl = ~isnan(y); sdfdata.trial{iTrial}(iUnit,:) = y(sl); sdfdata.time{iTrial}(1,:) = trialTime(sl); % write back original time axis end % pad with nans if there's variable trial length dofsel = ~isnan(y);%true(1,length(y)); if strcmp(cfg.vartriallen,'yes') padLeft = zeros(1, samplesShift(iTrial)); padRight = zeros(1,(maxNumSamples - nSamples - samplesShift(iTrial))); ySingleTrial = [NaN(size(padLeft)) y NaN(size(padRight))]; y = [padLeft y padRight]; dofsel = logical([padLeft dofsel padRight]); else ySingleTrial = y; end % compute the sum and the sum of squares s(iUnit,:) = nansum([s(iUnit,:);y]); % compute the sum ss(iUnit,:) = nansum([ss(iUnit,:);y.^2]); % compute the squared sum % count the number of samples that went into the sum dof(iUnit,dofsel) = dof(iUnit,dofsel) + 1; % keep the single trials if requested if strcmp(cfg.keeptrials,'yes'), singleTrials(iTrial,iUnit,:) = ySingleTrial; end end % remove the trial from data in order to avoid buildup in memory data.trial{origTrial} = []; data.time{origTrial} = []; end % give back a similar structure as timelockanalysis sdf.avg = s ./ dof; sdf.var = (ss - s.^2./dof)./(dof-1); sdf.dof = dof; sdf.time = time; sdf.label(1:nUnits) = data.label(spikesel); if (strcmp(cfg.keeptrials,'yes')) sdf.trial = singleTrials; sdf.dimord = 'rpt_chan_time'; else sdf.dimord = 'chan_time'; end % create a new structure that is a standard raw data spike structure itself, this is returned as second output argument if nargout==2 sdfdata.fsample = fsample; sdfdata.label(1:nUnits) = data.label(spikesel); try, sdfdata.hdr = data.hdr; end end % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous data ft_postamble history sdf if nargout==2 ft_postamble history sdfdata end function [spikelabel, eeglabel] = detectspikechan(data) % autodetect the spike channels ntrial = length(data.trial); nchans = length(data.label); spikechan = zeros(nchans,1); for i=1:ntrial for j=1:nchans hasAllInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:) == round(data.trial{i}(j,:))); hasAllPosInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:)>=0); spikechan(j) = spikechan(j) + double(hasAllInts & hasAllPosInts); end end spikechan = (spikechan==ntrial); spikelabel = data.label(spikechan); eeglabel = data.label(~spikechan);
github
lcnbeapp/beapp-master
ft_spike_rate.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spike_rate.m
9,138
utf_8
cd54c3262f0a19d4bb98e00fd04202b0
function [rate] = ft_spike_rate(cfg,spike) % FT_SPIKE_RATE computes the firing rate of spiketrains and their variance % % Use as % [rate] = ft_spike_rate(cfg, spike) % % The input SPIKE should be organised as the spike or the (binary) raw datatype, obtained from % FT_SPIKE_MAKETRIALS or FT_APPENDSPIKE (in that case, conversion is done % within the function) % % Configurations: % cfg.outputunit = 'rate' (default) or 'spikecount'. If 'rate', we convert % the output per trial to firing rates (spikes/sec). % If 'spikecount', we count the number spikes per trial. % cfg.spikechannel = see FT_CHANNELSELECTION for details % cfg.trials = vector of indices (e.g., 1:2:10) % logical selection of trials (e.g., [1010101010]) % 'all' (default), selects all trials% cfg.trials % cfg.vartriallen = 'yes' (default) or 'no'. % If 'yes' - accept variable trial lengths and use all available trials % and the samples in every trial. % If 'no' - only select those trials that fully cover the window as % specified by cfg.latency and discard those trials that do not. % cfg.latency = [begin end] in seconds % 'maxperiod' (default) % 'minperiod', i.e., the minimal period all trials share % 'prestim' (all t<=0) % 'poststim' (all t>=0). % cfg.keeptrials = 'yes' or 'no' (default). % % The outputs from spike is a TIMELOCK structure (see FT_DATATYPE_TIMELOCK) % rate.trial: nTrials x nUnits matrix containing the firing rate per unit and trial % rate.avg: nTrials array containing the average firing rate per unit % rate.var: nTrials array containing the variance of firing rates per unit % rate.dof: nTrials array containing the degree of freedom per unit % rate.label: nUnits cell array containing the labels of the neuronal units% % rate.time: Mean latency (this field ensures it is TIMELOCK % struct) % Copyright (C) 2010, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % control input spike structure spike = ft_checkdata(spike,'datatype', 'spike', 'feedback', 'yes'); % get the default options if isfield(cfg,'trials') && isempty(cfg.trials), error('no trials were selected'); end % empty should result in error, not in default cfg.outputunit = ft_getopt(cfg, 'outputunit','rate'); cfg.spikechannel = ft_getopt(cfg, 'spikechannel', 'all'); cfg.trials = ft_getopt(cfg, 'trials', 'all'); cfg.latency = ft_getopt(cfg,'latency','maxperiod'); cfg.vartriallen = ft_getopt(cfg,'vartriallen', 'yes'); cfg.keeptrials = ft_getopt(cfg,'keeptrials', 'yes'); % ensure that the options are valid cfg = ft_checkopt(cfg,'outputunit','char', {'rate', 'spikecount'}); cfg = ft_checkopt(cfg,'spikechannel',{'cell', 'char', 'double'}); cfg = ft_checkopt(cfg,'latency', {'char', 'ascendingdoublebivector'}); cfg = ft_checkopt(cfg,'trials', {'char', 'doublevector', 'logical'}); cfg = ft_checkopt(cfg,'vartriallen', 'char', {'yes', 'no'}); cfg = ft_checkopt(cfg,'keeptrials', 'char', {'yes', 'no'}); % check if the configuration inputs are valid cfg = ft_checkconfig(cfg, 'allowed', {'outputunit', 'spikechannel', 'trials', 'latency', 'vartriallen', 'keeptrials'}); % get the spikechannels cfg.spikechannel = ft_channelselection(cfg.spikechannel, spike.label); spikesel = match_str(spike.label, cfg.spikechannel); nUnits = length(spikesel); % number of spike channels if nUnits==0, error('No spikechannel selected by means of cfg.spikechannel'); end % do the trial selection cfg = trialselection(cfg,spike); nTrials = length(cfg.trials); % actual number of trials we use % determine the duration of each trial begTrialLatency = spike.trialtime(cfg.trials,1); endTrialLatency = spike.trialtime(cfg.trials,2); % select the latencies cfg = latencyselection(cfg,begTrialLatency,endTrialLatency); % check which trials will be used based on the latency overlaps = endTrialLatency>(cfg.latency(1)) & begTrialLatency<(cfg.latency(2)); hasWindow = true(nTrials,1); if strcmp(cfg.vartriallen,'no') % only select trials that fully cover our latency window startsLater = begTrialLatency > (cfg.latency(1) + 0.0001); endsEarlier = endTrialLatency < (cfg.latency(2) - 0.0001); hasWindow = ~(startsLater | endsEarlier); % it should not start later or end earlier trialDur = ones(nTrials,1)*(cfg.latency(2)-cfg.latency(1)); elseif strcmp(cfg.vartriallen,'yes') winBeg = max([begTrialLatency(:) cfg.latency(1)*ones(nTrials,1)],[],2); winEnd = min([endTrialLatency(:) cfg.latency(2)*ones(nTrials,1)],[],2); trialDur = winEnd-winBeg; % the effective trial duration end cfg.trials = cfg.trials(overlaps(:) & hasWindow(:)); trialDur = trialDur(overlaps(:) & hasWindow(:)); % select the durations, we will need this later nTrials = length(cfg.trials); if isempty(cfg.trials), warning('No trials were selected in the end'); end % preallocate before computing the psth keepTrials = strcmp(cfg.keeptrials,'yes'); if keepTrials, singleTrials = NaN(nTrials,nUnits); end % preallocate single trials with NaNs [s,ss] = deal(zeros(nUnits,1)); dof = nTrials*ones(nUnits,1); % compute degrees of freedom for iUnit = 1:nUnits unitIndx = spikesel(iUnit); ts = spike.time{unitIndx}(:); % get the times latencySel = ts>=cfg.latency(1) & ts<=cfg.latency(2); % select timestamps within latency trialSel = ismember(spike.trial{unitIndx},cfg.trials); trialNums = spike.trial{unitIndx}(latencySel(:) & trialSel(:)); % use the fact that trial numbers are integers >=1 apart, so we can use histc trialBins = sort([cfg.trials-0.5; cfg.trials+0.5]); trialRate = histc(trialNums(:),trialBins); trialRate = trialRate(1:2:end-1); % the uneven bins correspond to the trial integers if isempty(trialRate), trialRate = zeros(nTrials,1); end % convert to firing rates if requested if strcmp(cfg.outputunit,'rate') ,trialRate = trialRate(:)./trialDur(:); end % store and compute sum, just fill the single trials up with nans if keepTrials, singleTrials(:,iUnit) = trialRate(:); end s(iUnit) = sum(trialRate); ss(iUnit) = sum(trialRate.^2); end % compute the average rate rate.avg = s ./ dof; rate.var = (ss - s.^2./dof)./(dof); % since sumrate.^2 ./ dof = dof .* (sumrate/dof).^2 rate.var(dof<2) = 0; % gather the rest of the results rate.dof = dof; rate.label = spike.label(spikesel); rate.dimord = 'chan_time'; rate.time = mean(cfg.latency); if (strcmp(cfg.keeptrials,'yes')) rate.trial = singleTrials; rate.dimord = 'rpt_chan_time'; end if isfield(spike, 'trialinfo'), rate.trialinfo = spike.trialinfo(cfg.trials,:); end % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous spike ft_postamble history rate %%%%%%%%% SUB FUNCTIONS %%%%%%%%% function [cfg] = latencyselection(cfg,begTrialLatency,endTrialLatency) if strcmp(cfg.latency,'minperiod') cfg.latency = [max(begTrialLatency) min(endTrialLatency)]; elseif strcmp(cfg.latency,'maxperiod') cfg.latency = [min(begTrialLatency) max(endTrialLatency)]; elseif strcmp(cfg.latency,'prestim') cfg.latency = [min(begTrialLatency) 0]; elseif strcmp(cfg.latency,'poststim') cfg.latency = [0 max(endTrialLatency)]; end function [cfg] = trialselection(cfg,spike) % get the number of trials or change DATA according to cfg.trials nTrials = size(spike.trialtime,1); if strcmp(cfg.trials,'all') cfg.trials = 1:nTrials; elseif islogical(cfg.trials) cfg.trials = find(cfg.trials); end cfg.trials = sort(cfg.trials(:)); if max(cfg.trials)>nTrials, error('maximum trial number in cfg.trials should not exceed size(spike.trialtime,1)'); end if isempty(cfg.trials), error('no trials were selected by you'); end
github
lcnbeapp/beapp-master
ft_spike_plot_psth.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spike_plot_psth.m
6,983
utf_8
dcbec74860c44d235aad797cfe733489
function [cfg] = ft_spike_plot_psth(cfg, psth) % FT_SPIKE_PLOT_PSTH makes a bar plot of PSTH structure with error bars. % % Use as % ft_spike_plot_psth(cfg, psth) % % Inputs: % PSTH typically is a structure from FT_SPIKE_PSTH. % % Configurations: % cfg.latency = [begin end] in seconds, 'maxperiod' (default), 'prestim'(t<=0), or % 'poststim' (t>=0). % cfg.errorbars = 'no', 'std', 'sem' (default), 'conf95%' (requires statistic toolbox, % according to student-T distribution), 'var' % cfg.spikechannel = string or index of single spike channel to trigger on (default = 1) % Only one spikechannel can be plotted at a time. % cfg.ylim = [min max] or 'auto' (default) % If 'standard', we plot from 0 to 110% of maximum plotted value); % Outputs: % cfg.hdl.avg = figure handle for the bar plot, psth average. % cfg.hdl.var = figure handle for the error lines. % % See also FT_SPIKE_PSTH % Copyright (C) 2010, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % check the psth datatype psth = ft_checkdata(psth, 'datatype', 'timelock', 'feedback', 'yes'); % get the default options cfg.spikechannel = ft_getopt(cfg, 'spikechannel', 'all'); cfg.latency = ft_getopt(cfg,'latency','maxperiod'); cfg.errorbars = ft_getopt(cfg,'errorbars', 'sem'); cfg.ylim = ft_getopt(cfg,'ylim', 'auto'); % ensure that the options are valid cfg = ft_checkopt(cfg,'spikechannel',{'cell', 'char', 'double'}); cfg = ft_checkopt(cfg,'latency', {'char', 'ascendingdoublebivector'}); cfg = ft_checkopt(cfg,'errorbars', 'char', {'sem', 'std', 'conf95%', 'no', 'var'}); cfg = ft_checkopt(cfg,'ylim', {'char', 'ascendingdoublebivector'}); cfg = ft_checkconfig(cfg, 'allowed', {'spikechannel', 'latency', 'errorbars', 'ylim'}); % select the latencies if ischar(cfg.latency) if strcmp(cfg.latency, 'maxperiod') cfg.latency = [min(psth.time) max(psth.time)]; elseif strcmp(cfg.latency, 'prestim') cfg.latency = [min(psth.time) 0]; elseif strcmp(cfg.latency, 'poststim') cfg.latency = [0 max(psth.time)]; end end % check whether the time window fits with the data if cfg.latency(1) < min(psth.time), cfg.latency(1) = min(psth.time); warning('Correcting begin latency of averaging window'); end if (cfg.latency(2) > max(psth.time)), cfg.latency(2) = max(psth.time); warning('Correcting begin latency of averaging window'); end % get the spikechannels cfg.spikechannel = ft_channelselection(cfg.spikechannel, psth.label); spikesel = match_str(psth.label, cfg.spikechannel); nUnits = length(spikesel); if nUnits~=1, error('You selected more or less than one spikechannel by means of cfg.spikechannel'); end % select the timepoints within the latencies timeSel = psth.time>=cfg.latency(1) & psth.time <= cfg.latency(2); if isempty(timeSel), error('no time points selected, please change cfg.latency or inspect input PSTH');end % plot the average psth psthHdl = bar(psth.time(timeSel),psth.avg(spikesel,timeSel),'k'); set(psthHdl,'BarWidth', 1) % check if fields .dof and .var are correct given cfg.errorbars if ~strcmp(cfg.errorbars,'no') if ~isfield(psth,'var') || ~any(isfinite(psth.var(spikesel,:))) error('PSTH should contain field .var with numbers'); end if ~ (strcmp(cfg.errorbars,'std') || strcmp(cfg.errorbars,'var')) if ~isfield(psth,'dof') || ~any(isfinite(psth.dof(spikesel,:))) error('psth should contain field dof that contains numbers.'); end end end % add standard error bars to it x = [psth.time(timeSel);psth.time(timeSel)]; % create x doublets if strcmp(cfg.errorbars, 'sem') err = sqrt(psth.var(spikesel,timeSel)./psth.dof(timeSel)); elseif strcmp(cfg.errorbars, 'std') err = sqrt(psth.var(spikesel,timeSel)); elseif strcmp(cfg.errorbars, 'var') err = psth.var(spikesel,timeSel); elseif strcmp(cfg.errorbars, 'conf95%') % use a try statement just in case the statistics toolbox doesn't work. try tCrit = tinv(0.975,psth.dof(timeSel)); err = tCrit.*sqrt(psth.var(spikesel,timeSel)./psth.dof(timeSel)); % assuming normal distribution, SHOULD BE REPLACED BY STUDENTS-T! catch err = 0; end else err = 0; end y = psth.avg(spikesel,timeSel) + err; % create the error values % plot the errorbars as line plot on top of the bar plot if ~strcmp(cfg.errorbars,'no') hold on y = [zeros(1,length(y));y]; % let lines run from 0 to error values psthSemHdl = plot(x,y,'k'); % plot the error bars end % create labels xlabel('bin centers (sec)') try ylabel(psth.cfg.outputunit) catch ylabel('firing intensity') end % set the axis if strcmp(cfg.ylim, 'auto'), cfg.ylim = [0 max(y(:))*1.1+eps]; end if cfg.ylim(2)<max(y(:)) warning('correcting cfg.ylim(2) as it clips the data'); cfg.ylim(2) = max(y(:))*1.1+eps; end set(gca,'YLim', cfg.ylim, 'XLim', cfg.latency) set(gca,'TickDir','out', 'Box', 'off') % store the handles cfg.hdl.avg = psthHdl; if ~strcmp(cfg.errorbars,'no'), cfg.hdl.var = psthSemHdl; end % as usual, make sure that panning and zooming does not distort the y limits set(zoom,'ActionPostCallback',{@mypostcallback,cfg.ylim,cfg.latency}); set(pan,'ActionPostCallback',{@mypostcallback,cfg.ylim,cfg.latency}); % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous psth %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = mypostcallback(fig,evd,limY,limX) % get the x limits and reset them ax = evd.Axes; xlim = get(ax(1), 'XLim'); ylim = get(ax(1), 'YLim'); if limX(1)>xlim(1), xlim(1) = limX(1); end if limX(2)<xlim(2), xlim(2) = limX(2); end if limY(1)>ylim(1), ylim(1) = limY(1); end if limY(2)<ylim(2), ylim(2) = limY(2); end set(ax(1), 'XLim',xlim) set(ax(1), 'YLim',ylim);
github
lcnbeapp/beapp-master
ft_spiketriggeredspectrum_stat.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spiketriggeredspectrum_stat.m
20,734
utf_8
e8056c172557b5150d15a058d443c647
function [freq] = ft_spiketriggeredspectrum_stat(cfg,spike) % FT_SPIKETRIGGEREDSPECTRUM_STAT computes phase-locking statistics for spike-LFP % phases. These contain the PPC statistics according to Vinck et al. 2010 (Neuroimage) % and Vinck et al. 2011 (Journal of Computational Neuroscience). % % Use as: % [stat] = ft_spiketriggeredspectrum_stat(cfg, spike) % % Inputs: % SPIKE should be a structure as obtained from from the FT_SPIKETRIGGEREDSPECTRUM function. % % Configurations (cfg) % % cfg.method = string, indicating which statistic to compute. Can be: % -'plv' : phase-locking value, computes the resultant length over spike % phases. More spikes -> lower value (bias). % -'ang' : computes the angular mean of the spike phases. % -'ral' : computes the rayleigh p-value. % -'ppc0': computes the pairwise-phase consistency across all available % spike pairs (Vinck et al., 2010). % -'ppc1': computes the pairwise-phase consistency across all available % spike pairs with exclusion of spike pairs in the same trial. % This avoids history effects within spike-trains to influence % phase lock statistics. % -'ppc2': computes the PPC across all spike pairs with exclusion of % spike pairs in the same trial, but applies a normalization % for every set of trials. This estimator has more variance but % is more robust against dependencies between spike phase and % spike count. % % cfg.timwin = double or 'all' (default) % - double: indicates we compute statistic with a % sliding window of cfg.timwin, i.e. time-resolved analysis. % - 'all': we compute statistic over all time-points, % i.e. in non-time resolved fashion. % % cfg.winstepsize = double, stepsize of sliding window in seconds. For % example if cfg.winstepsize = 0.1, we compute stat every other 100 ms. % % cfg.channel = Nx1 cell-array or numerical array with selection of % channels (default = 'all'),See CHANNELSELECTION for details % % cfg.spikechannel = label of ONE unit, according to FT_CHANNELSELECTION % % cfg.spikesel = 'all' (default) or numerical or logical selection of spikes. % % cfg.foi = 'all' or numerical vector that specifies a subset of % frequencies in Hz, e.g. cfg.foi = spike.freq(1:10); % % cfg.latency = [beg end] in sec, or 'maxperiod', 'poststim' or % 'prestim'. This determines the start and end of analysis window. % % cfg.avgoverchan = 'weighted', 'unweighted' (default) or 'no'. % This regulates averaging of fourierspectra prior to % computing the statistic. % - 'weighted' : we average across channels by weighting by the LFP power. % This is identical to adding the raw LFP signals in time % and then taking their FFT. % - 'unweighted': we average across channels after normalizing for LFP power. % This is identical to normalizing LFP signals for % their power, averaging them, and then taking their FFT. % - 'no' : no weighting is performed, statistic is computed for % every LFP channel. % cfg.trials = vector of indices (e.g., 1:2:10), % logical selection of trials (e.g., [1010101010]), or % 'all' (default) % % Main outputs: % stat.nspikes = nChancmb-by-nFreqs-nTimepoints number % of spikes used to compute stat % stat.dimord = 'chan_freq_time' % stat.labelcmb = nChancmbs cell array with spike vs % LFP labels % stat.(cfg.method) = nChancmb-by-nFreqs-nTimepoints statistic % stat.freq = 1xnFreqs array of frequencies % stat.nspikes = number of spikes used to compute % % The output stat structure can be plotted using ft_singleplotTFR or ft_multiplotTFR. % Copyright (C) 2012, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % check if the data is of spike format, and convert from old format if required spike = ft_checkdata(spike,'datatype', 'spike', 'feedback', 'yes'); % get the options cfg.method = ft_getopt(cfg, 'method', 'ppc1'); cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.spikechannel = ft_getopt(cfg, 'spikechannel', spike.label{1}); cfg.latency = ft_getopt(cfg, 'latency', 'maxperiod'); cfg.spikesel = ft_getopt(cfg, 'spikesel', 'all'); cfg.avgoverchan = ft_getopt(cfg, 'avgoverchan', 'no'); cfg.foi = ft_getopt(cfg, 'foi', 'all'); cfg.trials = ft_getopt(cfg, 'trials', 'all'); cfg.timwin = ft_getopt(cfg, 'timwin', 'all'); cfg.winstepsize = ft_getopt(cfg, 'winstepsize', 0.01); % ensure that the options are valid cfg = ft_checkopt(cfg, 'method', 'char', {'ppc0', 'ppc1', 'ppc2', 'ang', 'ral', 'plv'}); cfg = ft_checkopt(cfg, 'foi',{'char', 'double'}); cfg = ft_checkopt(cfg, 'spikechannel',{'cell', 'char', 'double'}); cfg = ft_checkopt(cfg, 'channel', {'cell', 'char', 'double'}); cfg = ft_checkopt(cfg, 'spikesel', {'char', 'logical', 'double'}); cfg = ft_checkopt(cfg, 'avgoverchan', 'char', {'weighted', 'unweighted', 'no'}); cfg = ft_checkopt(cfg, 'latency', {'char', 'doublevector'}); cfg = ft_checkopt(cfg, 'trials', {'char', 'double', 'logical'}); cfg = ft_checkopt(cfg, 'timwin', {'double', 'char'}); cfg = ft_checkopt(cfg, 'winstepsize', {'double'}); cfg = ft_checkconfig(cfg, 'allowed', {'method', 'channel', 'spikechannel', 'latency', 'spikesel', 'avgoverchan', 'foi', 'trials', 'timwin', 'winstepsize'}); % collect channel information cfg.channel = ft_channelselection(cfg.channel, spike.lfplabel); chansel = match_str(spike.lfplabel, cfg.channel); % get the spikechannels spikelabel = spike.label; cfg.spikechannel = ft_channelselection(cfg.spikechannel, spikelabel); unitsel = match_str(spikelabel, cfg.spikechannel); nspikesel = length(unitsel); % number of spike channels if nspikesel>1, error('only one unit should be selected for now'); end if nspikesel==0, error('no unit was selected'); end % collect frequency information if strcmp(cfg.foi, 'all'), cfg.foi = spike.freq(:)'; freqindx = 1:length(spike.freq); else freqindx = zeros(1,length(foi)); for iFreq = 1:length(cfg.foi) freqindx(iFreq) = nearest(spike.freq,cfg.foi(iFreq)); end end if length(freqindx)~=length(unique(freqindx)) error('Please select every frequency only once, are you sure you selected in Hz?') end nFreqs = length(freqindx); cfg.foi = spike.freq(freqindx); % update the information again % create the spike selection nSpikes = length(spike.trial{unitsel}); if strcmp(cfg.spikesel,'all'), cfg.spikesel = 1:length(spike.trial{unitsel}); elseif islogical(cfg.spikesel) cfg.spikesel = find(cfg.spikesel); end if ~isempty(cfg.spikesel) if max(cfg.spikesel)>nSpikes || length(cfg.spikesel)>nSpikes error('cfg.spikesel must not exceed number of spikes and select every spike just once') end end % select on basis of latency if strcmp(cfg.latency, 'maxperiod'), cfg.latency = [min(spike.trialtime(:)) max(spike.trialtime(:))]; elseif strcmp(cfg.latency,'prestim') cfg.latency = [min(spike.trialtime(:)) 0]; elseif strcmp(cfg.latency,'poststim') cfg.latency = [0 max(spike.trialtime(:))]; elseif ~isrealvec(cfg.latency) && length(cfg.latency)~=2 error('cfg.latency should be "maxperiod", "prestim", "poststim" or 1-by-2 numerical vector'); end if cfg.latency(1)>=cfg.latency(2), error('cfg.latency should be a vector in ascending order, i.e., cfg.latency(2)>cfg.latency(1)'); end inWindow = find(spike.time{unitsel}>=cfg.latency(1) & cfg.latency(2)>=spike.time{unitsel}); % selection of the trials cfg = trialselection(cfg,spike); % do the final selection, and select on spike structure isintrial = ismember(spike.trial{unitsel}, cfg.trials); spikesel = intersect(cfg.spikesel(:),inWindow(:)); spikesel = intersect(spikesel,find(isintrial)); cfg.spikesel = spikesel; spikenum = length(cfg.spikesel); % number of spikes that were finally selected if isempty(spikenum), warning('No spikes were selected after applying cfg.latency, cfg.spikesel and cfg.trials'); end spike.fourierspctrm = spike.fourierspctrm{unitsel}(cfg.spikesel,chansel,freqindx); spike.time = spike.time{unitsel}(cfg.spikesel); spike.trial = spike.trial{unitsel}(cfg.spikesel); % average the lfp channels (weighted, unweighted, or not) if strcmp(cfg.avgoverchan,'unweighted') spike.fourierspctrm = spike.fourierspctrm ./ abs(spike.fourierspctrm); % normalize the angles before averaging spike.fourierspctrm = nanmean(spike.fourierspctrm,2); % now rep x 1 x freq nChans = 1; outlabels = {'avgLFP'}; elseif strcmp(cfg.avgoverchan,'no') nChans = length(chansel); outlabels = cfg.channel; elseif strcmp(cfg.avgoverchan,'weighted') spike.fourierspctrm = nanmean(spike.fourierspctrm,2); % now rep x 1 x freq outlabels = {'avgLFP'}; nChans = 1; end % normalize the spectrum first spike.fourierspctrm = spike.fourierspctrm ./ abs(spike.fourierspctrm); % normalize the angles before averaging ft_progress('init', 'text', 'Please wait...'); if strcmp(cfg.timwin,'all') freq.time = 'all'; switch cfg.method case 'ang' out = angularmean(spike.fourierspctrm); case 'plv' out = resultantlength(spike.fourierspctrm); case 'ral' out = rayleightest(spike.fourierspctrm); % the rayleigh test case 'ppc0' out = ppc(spike.fourierspctrm); case {'ppc1', 'ppc2'} % check the final set of trials present in the spikes trials = unique(spike.trial); % loop init for PPC 2.0 [S,SS,dof,dofSS] = deal(zeros(1,nChans,nFreqs)); nTrials = length(trials); if nTrials==1 warning('computing ppc1 or ppc2 can only be performed with more than 1 trial'); end for iTrial = 1:nTrials % compute the firing rate trialNum = trials(iTrial); spikesInTrial = find(spike.trial == trialNum); spc = spike.fourierspctrm(spikesInTrial,:,:); ft_progress(iTrial/nTrials, 'Processing trial %d from %d', iTrial, nTrials); % compute PPC 1.0 and 2.0 according to Vinck et al. (2011) using summation per trial if strcmp(cfg.method,'ppc2') if ~isempty(spc) m = nanmean(spc,1); % no problem with NaN hasNum = ~isnan(m); S(hasNum) = S(hasNum) + m(hasNum); % add the imaginary and real components SS(hasNum) = SS(hasNum) + m(hasNum).*conj(m(hasNum)); dof(hasNum) = dof(hasNum) + 1; % dof needs to be kept per frequency end elseif strcmp(cfg.method,'ppc1') if ~isempty(spc) n = sum(~isnan(spc),1); m = nansum(spc,1); hasNum = ~isnan(m); S(hasNum) = S(hasNum) + m(hasNum); % add the imaginary and real components SS(hasNum) = SS(hasNum) + m(hasNum).*conj(m(hasNum)); dof(hasNum) = dof(hasNum) + n(hasNum); dofSS(hasNum) = dofSS(hasNum) + n(hasNum).^2; end end end [out] = deal(NaN(1,nChans,nFreqs)); hasTrl = dof>1; if strcmp(cfg.method,'ppc1') out(hasTrl) = (S(hasTrl).*conj(S(hasTrl)) - SS(hasTrl))./(dof(hasTrl).^2 - dofSS(hasTrl)); elseif strcmp(cfg.method, 'ppc2') out(hasTrl) = (S(hasTrl).*conj(S(hasTrl)) - SS(hasTrl))./(dof(hasTrl).*(dof(hasTrl)-1)); end end nSpikes = sum(~isnan(spike.fourierspctrm)); else % compute time-resolved spectra of statistic % make the sampling axis for the window bins = cfg.latency(1):cfg.winstepsize:cfg.latency(2); N = length(bins)-1; % number of bins wintime = 0:cfg.winstepsize:cfg.timwin; win = ones(1,length(wintime)); freq.time = (bins(2:end)+bins(1:end-1))/2; if ~mod(length(win),2), win = [win 1]; end % make sure the number of samples is uneven. out = NaN(N,nChans,nFreqs); nSpikes = zeros(N,nChans,nFreqs); for iChan = 1:nChans for iFreq = 1:nFreqs spctra = spike.fourierspctrm(:,iChan,iFreq); % values to accumulate tm = spike.time; hasnan = isnan(spctra); tm(hasnan) = []; spctra(hasnan) = []; % compute the degree of freedom per time bin and the index for every spike [dof, indx] = histc(tm, bins); % get the index per spike, and number per bin if isempty(dof), continue,end toDel = indx==length(bins) | indx==0; % delete those points that are equal to last output histc or don't fall in spctra(toDel) = []; indx(toDel) = []; dof(end) = []; % the last bin is a single point in time, so we delete it % compute the sum of spikes per window at every time point dof = dof(:); % force it to be row dof = conv2(dof(:),win(:),'same'); % get the total number of spikes across all trials nSpikes(:,iChan,iFreq) = dof; switch cfg.method case {'ang', 'plv', 'ppc0', 'ral'} % first create a vector with the phases at the samples x = accumarray(indx(:),spctra,[N 1]); % simply the sum of the complex numbers % then compute the sum of the spectra for every timepoint y = conv2(x(:),win(:),'same'); % now compute the output statistic hasnum = dof>1; hasnum0 = dof>0; if strcmp(cfg.method,'plv') out(hasnum,iChan,iFreq) = abs(y(hasnum)./dof(hasnum)); elseif strcmp(cfg.method,'ral') Z = abs(y).^2./dof; P = exp(-Z) .* (1 + (2*Z - Z.^2)./(4*dof) -(24.*Z - 123*(Z.^2) + 76*(Z.^3) - 9*(Z.^4))./(288*dof.^2)); %Mardia 1972 out(hasnum,iChan,iFreq) = P(hasnum); elseif strcmp(cfg.method,'ang') out(hasnum0,iChan,iFreq) = angle(y(hasnum0)); % elseif strcmp(cfg.method,'ppc0') out(hasnum,iChan,iFreq) = (y(hasnum).*conj(y(hasnum)) - dof(hasnum))./(dof(hasnum).*(dof(hasnum)-1)); % simplest form of ppc end case {'ppc1', 'ppc2'} trials = unique(spike.trial); nTrials = length(trials); [S,SS,dofS,dofSS] = deal(zeros(length(bins)-1,1)); if nTrials==1 warning('computing ppc1 or ppc2 can only be performed with more than 1 trial'); end % compute the new ppc versions for iTrial = 1:nTrials ft_progress(iTrial/nTrials, 'Processing trial %d from %d for freq %d and chan %d', iTrial, nTrials, iFreq, iChan); % select the spectra, time points, and trial numbers again trialNum = trials(iTrial); spikesInTrial = find(spike.trial == trialNum); if isempty(spikesInTrial), continue,end spctraTrial = spike.fourierspctrm(spikesInTrial,iChan,iFreq); tm = spike.time; hasnan = isnan(spctraTrial); tm(hasnan) = []; spctraTrial(hasnan) = []; % bin the spikes and delete spikes out of the selected time [dof, indx] = histc(tm(spikesInTrial), bins); % get the index per spike, and number per bin dof(end) = []; toDel = indx==length(bins) | indx==0; % delete those points that are equal to last output histc spctraTrial(toDel,:,:) = []; % delete those spikes from fourierspctrm as well indx(toDel) = []; % make sure index doesn't contain them % first create a vector that sums the spctra x = accumarray(indx(:),spctraTrial,[N 1]); % then compute the moving average sum of this vector y = conv2(x(:),win(:),'same'); % convolution again just means a sum d = conv2(dof(:),win(:),'same'); % get the dof of spikes per trial if strcmp(cfg.method,'ppc1') S = S + y; % add the imaginary and real components SS = SS + y.*conj(y); dofS = dofS + d(:); dofSS = dofSS + d(:).^2; else sl = d(:)>0; m = y./d(:); S(sl) = S(sl) + m(sl); % add the imaginary and real components SS(sl) = SS(sl) + m(sl).*conj(m(sl)); dofS(sl) = dofS(sl) + 1; end end % we need at least two trials hasNum = dofS>1; if strcmp(cfg.method,'ppc1') out(hasNum,iChan,iFreq) = (S(hasNum).*conj(S(hasNum)) - SS(hasNum))./(dofS(hasNum).^2 - dofSS(hasNum)); else out(hasNum,iChan,iFreq) = (S(hasNum).*conj(S(hasNum)) - SS(hasNum))./(dofS(hasNum).*(dofS(hasNum)-1)); end end end end end ft_progress('close'); % collect the outputs: in labelcmb representation outparam = cfg.method; freq.(outparam) = permute(out,[2 3 1]); freq.nspikes = permute(nSpikes,[2 3 1]); % also cross-unit purposes freq.labelcmb = cell(nChans,2); freq.labelcmb(1:nChans,1) = cfg.spikechannel; for iCmb = 1:nChans freq.labelcmb{iCmb,2} = outlabels{iCmb}; end freq.freq = spike.freq(freqindx); freq.dimord = 'chancmb_freq_time'; % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous spike ft_postamble history freq function [P] = rayleightest(x) n = sum(~isnan(x),1); R = resultantlength(x); Z = n.*R.^2; P = exp(-Z).*... (1 + (2*Z - Z.^2)./(4*n) -(24.*Z - 123*(Z.^2) + 76*(Z.^3) - 9*(Z.^4))./(288*n.^2)); %Mardia 1972 function [resLen] = resultantlength(angles) n = sum(~isnan(angles),1); resLen = abs(nansum(angles,1))./n;%calculate the circular variance function [y] = ppc(crss) dim = 1; dof = sum(~isnan(crss),dim); sinSum = abs(nansum(imag(crss),dim)); cosSum = nansum(real(crss),dim); y = (cosSum.^2+sinSum.^2 - dof)./(dof.*(dof-1)); function [angMean] = angularmean(angles) angMean = angle(nanmean(angles,1)); %get the mean angle function [cfg] = trialselection(cfg,spike) % get the number of trials or change DATA according to cfg.trials nTrials = size(spike.trialtime,1); if strcmp(cfg.trials, 'all') cfg.trials = 1:nTrials; elseif islogical(cfg.trials) cfg.trials = find(cfg.trials); end cfg.trials = sort(cfg.trials(:)); if max(cfg.trials)>nTrials, warning('maximum trial number in cfg.trials should not exceed length of DATA.trial') end if isempty(cfg.trials), error('No trials were selected'); end function m = nansum(x,dim) % Find NaNs and set them to zero nans = isnan(x); x(nans) = 0; if nargin == 1 % let sum deal with figuring out which dimension to use % Count up non-NaNs. n = sum(~nans); n(n==0) = NaN; % prevent divideByZero warnings % Sum up non-NaNs, and divide by the number of non-NaNs. m = sum(x); else % Count up non-NaNs. n = sum(~nans,dim); n(n==0) = NaN; % prevent divideByZero warnings % Sum up non-NaNs, and divide by the number of non-NaNs. m = sum(x,dim); end
github
lcnbeapp/beapp-master
ft_spike_select.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spike_select.m
7,381
utf_8
17594cc9b902b58cd372eac21bf3272f
function [spike] = ft_spike_select(cfg,spike) % FT_SPIKE_SELECT selects subsets of spikes, channels and trials from a % spike structure % % Use as % [spike] = ft_spike_select(cfg, spike) % % The input SPIKE should be organised as the spike datatype (see % FT_DATATYPE_SPIKE) % % Configurations: % cfg.spikechannel = See FT_CHANNELSELECTION for details. % cfg.trials = vector of indices (e.g., 1:2:10) % logical selection of trials (e.g., [1010101010]) % 'all' (default), selects all trials % cfg.latency = [begin end] in seconds % 'maxperiod' (default), i.e., maximum period available % 'minperiod', i.e., the minimal period all trials share % 'prestim' (all t<=0) % 'poststim' (all t>=0). % Outputs: % Spike structure with selections % Copyright (C) 2012, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % control input spike structure spike = ft_checkdata(spike,'datatype', 'spike', 'feedback', 'yes'); % get the default options cfg.spikechannel = ft_getopt(cfg, 'spikechannel', 'all'); cfg.trials = ft_getopt(cfg, 'trials', 'all'); cfg.latency = ft_getopt(cfg, 'latency', 'maxperiod'); % ensure that the options are valid cfg = ft_checkopt(cfg,'spikechannel',{'cell', 'char', 'double'}); cfg = ft_checkopt(cfg,'latency', {'char', 'ascendingdoublebivector'}); cfg = ft_checkopt(cfg,'trials', {'char', 'doublevector', 'logical'}); % select the desired channels doAll = strcmp(cfg.spikechannel,'all'); try cfg.spikechannel = ft_channelselection(cfg.spikechannel, spike.label); catch [I,J] = unique(spike.label, 'first'); label = spike.label(J); cfg.spikechannel = ft_channelselection(cfg.spikechannel, label); end spikesel = match_str(spike.label, cfg.spikechannel); nUnits = length(spikesel); if nUnits==0, error('no spikechannel selected by means of cfg.spikechannel');end doAllTrials = strcmp(cfg.trials,'all'); doAllLatencies = strcmp(cfg.latency,'maxperiod'); % select the desired channels if ~doAll fprintf('Selecting channels\n'); try, spike.time = spike.time(spikesel); end try, spike.trial = spike.trial(spikesel); end try, spike.waveform = spike.waveform(spikesel); end try, spike.timestamp = spike.timestamp(spikesel); end try, spike.unit = spike.unit(spikesel); end try, spike.fourierspctrm = spike.fourierspctrm(spikesel); end try, spike.label = spike.label(spikesel); end end % select the desired trials if ~isfield(spike,'trial') | ~isfield(spike,'trialtime') | ~isfield(spike,'time') if ~doAllTrials warning('spike structure does not contain trial, time or trialtime field, cannot select trials'); end else doSelection = ~strcmp(cfg.trials,'all'); cfg = trialselection(cfg,spike); if doSelection fprintf('Selecting trials\n'); nUnits = length(spike.trial); for iUnit = 1:nUnits spikesInTrial = ismember(spike.trial{iUnit},cfg.trials); % get spikes in trial spike.trial{iUnit} = spike.trial{iUnit}(spikesInTrial); spike.time{iUnit} = spike.time{iUnit}(spikesInTrial); try, spike.timestamp{iUnit} = spike.timestamp{iUnit}(spikesInTrial); end try, spike.waveform{iUnit} = spike.waveform{iUnit}(spikesInTrial); end try, spike.unit{iUnit} = spike.unit{iUnit}(spikesInTrial); end try, spike.fourierspctrm{iUnit} = spike.fourierspctrm{iUnit}(spikesInTrial,:,:); end end warning('No selection is performed on spike.trialtime and spike.sampleinfo'); % Note: .trialtime and .sampleinfo are explicitly left intact, as the % relationship between trial number and trialtime becomes ambigious % otherwise! end end % select the desired latencies if ~isfield(spike, 'trialtime') || ~isfield(spike,'time') || ~isfield(spike,'trial') if ~doAllLatencies warning('cannot select latencies as either .trialtime, .time or .trial is missing'); end else if ~strcmp(cfg.latency,'maxperiod') % otherwise, all spikes are selected fprintf('Selecting on latencies\n'); begTrialLatency = spike.trialtime(cfg.trials,1); endTrialLatency = spike.trialtime(cfg.trials,2); cfg = latencyselection(cfg,begTrialLatency,endTrialLatency); for iUnit = 1:nUnits spikesInWin = spike.time{iUnit}>=cfg.latency(1) & spike.time{iUnit}<=cfg.latency(2); % get spikes in trial spike.trial{iUnit} = spike.trial{iUnit}(spikesInWin); spike.time{iUnit} = spike.time{iUnit}(spikesInWin); try, spike.timestamp{iUnit} = spike.timestamp{iUnit}(spikesInWin); end try, spike.waveform{iUnit} = spike.waveform{iUnit}(spikesInWin); end try, spike.unit{iUnit} = spike.unit{iUnit}(spikesInWin); end try, spike.fourierspctrm{iUnit} = spike.fourierspctrm{iUnit}(spikesInWin,:,:); end end % modify the trialtime adjust = spike.trialtime(:,1)<=cfg.latency(1); spike.trialtime(adjust,1) = cfg.latency(1); adjust = spike.trialtime(:,2)>=cfg.latency(2); spike.trialtime(adjust,2) = cfg.latency(2); % FIXME: change sampleinfo field automatically again, for now remove. try, spike = rmfield(spike,'sampleinfo'); end end end % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous spike ft_postamble history spike %%%%%%%%% SUB FUNCTIONS %%%%%%%%% function [cfg] = latencyselection(cfg,begTrialLatency,endTrialLatency) if strcmp(cfg.latency,'minperiod') cfg.latency = [max(begTrialLatency) min(endTrialLatency)]; elseif strcmp(cfg.latency,'maxperiod') cfg.latency = [min(begTrialLatency) max(endTrialLatency)]; elseif strcmp(cfg.latency,'prestim') cfg.latency = [min(begTrialLatency) 0]; elseif strcmp(cfg.latency,'poststim') cfg.latency = [0 max(endTrialLatency)]; end %%% function [cfg] = trialselection(cfg,spike) % get the number of trials or change DATA according to cfg.trials nTrials = size(spike.trialtime,1); if strcmp(cfg.trials,'all') cfg.trials = 1:nTrials; elseif islogical(cfg.trials) cfg.trials = find(cfg.trials); end cfg.trials = sort(cfg.trials(:)); if max(cfg.trials)>nTrials, error('maximum trial number in cfg.trials should not exceed length of spike.trialtime') end if isempty(cfg.trials), error('No trials were selected'); end
github
lcnbeapp/beapp-master
ft_spiketriggeredspectrum_fft.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spiketriggeredspectrum_fft.m
13,060
utf_8
9ddd1c3908a218f53afc3cd852cffd4b
function [sts] = ft_spiketriggeredspectrum_fft(cfg, data, spike) % FT_SPIKETRIGGEREDSPECTRUM_FFT computes the Fourier spectrum (amplitude and phase) % of the LFP around the % spikes. A phase of zero corresponds to the spike being on % the peak of the LFP oscillation. A phase of 180 degree corresponds to the spike being % in the through of the oscillation. A phase of 45 degrees corresponds to the spike % being just after the peak in the LFP. % % If the triggered spike leads a spike in another channel, then the angle of the Fourier % spectrum of that other channel will be negative. Earlier phases are in clockwise % direction. % % Use as % [sts] = ft_spiketriggeredspectrum_convol(cfg,data,spike) % or % [sts] = ft_spiketriggeredspectrum_convol(cfg,data) % where the spike data can either be contained in the DATA input or in the SPIKE input. % % The input DATA should be organised as the raw datatype, obtained from FT_PREPROCESSING % or FT_APPENDSPIKE. % % The (optional) input SPIKE should be organised as the spike or the raw datatype, % obtained from FT_SPIKE_MAKETRIALS or FT_PREPROCESSING (in that case, conversion is done % within the function) % % Important is that data.time and spike.trialtime should be referenced relative to the % same trial trigger times. % % The configuration should be according to % cfg.timwin = [begin end], time around each spike (default = [-0.1 0.1]) % cfg.foilim = [begin end], frequency band of interest (default = [0 150]) % cfg.taper = 'dpss', 'hanning' or many others, see WINDOW (default = 'hanning') % cfg.tapsmofrq = number, the amount of spectral smoothing through % multi-tapering. Note that 4 Hz smoothing means plus-minus 4 Hz, % i.e. a 8 Hz smoothing box. Note: multitapering rotates phases (no % problem for consistency) % cfg.spikechannel = string, name of spike channels to trigger on cfg.channel = Nx1 % cell-array with selection of channels (default = 'all'), % see FT_CHANNELSELECTION for details % cfg.feedback = 'no', 'text', 'textbar', 'gui' (default = 'no') % % The output STS data structure can be input to FT_SPIKETRIGGEREDSPECTRUM_STAT % % This function uses a NaN-aware spectral estimation technique, which will default to the % standard Matlab FFT routine if no NaNs are present. The fft_along_rows subfunction below % demonstrates the expected function behaviour. % % See FT_SPIKETRIGGEREDINTERPOLATION to remove segments of LFP around spikes. % See FT_SPIKETRIGGEREDSPECTRUM_CONVOL for an alternative implementation based % on convolution % Copyright (C) 2008, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % check input data structure data = ft_checkdata(data,'datatype', 'raw', 'feedback', 'yes'); if nargin==3 spike = ft_checkdata(spike, 'datatype', {'spike'}, 'feedback', 'yes'); end % these were supported in the past, but are not any more (for consistency with other spike functions) cfg = ft_checkconfig(cfg, 'forbidden', {'inputfile','outputfile'}); %get the options cfg.timwin = ft_getopt(cfg, 'timwin',[-0.1 0.1]); cfg.spikechannel = ft_getopt(cfg,'spikechannel', 'all'); cfg.channel = ft_getopt(cfg,'channel', 'all'); cfg.feedback = ft_getopt(cfg,'feedback', 'no'); cfg.tapsmofrq = ft_getopt(cfg,'tapsmofrq', 4); cfg.taper = ft_getopt(cfg,'taper', 'hanning'); cfg.foilim = ft_getopt(cfg,'foilim', [0 150]); % ensure that the options are valid cfg = ft_checkopt(cfg,'timwin','doublevector'); cfg = ft_checkopt(cfg,'spikechannel',{'cell', 'char', 'double', 'empty'}); cfg = ft_checkopt(cfg,'channel', {'cell', 'char', 'double'}); cfg = ft_checkopt(cfg,'feedback', 'char', {'yes', 'no'}); cfg = ft_checkopt(cfg,'taper', 'char'); cfg = ft_checkopt(cfg,'tapsmofrq', 'doublescalar'); cfg = ft_checkopt(cfg,'foilim', 'doublevector'); if strcmp(cfg.taper, 'sine') error('sorry, sine taper is not yet implemented'); end % get the spikechannels if nargin==2 % autodetect the spikechannels and EEG channels [spikechannel, eegchannel] = detectspikechan(data); % make the final selection of spike channels and check if strcmp(cfg.spikechannel, 'all'), cfg.spikechannel = spikechannel; else cfg.spikechannel = ft_channelselection(cfg.spikechannel, data.label); if ~all(ismember(cfg.spikechannel,spikechannel)), error('some selected spike channels appear eeg channels'); end end % make the final selection of EEG channels and check if strcmp(cfg.channel,'all') cfg.channel = eegchannel; else cfg.channel = ft_channelselection(cfg.channel, data.label); if ~all(ismember(cfg.channel,eegchannel)), warning('some of the selected eeg channels appear spike channels'); end end % select the data and convert to a spike structure data_spk = ft_selectdata(data,'channel', cfg.spikechannel); data = ft_selectdata(data,'channel', cfg.channel); % leave only LFP spike = ft_checkdata(data_spk,'datatype', 'spike'); clear data_spk % remove the continuous data else cfg.spikechannel = ft_channelselection(cfg.spikechannel, spike.label); cfg.channel = ft_channelselection(cfg.channel, data.label); end % determine the channel indices and number of chans chansel = match_str(data.label, cfg.channel); % selected channels nchansel = length(cfg.channel); % number of channels spikesel = match_str(spike.label, cfg.spikechannel); nspikesel = length(spikesel); % number of spike channels if nspikesel==0, error('no spike channel selected'); end % construct the taper if ~isfield(data, 'fsample'), data.fsample = 1/mean(diff(data.time{1})); end begpad = round(cfg.timwin(1)*data.fsample); endpad = round(cfg.timwin(2)*data.fsample); numsmp = endpad - begpad + 1; if ~strcmp(cfg.taper,'dpss') taper = window(cfg.taper, numsmp); taper = taper./norm(taper); else % not implemented yet: keep tapers, or selecting only a subset of them. taper = dpss(numsmp, cfg.tapsmofrq); taper = taper(:,1:end-1); % we get 2*NW-1 tapers taper = sum(taper,2)./size(taper,2); % using the linearity of multitapering end taper = sparse(diag(taper)); % preallocate the output structures for different units / trials ntrial = length(data.trial); spectrum = cell(nspikesel,ntrial); spiketime = cell(nspikesel,ntrial); spiketrial = cell(nspikesel,ntrial); % select the frequencies freqaxis = linspace(0, data.fsample, numsmp); fbeg = nearest(freqaxis, cfg.foilim(1)); fend = nearest(freqaxis, cfg.foilim(2)); % update the configuration to account for rounding off differences cfg.foilim(1) = freqaxis(fbeg); cfg.foilim(2) = freqaxis(fend); % make a representation of the spike, this is used for the phase rotation spike_repr = zeros(1,numsmp); time = linspace(cfg.timwin(1),cfg.timwin(2), numsmp); spike_repr(1-begpad) = 1; spike_fft = specest_nanfft(spike_repr, time); spike_fft = spike_fft(fbeg:fend); spike_fft = spike_fft./abs(spike_fft); rephase = sparse(diag(conj(spike_fft))); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute the spectra %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ft_progress('init', 'text', 'Please wait...'); for iUnit = 1:nspikesel for iTrial = 1:ntrial % select the spikes that fell in the trial and convert to samples timeBins = [data.time{iTrial} data.time{iTrial}(end)+1/data.fsample] - (0.5/data.fsample); hasTrial = spike.trial{spikesel(iUnit)} == iTrial; % find the spikes that are in the trial ts = spike.time{spikesel(iUnit)}(hasTrial); % get the spike times for these spikes ts = ts(ts>=timeBins(1) & ts<=timeBins(end)); % only select those spikes that fall in the trial window [ignore,spikesmp] = histc(ts,timeBins); if ~isempty(ts) ts(spikesmp==0 | spikesmp==length(timeBins)) = []; end spikesmp(spikesmp==0 | spikesmp==length(timeBins)) = []; % store in the output cell arrays as column vectors spiketime{iUnit, iTrial} = ts(:); tr = iTrial*ones(size(spikesmp)); spiketrial{iUnit, iTrial} = tr(:); % preallocate the spectrum spectrum{iUnit, iTrial} = zeros(length(spikesmp), nchansel, fend-fbeg+1); % compute the spiketriggered spectrum ft_progress(iTrial/ntrial, 'spectrally decomposing data for trial %d of %d, %d spikes for unit %d', iTrial, ntrial, length(spikesmp), iUnit); for j=1:length(spikesmp) % selected samples begsmp = spikesmp(j) + begpad; endsmp = spikesmp(j) + endpad; % handle spikes near the borders of the trials if (begsmp<1) segment = nan(nchansel, numsmp); elseif endsmp>size(data.trial{iTrial},2) segment = nan(nchansel, numsmp); else segment = data.trial{iTrial}(chansel,begsmp:endsmp); end % substract the DC component from every segment, to avoid any leakage of the taper segmentMean = repmat(nanmean(segment,2),1,numsmp); % nChan x Numsmp segment = segment - segmentMean; % LFP has average of zero now (no DC) % taper the data segment around the spike and compute the fft segment_fft = specest_nanfft(segment * taper, time); % select the desired output frquencies and normalize segment_fft = segment_fft(:,fbeg:fend) ./ sqrt(numsmp/2); % rotate the estimated phase at each frequency to correct for the segment t=0 not being at the first sample segment_fft = segment_fft * rephase; % store the result for this spike in this trial spectrum{iUnit, iTrial}(j,:,:) = segment_fft; end % for each spike in this trial end % for each trial end ft_progress('close'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % collect the results in a structure that is a spike structure %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% sts.lfplabel = data.label(chansel); sts.freq = freqaxis(fbeg:fend); sts.dimord = 'rpt_chan_freq'; for iUnit = 1:nspikesel sts.fourierspctrm{iUnit} = cat(1, spectrum{iUnit,:}); spectrum(iUnit,:) = {[]}; % free from the memory sts.time{iUnit} = cat(1,spiketime{iUnit,:}); sts.trial{iUnit} = cat(1,spiketrial{iUnit,:}); end sts.dimord = '{chan}_spike_lfpchan_freq'; sts.trialtime = spike.trialtime; sts.label = spike.label(spikesel); % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous data ft_postamble history sts %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [spikelabel, eeglabel] = detectspikechan(data) maxRate = 1000; % default on what we still consider a neuronal signal % autodetect the spike channels ntrial = length(data.trial); nchans = length(data.label); spikechan = zeros(nchans,1); for i=1:ntrial for j=1:nchans hasAllInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:) == round(data.trial{i}(j,:))); hasAllPosInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:)>=0); fr = nansum(data.trial{i}(j,:),2) ./ (data.time{i}(end)-data.time{i}(1)); spikechan(j) = spikechan(j) + double(hasAllInts & hasAllPosInts & fr<=maxRate); end end spikechan = (spikechan==ntrial); spikelabel = data.label(spikechan); eeglabel = data.label(~spikechan); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for demonstration purpose %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = fft_along_rows(x) y = fft(x, [], 2); % use normal Matlab function to compute the fft along 2nd dimension
github
lcnbeapp/beapp-master
ft_spike_plot_raster.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spike_plot_raster.m
19,802
utf_8
2861220e5c63dfa6d9a32157c62c8593
function [cfg] = ft_spike_plot_raster(cfg, spike, timelock) % FT_SPIKE_PLOT_RASTER makes a raster plot of spike-trains and allows for a % spike-density or a PSTH plot on top. % % Use as % ft_spike_plot_raster(cfg, spike) % or % ft_spike_plot_raster(cfg, spike, timelock) % % The input SPIKE data structure should be organized as the spike or the % raw datatype The optional input TIMELOCK should be organized as the % timelock datatype, e.g. the output from FT_SPIKE_PSTH or FT_SPIKEDENSITY, % having the average firing rate / spike count per time-point / time-bin. % However, timelock could also be the output from FT_TIMELOCKANALYSIS. % % Configuration options % cfg.spikechannel = see FT_CHANNELSELECTION for details % cfg.latency = [begin end] in seconds, 'maxperiod' (default), 'minperiod', % 'prestim' (all t<=0), or 'poststim' (all t>=0). % If a third input is present, we will use the % timelock.cfg.latency field to ensure that the % raster and the timelock data have the same % latency. % cfg.linewidth = number indicating the width of the lines (default = 1); % cfg.cmapneurons = 'auto' (default), or nUnits-by-3 matrix. % Controls coloring of spikes and psth/density % data if multiple cells are present. % cfg.spikelength = number >0 and <=1 indicating the length of the spike. If % cfg.spikelength = 1, then no space will be left between % subsequent rows representing trials (row-unit is 1). % cfg.trialborders = 'yes' or 'no'. If 'yes', borders of trials are % plotted % cfg.plotselection = 'yes' or 'no' (default). If yes plot Y axis only for selection in cfg.trials % cfg.topplotsize = number ranging from 0 to 1, indicating the proportion of the % rasterplot that the top plot will take (e.g., with 0.7 the top % plot will be 70% of the rasterplot in size). Default = 0.5. % cfg.topplotfunc = 'bar' (default) or 'line'. % cfg.errorbars = 'no', 'std', 'sem' (default), 'conf95%','var' % % cfg.interactive = 'yes' (default) or 'no'. If 'yes', zooming and panning operate via callbacks. % cfg.trials = numeric or logical selection of trials (default = 'all'). % Copyright (C) 2010-2013, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % check if input spike structure is indeed a spike structure spike = ft_checkdata(spike,'datatype', 'spike', 'feedback', 'yes'); % converts raw as well % get the default options cfg.spikechannel = ft_getopt(cfg,'spikechannel', 'all'); cfg.trials = ft_getopt(cfg,'trials', 'all'); cfg.latency = ft_getopt(cfg,'latency','maxperiod'); cfg.linewidth = ft_getopt(cfg,'linewidth', 1); cfg.cmapneurons = ft_getopt(cfg,'cmapneurons', 'auto'); cfg.spikelength = ft_getopt(cfg,'spikelength', 0.9); cfg.topplotsize = ft_getopt(cfg,'topplotsize', 0.5); cfg.topplotfunc = ft_getopt(cfg,'topplotfunc', 'bar'); cfg.errorbars = ft_getopt(cfg,'errorbars', 'sem'); cfg.trialborders = ft_getopt(cfg,'trialborders','yes'); cfg.plotselection = ft_getopt(cfg,'plotselection','no'); cfg.interactive = ft_getopt(cfg,'interactive','yes'); % ensure that the options are valid cfg = ft_checkopt(cfg,'spikechannel',{'cell', 'char', 'double'}); cfg = ft_checkopt(cfg,'latency', {'char', 'ascendingdoublebivector'}); cfg = ft_checkopt(cfg,'trials', {'char', 'doublevector', 'logical'}); cfg = ft_checkopt(cfg,'linewidth', 'doublescalar'); cfg = ft_checkopt(cfg,'cmapneurons', {'char', 'doublematrix', 'doublevector'}); cfg = ft_checkopt(cfg,'spikelength', 'doublescalar'); cfg = ft_checkopt(cfg,'topplotsize', 'doublescalar'); cfg = ft_checkopt(cfg,'topplotfunc', 'char', {'bar', 'line'}); cfg = ft_checkopt(cfg,'errorbars', 'char', {'sem', 'std', 'conf95%', 'no', 'var'}); cfg = ft_checkopt(cfg,'trialborders', 'char', {'yes', 'no'}); cfg = ft_checkopt(cfg,'plotselection', 'char', {'yes', 'no'}); cfg = ft_checkopt(cfg,'interactive', 'char', {'yes', 'no'}); cfg = ft_checkconfig(cfg, 'allowed', {'spikechannel', 'latency', 'trials', 'linewidth', 'cmapneurons', 'spikelength', 'topplotsize', 'topplotfunc', 'errorbars', 'trialborders', 'plotselection', 'interactive'}); % check if a third input is present, and check if it's a timelock structure if nargin==3 doTopData = true; timelock = ft_checkdata(timelock,'datatype', 'timelock', 'feedback', 'yes'); if isfield(timelock,'cfg') && isfield(timelock.cfg, 'latency') cfg.latency = timelock.cfg.latency; end else doTopData = false; end % get the spikechannels cfg.spikechannel = ft_channelselection(cfg.spikechannel, spike.label); spikesel = match_str(spike.label, cfg.spikechannel); nUnits = length(spikesel); % number of spike channels if nUnits==0, error('No spikechannel selected by means of cfg.spikechannel'); end % get the number of trials and set the cfg.trials field nTrialsOrig = size(spike.trialtime,1); nTrialsShown = nTrialsOrig; if strcmp(cfg.trials,'all') cfg.trials = 1:nTrialsOrig; elseif islogical(cfg.trials) cfg.trials = find(cfg.trials); end cfg.trials = sort(cfg.trials(:)); if max(cfg.trials)>nTrialsOrig, error('maximum trial number in cfg.trials should not exceed length of spike.trial') end if isempty(cfg.trials), errors('No trials were selected in cfg.trials'); end % determine the duration of each trial begTrialLatency = spike.trialtime(cfg.trials,1); endTrialLatency = spike.trialtime(cfg.trials,2); % select the latencies if strcmp(cfg.latency,'minperiod') cfg.latency = [max(begTrialLatency) min(endTrialLatency)]; elseif strcmp(cfg.latency,'maxperiod') cfg.latency = [min(begTrialLatency) max(endTrialLatency)]; elseif strcmp(cfg.latency,'prestim') cfg.latency = [min(begTrialLatency) 0]; elseif strcmp(cfg.latency,'poststim') cfg.latency = [0 max(endTrialLatency)]; end % check whether the time window fits with the data if (cfg.latency(1) < min(begTrialLatency)), cfg.latency(1) = min(begTrialLatency); warning('Correcting begin latency of averaging window'); end if (cfg.latency(2) > max(endTrialLatency)), cfg.latency(2) = max(endTrialLatency); warning('Correcting begin latency of averaging window'); end % delete trials that are not in our window overlaps = endTrialLatency>=cfg.latency(1) & begTrialLatency<=cfg.latency(2); trialSel = overlaps(:); cfg.trials = cfg.trials(trialSel); %update the trial selection if isempty(cfg.trials),warning('No trials were selected');end % create the data that should be plotted [unitX,unitY] = deal(cell(1,nUnits)); % find the spiketimes per neuron and make one vector of them with y value per element for iUnit = 1:nUnits unitIndx = spikesel(iUnit); latencySel = spike.time{unitIndx}>=cfg.latency(1) & spike.time{unitIndx} <= cfg.latency(2); isInTrials = ismember(spike.trial{unitIndx},cfg.trials); unitX{iUnit} = spike.time{unitIndx}(isInTrials(:) & latencySel(:)); unitY{iUnit} = spike.trial{unitIndx}(isInTrials(:) & latencySel(:)); if strcmp(cfg.plotselection,'yes') tempY{iUnit} = zeros(size(unitY{iUnit})); u = unique(unitY{iUnit}); for i = 1:length(u) idx = find(unitY{iUnit} == u(i)); tempY{iUnit}(idx) = i; end nTrialsShown = length(u); unitY{iUnit} = tempY{iUnit}; end end % some error checks on spike length if (cfg.spikelength<=0 || cfg.spikelength>1), error('cfg.spikelength should be a single number >0 and <=1. 1 row (1 trial) = 1'); end % some error checks on the size of the top figure if (cfg.topplotsize<=0 || cfg.topplotsize>1), error('cfg.topplotsize should be a single number >0 and <=1. 0.7 = 70%'); end % plot the trial borders if desired if strcmp(cfg.trialborders,'yes') begTrialLatency = begTrialLatency(overlaps(:)); endTrialLatency = endTrialLatency(overlaps(:)); % make yellow fills after trial end X = endTrialLatency; Y = cfg.trials; Y = [Y(:);Y(end);Y(1);(Y(1))]; X = [X(:);cfg.latency(2);cfg.latency(2);endTrialLatency(1)]; f = fill(X,Y,'y'); set(f,'EdgeColor', [1 1 1]); % make yellow fills before trial beginning X = begTrialLatency; Y = cfg.trials; Y = [Y(:);Y(end);Y(1);(Y(1))]; X = [X(:);cfg.latency(1);cfg.latency(1);begTrialLatency(1)]; hold on, fill(X,Y,'y'), hold on set(f,'EdgeColor', [1 1 1]); end % start plotting the rasterplot for iUnit = 1:nUnits % create the x and y value to be plotted x = [unitX{iUnit}(:)'; unitX{iUnit}(:)']; % create x duplicates, spike times y = unitY{iUnit}(:); % these are the trial values y = [y' - cfg.spikelength/2; y' + cfg.spikelength/2]; % process the color information for the different units if strcmp(cfg.cmapneurons, 'auto'), cfg.cmapneurons = colormap_cgbprb(nUnits); end if all(size(cfg.cmapneurons) ./ [nUnits 3]) color = cfg.cmapneurons(iUnit,:); else error('cfg.cmapneurons should be nUnits-by-3 matrix or "auto"'); end % create axes for the rasterplot, all go to the same position, so do this for unit 1 if iUnit==1 ax(1) = newplot; posOrig = get(ax(1), 'Position'); % original position for a standard plot pos = posOrig; if doTopData % if topdata, we leave space on top posRaster = [pos(1:3) pos(4)*(1-cfg.topplotsize)]; % and decrease the size of width and height else posRaster = pos; end set(ax(1), 'ActivePositionProperty', 'position', 'Position', posRaster) end % make the raster plot and hold on for the next plots rasterHdl = line(x, y,'LineWidth', cfg.linewidth,'Color', color); cfg.hdl.raster = rasterHdl; set(ax(1),'NextPlot', 'add') set(ax(1),'Box', 'off') end % create the labels for the first axes xlabel('time (sec)') ylabel('Trial Number') axis ij % plot the top data if doTopData % match on the basis of labels, and specify this in the documentary unitIndx = find(ismember(timelock.label,spike.label(spikesel))); if sum(unitIndx)<nUnits, error('timelock.label should contain all label of selected units'); end % select timepoints and get the data to be plotted binSel = timelock.time>=cfg.latency(1) & timelock.time<=cfg.latency(2); dataY = timelock.avg(unitIndx,binSel); dataX = timelock.time(binSel); % create the position for the topplot and axes with this position posTopPlot = [0 pos(4)*(1-cfg.topplotsize) 0 0] + pos.*[1 1 1 cfg.topplotsize]; ax(2) = axes('Units', get(ax(1), 'Units'), 'Position', posTopPlot,... 'Parent', get(ax(1), 'Parent')); % make the bar or the line plot if strcmp(cfg.topplotfunc,'bar') % plot thje density / psth as a bar plot avgHdl = feval(cfg.topplotfunc,dataX,dataY', 'stack'); % color the different bars for iUnit = 1:nUnits set(avgHdl(iUnit),'FaceColor',cfg.cmapneurons(iUnit,:),'EdgeColor', cfg.cmapneurons(iUnit,:),'LineWidth', 3); end % set the bar width to 1 set(avgHdl,'BarWidth', 1); if ~strcmp(cfg.errorbars, 'no') && nUnits>1 warning('error bars can only be plotted with bar plot if one unit is plotted'); end % add standard error bars to it if ~strcmp(cfg.errorbars, 'no') && nUnits==1 x = [timelock.time(binSel);timelock.time(binSel)]; % create x doublets if strcmp(cfg.errorbars, 'sem') err = sqrt(timelock.var(unitIndx,binSel)./timelock.dof(unitIndx,binSel)); elseif strcmp(cfg.errorbars, 'std') err = sqrt(timelock.var(unitIndx,binSel)); elseif strcmp(cfg.errorbars, 'var') err = timelock.var(unitIndx,binSel); elseif strcmp(cfg.errorbars, 'conf95%') % use a try statement just in case the statistics toolbox doesn't work. try tCrit = tinv(0.975,timelock.dof(unitIndx,binSel)); err = tCrit.*sqrt(timelock.var(unitIndx,binSel)./timelock.dof(unitIndx,binSel)); % assuming normal distribution, SHOULD BE REPLACED BY STUDENTS-T! catch % this is in case statistics toolbox is lacking err = 0; warning('error with computing 95% conf limits, probably issue with statistics toolbox'); end end y = dataY + err; % plot the errorbars as line plot on top of the bar plot hold on y = [zeros(1,length(y));y]; % let lines run from 0 to error values hd = plot(x,y,'k'); % plot the error bars end else % plot the density / psth avgHdl = feval(cfg.topplotfunc,dataX,dataY'); % set the color for every unit for iUnit = 1:nUnits set(avgHdl(iUnit),'Color',cfg.cmapneurons(iUnit,:)); end % ensure that the data limits are increasing mnmax = [nanmin(dataY(:))-eps nanmax(dataY(:))+eps]; % plot the errorbars if ~strcmp(cfg.errorbars,'no') % check if the right error information is there if ~isfield(timelock,'var') || ~isfield(timelock,'dof'), error('timelock should contain field .var and .dof for errorbars'); end % select the degrees of freedom df = timelock.dof(unitIndx,binSel); % plot the different error bars if strcmp(cfg.errorbars, 'sem') err = sqrt(timelock.var(unitIndx,binSel)./df); elseif strcmp(cfg.errorbars, 'std') err = sqrt(timelock.var(unitIndx,binSel)); elseif strcmp(cfg.errorbars, 'var') err = timelock.var(unitIndx,binSel); elseif strcmp(cfg.errorbars, 'conf95%') tCrit = tinv(0.975,df); err = tCrit.*sqrt(timelock.var(unitIndx,binSel)./df); end % ensure division by zero does not count, should not happen however err(~isfinite(err)) = NaN; % make a polygon of the error bars that allows easy filling in adobe for iUnit = 1:nUnits upb = dataY(iUnit,:) + err(iUnit,:); lowb = dataY(iUnit,:) - err(iUnit,:); sl = ~isnan(upb); [X,Y] = polygon(dataX(sl),upb(sl)+0.0001,lowb(sl)-0.0001); hold on hd = plot(X,Y,'--'); set(hd,'Color', cfg.cmapneurons(iUnit,:)); hold on end mnmax = [nanmin(dataY(:) - err(:)) nanmax(dataY(:) + err(:))]; end % set the y limits explicitly ylim = mnmax; d = ylim(2)-ylim(1); yl = ylim(1)-0.05*d; if ylim(1)>0 if yl<0, yl = 0; end end ylim(1) = yl; yl = ylim(2)+0.05*d; if ylim(2)<0 if yl>0, yl = 0; end end ylim(2) = yl; if ylim(2) == ylim(1) %if the plot is empty ylim(2)=ylim(1)+1; %be nice to set end set(gca,'YLim', ylim) end % store the handle cfg.hdl.psth = avgHdl; % modify the axes set(ax(2),'YAxisLocation', 'right') % swap y axis location set(ax(2),'XTickLabel', {}) % remove ticks and labels for x axis set(ax(2),'XTick', []) set(ax(2), 'Box', 'off') % turn the box off % change the axis settings try ylabel(timelock.cfg.outputunit) catch warning('unit of the y-axis is unknown'); ylabel('Signal intensity') end end % set the limits for the axis set(ax,'XLim', [cfg.latency]) if nTrialsShown==0; nTrialsShown = 1; end % set(ax(1), 'YLim', [0.5 nTrialsShown+0.5]); % number of trials set(ax,'TickDir','out') % put the tickmarks outside % now link the axes, constrain zooming and keep ticks intact limX = [cfg.latency]; limY = get(ax,'YLim'); if ~iscell(limY), limY = {limY}; end % constrain the zooming and zoom psth together with the jpsth, remove % ticklabels jpsth if strcmp(cfg.interactive,'yes') set(zoom,'ActionPostCallback',{@mypostcallback,ax,limX,limY}); set(pan,'ActionPostCallback',{@mypostcallback,ax,limX,limY}); end % pass positions and axis handles so downstream % functions can respect the positions set here. cfg.pos.posRaster = posRaster; cfg.hdl.axRaster = ax(1); if doTopData cfg.pos.posTopPlot = posTopPlot; cfg.hdl.axTopPlot = ax(2); end % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous spike %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = mypostcallback(fig,evd,ax,lim,ylim) currentAxes = evd.Axes; indx = find(currentAxes==ax); % keep the y axis within boundaries origLim = ylim{indx}; ylim = get(ax(indx), 'YLim'); if origLim(1)>ylim(1), ylim(1) = origLim(1); end if origLim(2)<ylim(2), ylim(2) = origLim(2); end set(ax(indx), 'YLim', ylim) % keep the x axis within boundaries and reset for both xlim = get(ax(indx), 'XLim'); if lim(1)>xlim(1), xlim(1) = lim(1); end if lim(2)<xlim(2), xlim(2) = lim(2); end set(ax,'XLim', xlim) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [colorspace] = colormap_cgbprb(N) % COLORMAP_SEPARATION returns a color map with well separated colors that does not include % white, yellow or orange since these are not well visible in white plots. % % Inputs: N is the number of colors desired % Outputs: COLORSPACE is an N-by-3 colorspace. % Chosen colors are green, cyan, blue, purple, red and black % Script was adapted from varycolors.m from FEX % Copyright (c) 2009, Martin Vinck if nargin<1 error('specify the number of colors that you want') end % create a well visible color space % green cyan blue purple red black colors = [[0 1 0]; [0 1 1] ; [0 0 1] ; [1 0 1]; [1 0 0]; [0 0 0]]; order = [1 5 3 2 4 6]; % our preference order when plotting different lines rm{2} = [2:5]; rm{3} = [2 4 5]; rm{4} = [2 4]; rm{5} = [4]; if N==1 colorspace = colors(end,:); elseif N>1&&N<6 colors(rm{N},:) = []; colorspace = colors; else n = floor(N/5)*ones(1,5); rest = mod(N,5); order = [1 5 3 2 4]; % if we have some rest, add them starting oppositly n(order(1:rest)) = n(order(1:rest)) + 1; colorspace = []; for iColor = 1:5 corStart = colors(iColor,:); corEnd = colors(iColor+1,:); dim = corStart~=corEnd; subColors = corStart(ones(n(iColor)+1,1),:); if iColor>1 subColors(:,dim) = linspace(corStart(dim),corEnd(dim),n(iColor)+1); subColors(1,:) = []; else subColors(1:end-1,dim) = linspace(corStart(dim),corEnd(dim),n(iColor)); subColors(end,:) = []; end colorspace = [colorspace;subColors]; end end function [X,Y] = polygon(x,sm1,sm2,multiplier) x = x(:)'; if nargin < 4 multiplier = 1; end X = [x x(end:-1:1) x(1)]; up = sm1(:)'; down = sm2(:)'; Y = [down up(end:-1:1) down(1)];
github
lcnbeapp/beapp-master
ft_spiketriggeredspectrum_convol.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spiketriggeredspectrum_convol.m
22,946
utf_8
d98d6fda0d5ecfa7112481f075927c44
function [sts] = ft_spiketriggeredspectrum_convol(cfg, data, spike) % FT_SPIKETRIGGEREDSPECTRUM_CONVOL computes the Fourier spectrum (amplitude and % phase) of the LFP around the spikes using convolution of the complete LFP traces. A % phase of zero corresponds to the spike being on the peak of the LFP oscillation. A % phase of 180 degree corresponds to the spike being in the through of the oscillation. % A phase of 45 degrees corresponds to the spike being just after the peak in the LFP. % % The difference to FT_SPIKETRIGGEREDSPECTRUM_FFT is that this function allows for % multiple frequencies to be processed with different time-windows per frequency, and % that FT_SPIKETRIGGEREDSPECTRUM_FFT is based on taking the FFT of a limited LFP % segment around each spike. % % Use as % [sts] = ft_spiketriggeredspectrum_convol(cfg,data,spike) % or % [sts] = ft_spiketriggeredspectrum_convol(cfg,data) % The spike data can either be contained in the data input or in the spike % input. % % The input DATA should be organised as the raw datatype, obtained from % FT_PREPROCESSING or FT_APPENDSPIKE. % % The input SPIKE should be organised as the spike or the raw datatype, obtained from % FT_SPIKE_MAKETRIALS or FT_PREPROCESSING, in which case the conversion is done % within this function. % % Important is that data.time and spike.trialtime should be referenced % relative to the same trial trigger times! % % Configurations (following largely FT_FREQNALYSIS with method mtmconvol) % cfg.tapsmofrq = vector 1 x numfoi, the amount of spectral smoothing through % multi-tapering. Note that 4 Hz smoothing means % plus-minus 4 Hz, i.e. a 8 Hz smoothing box. % cfg.foi = vector 1 x numfoi, frequencies of interest % cfg.taper = 'dpss', 'hanning' or many others, see WINDOW (default = 'dpss') % cfg.t_ftimwin = vector 1 x numfoi, length of time window (in % seconds) % cfg.taperopt = parameter that goes in WINDOW function (only % applies to windows like KAISER). % cfg.spikechannel = cell-array with selection of channels (default = 'all') % see FT_CHANNELSELECTION for details % cfg.channel = Nx1 cell-array with selection of channels (default = 'all'), % see FT_CHANNELSELECTION for details % cfg.borderspikes = 'yes' (default) or 'no'. If 'yes', we process the spikes % falling at the border using an LFP that is not centered % on the spike. If 'no', we output NaNs for spikes % around which we could not center an LFP segment. % cfg.rejectsaturation= 'yes' (default) or 'no'. If 'yes', we set % EEG segments where the maximum or minimum % voltage range is reached % with zero derivative (i.e., saturated signal) to % NaN, effectively setting all spikes phases that % use these parts of the EEG to NaN. An EEG that % saturates always returns the same phase at all % frequencies and should be ignored. % % Note: some adjustment of the frequencies can occur as the chosen time-window may not % be appropriate for the chosen frequency. % For example, suppose that cfg.foi = 80, data.fsample = 1000, and % cfg.t_ftimwin = 0.0625. The DFT frequencies in that case are % linspace(0,1000,63) such that cfg.foi --> 80.645. In practice, this error % can only become large if the number of cycles per frequency is very % small and the frequency is high. For example, suppose that cfg.foi = 80 % and cfg.t_ftimwin = 0.0125. In that case cfg.foi-->83.33. % The error is smaller as data.fsample is larger. % % Outputs: % sts is a spike structure, containing new fields: % sts.fourierspctrm = 1 x nUnits cell array with dimord spike_lfplabel_freq % sts.lfplabel = 1 x nChan cell array with EEG labels % sts.freq = 1 x nFreq frequencies. Note that per default, not % all frequencies can be used as we compute the DFT % around the spike based on an uneven number of % samples. This introduces a slight adjustment of the % selected frequencies. % % Note: sts.fourierspctrm can contain NaNs, for example if % cfg.borderspikes = 'no', or if cfg.rejectsaturation = 'yes', or if the % trial length was too short for the window desired. % % WHen using multitapering, the phase distortion is corrected for. % % The output STS data structure can be input to FT_SPIKETRIGGEREDSPECTRUM_STAT % Copyright (C) 2008-2012, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % check if the input data is valid for this function data = ft_checkdata(data, 'datatype', {'raw'}, 'feedback', 'yes'); if nargin==3 spike = ft_checkdata(spike, 'datatype', {'spike'}, 'feedback', 'yes'); end % ensure that the required options are present cfg = ft_checkconfig(cfg, 'required', {'foi','t_ftimwin'}); % get the options cfg.borderspikes = ft_getopt(cfg, 'borderspikes','yes'); cfg.taper = ft_getopt(cfg, 'taper','hanning'); cfg.taperopt = ft_getopt(cfg, 'taperopt',[]); cfg.spikechannel = ft_getopt(cfg,'spikechannel', 'all'); cfg.channel = ft_getopt(cfg,'channel', 'all'); cfg.rejectsaturation = ft_getopt(cfg,'rejectsaturation', 'yes'); % ensure that the options are valid cfg = ft_checkopt(cfg, 'taper',{'char', 'function_handle'}); cfg = ft_checkopt(cfg, 'borderspikes','char',{'yes', 'no'}); cfg = ft_checkopt(cfg, 't_ftimwin',{'doublevector', 'doublescalar'}); cfg = ft_checkopt(cfg, 'foi',{'doublevector', 'doublescalar'}); cfg = ft_checkopt(cfg, 'spikechannel',{'cell', 'char', 'double'}); cfg = ft_checkopt(cfg, 'channel', {'cell', 'char', 'double'}); cfg = ft_checkopt(cfg, 'taperopt', {'double','empty'}); cfg = ft_checkopt(cfg, 'rejectsaturation','char', {'yes', 'no'}); if isequal(cfg.taper, 'dpss') cfg = ft_checkconfig(cfg, 'required', {'tapsmofrq'}); cfg = ft_checkopt(cfg,'tapsmofrq',{'doublevector', 'doublescalar'}); end cfg = ft_checkconfig(cfg, 'allowed', {'taper', 'borderspikes', 't_ftimwin', 'foi', 'spikechannel', 'channel', 'taperopt', 'rejectsaturation','tapsmofrq'}); % length of tapsmofrq, foi and t_ftimwin should all be matched if isfield(cfg,'tapsmofrq') if length(cfg.tapsmofrq) ~= length(cfg.foi) || length(cfg.foi)~=length(cfg.t_ftimwin) error('lengths of cfg.tapsmofrq, cfg.foi and cfg_t_ftimwin should be equal and 1 x nFreqs') end end % get the spikechannels if nargin==2 % autodetect the spikechannels and EEG channels [spikechannel, eegchannel] = detectspikechan(data); if strcmp(cfg.spikechannel, 'all'), cfg.spikechannel = spikechannel; else cfg.spikechannel = ft_channelselection(cfg.spikechannel, data.label); if ~all(ismember(cfg.spikechannel,spikechannel)), error('some selected spike channels appear eeg channels'); end end if strcmp(cfg.channel,'all') cfg.channel = eegchannel; else cfg.channel = ft_channelselection(cfg.channel, data.label); if ~all(ismember(cfg.channel,eegchannel)), warning('some of the selected eeg channels appear spike channels'); end end data_spk = ft_selectdata(data,'channel', cfg.spikechannel); data = ft_selectdata(data,'channel', cfg.channel); % leave only LFP spike = ft_checkdata(data_spk,'datatype', 'spike'); clear data_spk % remove the continuous data else cfg.spikechannel = ft_channelselection(cfg.spikechannel, spike.label); cfg.channel = ft_channelselection(cfg.channel, data.label); end % determine the channel indices and number of chans chansel = match_str(data.label, cfg.channel); % selected channels nchansel = length(cfg.channel); % number of channels spikesel = match_str(spike.label, cfg.spikechannel); nspikesel = length(spikesel); % number of spike channels if nspikesel==0, error('no units were selected'); end if nchansel==0, error('no channels were selected'); end % preallocate nTrials = length(data.trial); % number of trials [spectrum,spiketime, spiketrial] = deal(cell(nspikesel,nTrials)); % preallocate the outputs [unitsmp,unittime,unitshift] = deal(cell(1,nspikesel)); nSpikes = zeros(1,nspikesel); % construct the frequency axis and restrict to unique frequencies if ~isfield(data, 'fsample'), data.fsample = 1/mean(diff(data.time{1})); end if any(cfg.foi > (data.fsample/2)) error('frequencies in cfg.foi are above Nyquist frequency') end numsmp = round(cfg.t_ftimwin .* data.fsample); numsmp(~mod(numsmp,2)) = numsmp(~mod(numsmp,2))+1; % make sure we always have uneven samples, since we want the spike in the middle foi = zeros(1,length(cfg.foi)); for iSmp = 1:length(numsmp) faxis = linspace(0,data.fsample,numsmp(iSmp)); findx = nearest(faxis,cfg.foi(iSmp)); [foi(iSmp)] = deal(faxis(findx)); % this is the actual frequency used, from the DFT formula end % [cfg.foi,B,C] = unique(foi); % take the unique frequencies from this cfg.t_ftimwin = cfg.t_ftimwin(B); % compute the minima and maxima of the data, this is done to remove EEG portions where there are potential saturation effects if strcmp(cfg.rejectsaturation,'yes') [minChan,maxChan] = deal([]); for iChan = 1:nchansel mx = -inf; mn = +inf; for iTrial = 1:nTrials minTrial = nanmin(data.trial{iTrial}(iChan,:)); maxTrial = nanmax(data.trial{iTrial}(iChan,:)); if maxTrial>mx, mx = maxTrial; end if minTrial<mn, mn = minTrial; end end minChan(iChan) = mn; maxChan(iChan) = mx; end end % compute the spectra ft_progress('init', 'text', 'Please wait...'); for iTrial = 1:nTrials % select the spike times for a given trial and restrict to those overlapping with the EEG x = data.time{iTrial}; timeBins = [x x(end)+1/data.fsample] - (0.5/data.fsample); for iUnit = 1:nspikesel unitindx = spikesel(iUnit); hasTrial = spike.trial{unitindx} == iTrial; % find the spikes that are in the trial ts = spike.time{unitindx}(hasTrial); % get the spike times for these spikes vld = ts>=timeBins(1) & ts<=timeBins(end); % only select those spikes that fall in the trial window ts = ts(vld); % timestamps for these spikes [ignore,I] = histc(ts,timeBins); if ~isempty(ts) ts(I==0 | I==length(timeBins)) = []; end I(I==0 | I==length(timeBins)) = []; unitsmp{iUnit} = I; unittime{iUnit} = ts(:); % this is for storage in the output structure smptime = data.time{iTrial}(unitsmp{iUnit}); % times corresponding to samples unitshift{iUnit} = ts(:) - smptime(:); % shift induced by shifting to sample times, important for high-frequency oscillations nSpikes(iUnit) = length(unitsmp{iUnit}); end if ~any(nSpikes),continue,end % continue to the next trial if this one does not contain valid spikes % set the saturated parts of the data to NaNs if strcmp(cfg.rejectsaturation,'yes') for iChan = 1:nchansel isSaturated = find(diff(data.trial{iTrial}(chansel(iChan),:))==0)+1; remove = data.trial{iTrial}(chansel(iChan),isSaturated)==maxChan(iChan) | data.trial{iTrial}(chansel(iChan),isSaturated)==minChan(iChan); remove = isSaturated(remove); data.trial{iTrial}(chansel(iChan),remove) = NaN; if ~isempty(remove) fprintf('setting %d points from channel %s in trial %d to NaN\n', length(remove), cfg.channel{iChan}, iTrial); end end end % preallocate nFreqs = length(cfg.foi); for iUnit = 1:nspikesel if nSpikes(iUnit)>0, spectrum{iUnit,iTrial} = zeros(nSpikes(iUnit),nchansel,nFreqs); end end % process the phases for every chan-freq combination separately to save memory for iFreq = 1:nFreqs % construct the input options for the sub-function phase_est tmpcfg = cfg; tmpcfg.foi = cfg.foi(iFreq); try tmpcfg.tapsmofrq = cfg.tapsmofrq(iFreq);end tmpcfg.t_ftimwin = cfg.t_ftimwin(iFreq); if tmpcfg.t_ftimwin>=(data.time{iTrial}(end)-data.time{iTrial}(1)) warning('time window for frequency %.2f Hz too large for trial %d', tmpcfg.foi, iTrial); spectrum{iUnit,iTrial}(:,:,iFreq) = NaN; continue; end % just some message if nTrials==1 ft_progress(iFreq/nFreqs, 'Processing frequency %d from %d', iFreq, nFreqs); else ft_progress(iTrial/nTrials, 'Processing trial %d from %d', iTrial, nTrials); end % compute the LFP phase at every time-point spec = zeros(length(data.time{iTrial}),nchansel); for iChan = 1:nchansel [spec(:,iChan),foi, numsmp] = phase_est(tmpcfg,data.trial{iTrial}(chansel(iChan),:),data.time{iTrial}, data.fsample); end % select now the proper phases for every unit for iUnit = 1:nspikesel if nSpikes(iUnit)==0, continue,end % gather the phases at the samples where we had the spikes spectrum{iUnit,iTrial}(:,:,iFreq) = spec(unitsmp{iUnit},:); % preallocate rephasing vector rephase = ones(nSpikes(iUnit),1); % do the rephasing and use proper phases for spikes at borders if strcmp(cfg.borderspikes,'yes') % use an LFP window not centered around the spike, to use spikes around the trial borders as well beg = 1+(numsmp-1)/2; % find the borders empirically ed = length(data.time{iTrial}) - beg + 1; vldSpikes = unitsmp{iUnit}>=beg & unitsmp{iUnit}<=ed; % determine the valid spikes earlySpikes = unitsmp{iUnit}<beg; lateSpikes = unitsmp{iUnit}>ed; if any(earlySpikes) rephase(earlySpikes) = exp(1i*2*pi*foi* (unittime{iUnit}(earlySpikes) - data.time{iTrial}(beg))' ); for iChan = 1:nchansel spectrum{iUnit,iTrial}(earlySpikes,iChan,iFreq) = spec(beg,iChan); end end if any(lateSpikes) rephase(lateSpikes) = exp(1i*2*pi*foi * (unittime{iUnit}(lateSpikes) - data.time{iTrial}(ed)) ); for iChan = 1:nchansel spectrum{iUnit,iTrial}(lateSpikes,iChan,iFreq) = spec(ed,iChan); end end if any(vldSpikes) rephase(vldSpikes) = exp(1i*2*pi*foi*unitshift{iUnit}(vldSpikes)); end else % in this case the spikes that fall around borders are set to NaN if ~isempty(unitshift{iUnit}) rephase(1:end) = exp(1i*2*pi*foi*unitshift{iUnit}); end end % Rephase the spectrum, this serves two purposes: % 1) correct for potential misallignment of spikes to LFP sampling axis % 2) for spikes falling at borders, we need to account for the fact that we % used the instantaneous phase at a different moment in time for iChan = 1:nchansel spectrum{iUnit,iTrial}(:,iChan,iFreq) = spectrum{iUnit,iTrial}(:,iChan,iFreq).*rephase; end % Store the spiketimes and spiketrials, constructing a type of SPIKE format spiketime{iUnit,iTrial} = unittime{iUnit}; spiketrial{iUnit,iTrial} = iTrial*ones(1,nSpikes(iUnit)); end end end ft_progress('close'); % collect the results sts.lfplabel = data.label(chansel); sts.freq = cfg.foi; sts.label = spike.label(spikesel); for iUnit = 1:nspikesel sts.fourierspctrm{iUnit} = cat(1, spectrum{iUnit,:}); spectrum(iUnit,:) = {[]}; % free from the memory sts.time{iUnit} = cat(1, spiketime{iUnit,:}); sts.trial{iUnit} = cat(2, spiketrial{iUnit,:})'; end sts.dimord = '{chan}_spike_lfpchan_freq'; sts.trialtime = spike.trialtime; % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous data spike ft_postamble history sts function [spctrm,foi, numsmp] = phase_est(cfg,dat,time,fsample) % Phase estimation function % Determine fsample and set total time-length of data if nargin<4 fsample = 1./mean(time(2:end)-time(1:end-1)); % round off errors! end numsmp = round(cfg.t_ftimwin .* fsample); numsmp(~mod(numsmp,2)) = numsmp(~mod(numsmp,2))+1; % make sure we always have uneven samples, since we want the spike in the middle faxis = linspace(0,fsample,numsmp); findx = nearest(faxis,cfg.foi); [cfg.foi,foi] = deal(faxis(findx)); % this is the actual frequency used, from the DFT formula timwinSamples = numsmp; % Compute tapers per frequency, multiply with wavelets and compute their fft switch cfg.taper case 'dpss' % create a sequence of DPSS tapers taper = double_dpss(timwinSamples, timwinSamples .* (cfg.tapsmofrq ./ fsample))'; taper = taper(1:(end-1), :); % removing the last taper % give error/warning about number of tapers if isempty(taper) error('%.3f Hz: datalength to short for specified smoothing\ndatalength: %.3f s, smoothing: %.3f Hz, minimum smoothing: %.3f Hz',... cfg.foi, timwinSamples/fsample,cfg.tapsmofrq,fsample/timwinSamples); elseif size(taper,1) == 1 warning('using only one taper for specified smoothing for %.2f Hz', cfg.foi) end case 'sine' taper = sine_taper(timwinSamples, timwinSamples .* (cfg.tapsmofrq ./ fsample))'; taper = taper(1:(end-1), :); otherwise % create a single taper according to the standard window specification if isempty(cfg.taperopt) taper = window(cfg.taper, timwinSamples)'; else try taper = window(cfg.taper, timwinSamples,cfg.taperopt)'; catch error('taper option was not appropriate for taper'); end end end % do some check on the taper size if size(taper,1)==numsmp, taper = taper'; end % normalize taper if there's 1 and all are positive if size(taper,1)==1 && all(taper>=0) taper = numsmp*taper./sum(taper); % magnitude of cosine is now returned end %%%% fit linear regression for every datapoint: to remove mean and ramp of signal sumKern = ones(1,timwinSamples); avgKern = sumKern./timwinSamples; xKern = timwinSamples:-1:1; % because of definition conv2 function meanX = mean(xKern); sumX = sum(xKern); % beta1 = (sum(x.*y) - sum(x)*sum(y)/n) ./ (sum((x-meanx).^2): standard linear regr formula beta1 = (conv2(dat(:),xKern(:),'same') - sumX.*conv2(dat(:),sumKern(:),'same')/timwinSamples ) ./ sum((xKern-meanX).^2); beta0 = conv2(dat(:),avgKern(:),'same') - beta1.*meanX; % beta0 = mean(dat) - beta1*mean(x) % DFT formula: basefunctions: cos(2*pi*k*[0:numsmp-1]/numsmp) and sin(2*pi*k*[0:numsmp-1]/numsmp) % center the base functions such that the peak of the cos function is at the center. See: % f = findx-1; ax = -(numsmp-1)/2:(numsmp-1)/2; y = cos(2*pi.*ax.*f/numsmp);figure, plot(ax,y,'sr'); % y2 = cos(2*pi.*linspace(-(numsmp-1)/2,(numsmp-1)/2,1000).*f/numsmp); % hold on, plot(linspace(-(numsmp-1)/2,(numsmp-1)/2,1000),y2,'r-') % correcting for phase rotation (as with multitapering) nTapers = size(taper,1); indN = -(numsmp-1)/2:(numsmp-1)/2; spctrmRot = complex(zeros(1,1)); for iTaper = 1:nTapers coswav = taper(iTaper,:).*cos(2*pi*(findx-1)*indN/numsmp); sinwav = taper(iTaper,:).*sin(2*pi*(findx-1)*indN/numsmp); wavelet = complex(coswav(:), sinwav(:)); cosSignal = cos(2*pi*(findx-1)*indN/numsmp); spctrmRot = spctrmRot + sum(wavelet.*cosSignal(:)); end phaseCor = angle(spctrmRot); %%%% compute the spectra nTapers = size(taper,1); indN = -(numsmp-1)/2:(numsmp-1)/2; spctrm = complex(zeros(length(dat),1)); for iTaper = 1:nTapers coswav = taper(iTaper,:).*cos(2*pi*(findx-1)*indN/numsmp); sinwav = taper(iTaper,:).*sin(2*pi*(findx-1)*indN/numsmp); wavelet = complex(coswav(:), sinwav(:)); fftRamp = sum(xKern.*coswav) + 1i*sum(xKern.*sinwav); % fft of ramp with dx/ds = 1 * taper fftDC = sum(ones(1,timwinSamples).*coswav) + 1i*sum(ones(1,timwinSamples).*sinwav);% fft of unit direct current * taper spctrm = spctrm + (conv_fftbased(dat(:),wavelet) - (beta0*fftDC + beta1.*fftRamp))/(numsmp/2); % fft % mean %linear ramp % make magnitude invariant to window length end spctrm = spctrm./nTapers; % normalize by number of tapers spctrm = spctrm.*exp(-1i*phaseCor); % set the part of the spectrum without a valid phase to NaNs n = (timwinSamples-1)/2; spctrm(1:n) = NaN; spctrm(end-n+1:end) = NaN; function [taper] = double_dpss(a, b, varargin) taper = dpss(double(a), double(b), varargin{:}); function [spikelabel, eeglabel] = detectspikechan(data) maxRate = 1000; % default on what we still consider a neuronal signal % autodetect the spike channels ntrial = length(data.trial); nchans = length(data.label); spikechan = zeros(nchans,1); for i=1:ntrial for j=1:nchans hasAllInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:) == round(data.trial{i}(j,:))); hasAllPosInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:)>=0); fr = nansum(data.trial{i}(j,:),2) ./ (data.time{i}(end)-data.time{i}(1)); spikechan(j) = spikechan(j) + double(hasAllInts & hasAllPosInts & fr<=maxRate); end end spikechan = (spikechan==ntrial); spikelabel = data.label(spikechan); eeglabel = data.label(~spikechan); % CONVOLUTION: FFT BASED IMPLEMENTATION function c = conv_fftbased(a, b) P = numel(a); Q = numel(b); L = P + Q - 1; K = 2^nextpow2(L); c = ifft(fft(a, K) .* fft(b, K)); c = c(1:L); toRm1 = [1:(Q-1)/2]; toRm2 = [(1 + length(c) - (Q-1)/2) : length(c)]; toRm = [toRm1(:); toRm2(:)]; c(toRm) = [];
github
lcnbeapp/beapp-master
ft_spikesorting.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spikesorting.m
6,746
utf_8
162576b720405723faae8c158c5b3b19
function [spike] = ft_spikesorting(cfg, spike) % FT_SPIKESORTING performs clustering of spike-waveforms and returns the % unit number to which each spike belongs. % % Use as % [spike] = ft_spikesorting(cfg, spike) % % The configuration can contain % cfg.channel cell-array with channel selection (default = 'all'), see FT_CHANNELSELECTION for details % cfg.method 'kmeans', 'ward' % cfg.feedback 'no', 'text', 'textbar', 'gui' (default = 'textbar') % cfg.kmeans substructure with additional low-level options for this method % cfg.ward substructure with additional low-level options for this method % cfg.ward.distance 'L1', 'L2', 'correlation', 'cosine' % % The input spike structure can be imported using READ_FCDC_SPIKE and should contain % spike.label = 1 x Nchans cell-array, with channel labels % spike.waveform = 1 x Nchans cell-array, each element contains a matrix (Nsamples x Nspikes), can be empty % spike.timestamp = 1 x Nchans cell-array, each element contains a vector (1 x Nspikes) % spike.unit = 1 x Nchans cell-array, each element contains a vector (1 x Nspikes) % % See also FT_READ_SPIKE, FT_SPIKEDOWNSAMPLE % Copyright (C) 2006-2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % these were supported in the past, but are not any more (for consistency with other spike functions) cfg = ft_checkconfig(cfg, 'forbidden', 'inputfile', ... 'outputfile'); % see http://bugzilla.fcdonders.nl/show_bug.cgi?id=1056 % set the defaults if ~isfield(cfg, 'feedback'), cfg.feedback = 'textbar'; end if ~isfield(cfg, 'method'), cfg.method = 'ward'; end if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end if isequal(cfg.method, 'ward') if ~isfield(cfg, 'ward'), cfg.ward = []; end if ~isfield(cfg.ward, 'distance'), cfg.ward.distance = 'L2'; end if ~isfield(cfg.ward, 'optie'), cfg.ward.optie = 'ward'; end if ~isfield(cfg.ward, 'aantal'), cfg.ward.aantal = 10; end if ~isfield(cfg.ward, 'absoluut'), cfg.ward.absoluut = 1; end end if isequal(cfg.method, 'kmeans') if ~isfield(cfg, 'kmeans'), cfg.kmeans = []; end if ~isfield(cfg.kmeans, 'aantal'), cfg.kmeans.aantal = 10; end end % select the channels cfg.channel = ft_channelselection(cfg.channel, spike.label); sel = match_str(spike.label, cfg.channel); spike.label = spike.label(sel); spike.waveform = spike.waveform(sel); spike.timestamp = spike.timestamp(sel); spike.unit = {}; % this will be assigned by the clustering nchan = length(spike.label); for chanlop=1:nchan label = spike.label{chanlop}; waveform = spike.waveform{chanlop}; timestamp = spike.timestamp{chanlop}; nspike = size(waveform,2); unit = zeros(1,nspike); fprintf('sorting %d spikes in channel %s\n', nspike, label); switch cfg.method case 'ward' dist = ward_distance(cfg, waveform); [grootte,ordening] = cluster_ward(dist,cfg.ward.optie,cfg.ward.absoluut,cfg.ward.aantal); for i=1:cfg.ward.aantal begsel = sum([1 grootte(1:(i-1))]); endsel = sum([0 grootte(1:(i ))]); unit(ordening(begsel:endsel)) = i; end case 'kmeans' unit = kmeans(waveform', cfg.kmeans.aantal)'; % 'sqEuclidean' - Squared Euclidean distance % 'cityblock' - Sum of absolute differences, a.k.a. L1 % 'cosine' - One minus the cosine of the included angle % between points (treated as vectors) % 'correlation' - One minus the sample correlation between % points (treated as sequences of values) otherwise error('unsupported clustering method'); end % remember the sorted units spike.unit{chanlop} = unit; end % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous spike ft_postamble history spike %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that computes the distance between all spike waveforms %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dist] = ward_distance(cfg, waveform) nspike = size(waveform,2); dist = zeros(nspike, nspike); ft_progress('init', cfg.feedback, 'computing distance'); switch lower(cfg.ward.distance) case 'l1' for i=1:nspike ft_progress((i-1)/nspike, 'computing distance for spike %d/%d', i, nspike); for j=2:nspike dist(i,j) = sum(abs(waveform(:,j)-waveform(:,i))); dist(j,i) = dist(i,j); end end case 'l2' for i=1:nspike ft_progress((i-1)/nspike, 'computing distance for spike %d/%d', i, nspike); for j=2:nspike dist(i,j) = sqrt(sum((waveform(:,j)-waveform(:,i)).^2)); dist(j,i) = dist(i,j); end end case 'correlation' for i=1:nspike ft_progress((i-1)/nspike, 'computing distance for spike %d/%d', i, nspike); for j=2:nspike dist(i,j) = corrcoef(waveform(:,j),waveform(:,i)); dist(j,i) = dist(i,j); end end case 'cosine' for i=1:nspike ft_progress((i-1)/nspike, 'computing distance for spike %d/%d', i, nspike); for j=2:nspike x = waveform(:,j); y = waveform(:,i); x = x./norm(x); y = y./norm(y); dist(i,j) = dot(x, y); dist(j,i) = dist(i,j); end end otherwise error('unsupported distance metric'); end ft_progress('close');
github
lcnbeapp/beapp-master
ft_spike_xcorr.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spike_xcorr.m
17,643
utf_8
1640c25cf61ea0bbfab739c9bf37ef6b
function [stat] = ft_spike_xcorr(cfg,spike) % FT_SPIKE_XCORR computes the cross-correlation histogram and shift predictor. % % Use as % [stat] = ft_spike_xcorr(cfg,data) % % The input SPIKE should be organised as the spike or the raw datatype, obtained from % FT_SPIKE_MAKETRIALS or FT_PREPROCESSING (in that case, conversion is done % within the function). A mex file is located in /contrib/spike/private % which will be automatically mexed. % % Configurations options for xcorr general: % cfg.maxlag = number in seconds, indicating the maximum lag for the % cross-correlation function in sec (default = 0.1 sec). % cfg.debias = 'yes' (default) or 'no'. If 'yes', we scale the % cross-correlogram by M/(M-abs(lags)), where M = 2*N -1 with N % the length of the data segment. % cfg.method = 'xcorr' or 'shiftpredictor'. If 'shiftpredictor' % we do not compute the normal cross-correlation % but shuffle the subsequent trials. % If two channels are independent, then the shift % predictor should give the same correlogram as the raw % correlogram calculated from the same trials. % Typically, the shift predictor is subtracted from the % correlogram. % cfg.outputunit = - 'proportion' (value in each bin indicates proportion of occurence) % - 'center' (values are scaled to center value which is set to 1) % - 'raw' (default) unnormalized crosscorrelogram. % cfg.binsize = [binsize] in sec (default = 0.001 sec). % cfg.channelcmb = Mx2 cell-array with selection of channel pairs (default = {'all' 'all'}), % see FT_CHANNELCOMBINATION for details % cfg.latency = [begin end] in seconds, 'max' (default), 'min', 'prestim'(t<=0), or % 'poststim' (t>=0).% % cfg.vartriallen = 'yes' (default) or 'no'. % If 'yes' - accept variable trial lengths and use all available trials % and the samples in every trial. % If 'no' - only select those trials that fully cover the window as % specified by cfg.latency and discard those trials that do not. % if cfg.method = 'yes', then cfg.vartriallen % should be 'no' (otherwise, fewer coincidences % will occur because of non-overlapping windows) % cfg.trials = numeric selection of trials (default = 'all') % cfg.keeptrials = 'yes' or 'no' (default) % % A peak at a negative lag for stat.xcorr(chan1,chan2,:) means that chan1 is % leading chan2. Thus, a negative lag represents a spike in the second % dimension of stat.xcorr before the channel in the third dimension of % stat.stat. % % Variable trial length is controlled by the option cfg.vartriallen. If % cfg.vartriallen = 'yes', all trials are selected that have a minimum % overlap with the latency window of cfg.maxlag. However, the shift % predictor calculation demands that following trials have the same amount % of data, otherwise, it does not control for rate non-stationarities. If % cfg.vartriallen = 'yes', all trials should fall in the latency window, % otherwise we do not compute the shift predictor. % % Output: % stat.xcorr = nchans-by-nchans-by-(2*nlags+1) cross correlation histogram % or % stat.shiftpredictor = nchans-by-nchans-by-(2*nlags+1) shift predictor. % both with dimord 'chan_chan_time' % stat.lags = (2*nlags + 1) vector with lags in seconds. % % stat.trial = ntrials-by-nchans-by-nchans-by-(2*nlags + 1) with single % trials and dimord 'rpt_chan_chan_time'; % stat.label = corresponding labels to channels in stat.xcorr % stat.cfg = configurations used in this function. % Copyright (C) 2010-2012, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % check input spike structure spike = ft_checkdata(spike,'datatype', 'spike', 'feedback', 'yes'); % get the default options cfg.trials = ft_getopt(cfg,'trials', 'all'); cfg.latency = ft_getopt(cfg,'latency','maxperiod'); cfg.keeptrials = ft_getopt(cfg,'keeptrials', 'no'); cfg.method = ft_getopt(cfg,'method', 'xcorr'); cfg.channelcmb = ft_getopt(cfg,'channelcmb', 'all'); cfg.vartriallen = ft_getopt(cfg,'vartriallen', 'yes'); cfg.debias = ft_getopt(cfg,'debias', 'yes'); cfg.maxlag = ft_getopt(cfg,'maxlag', 0.01); cfg.binsize = ft_getopt(cfg,'binsize', 0.001); cfg.outputunit = ft_getopt(cfg,'outputunit', 'proportion'); % ensure that the options are valid cfg = ft_checkopt(cfg, 'latency', {'char', 'ascendingdoublebivector'}); cfg = ft_checkopt(cfg, 'trials', {'char', 'doublevector', 'logical'}); cfg = ft_checkopt(cfg, 'keeptrials', 'char', {'yes', 'no'}); cfg = ft_checkopt(cfg, 'method', 'char', {'xcorr', 'shiftpredictor'}); cfg = ft_checkopt(cfg, 'channelcmb', {'char', 'cell'}); cfg = ft_checkopt(cfg, 'vartriallen', 'char', {'no', 'yes'}); cfg = ft_checkopt(cfg, 'debias', 'char', {'yes', 'no'}); cfg = ft_checkopt(cfg, 'maxlag', 'doublescalar'); cfg = ft_checkopt(cfg, 'binsize', 'doublescalar'); cfg = ft_checkopt(cfg, 'outputunit', 'char', {'proportion', 'center', 'raw'}); cfg = ft_checkconfig(cfg, 'allowed', {'latency', 'trials', 'keeptrials', 'method', 'channelcmb', 'vartriallen', 'debias', 'maxlag', 'binsize', 'outputunit'}); doShiftPredictor = strcmp(cfg.method, 'shiftpredictor'); % shift predictor % determine the corresponding indices of the requested channel combinations cfg.channelcmb = ft_channelcombination(cfg.channelcmb, spike.label(:), true); cmbindx = zeros(size(cfg.channelcmb)); for k=1:size(cfg.channelcmb,1) cmbindx(k,1) = strmatch(cfg.channelcmb(k,1), spike.label, 'exact'); cmbindx(k,2) = strmatch(cfg.channelcmb(k,2), spike.label, 'exact'); end nCmbs = size(cmbindx,1); chansel = unique(cmbindx(:)); % get the unique channels nChans = length(chansel); if isempty(chansel), error('No channel was selected'); end % get the number of trials or change SPIKE according to cfg.trials nTrials = size(spike.trialtime,1); if strcmp(cfg.trials,'all') cfg.trials = 1:nTrials; elseif islogical(cfg.trials) cfg.trials = find(cfg.trials); end cfg.trials = sort(cfg.trials(:)); if max(cfg.trials)>nTrials, error('maximum trial number in cfg.trials should not exceed length of DATA.trial'); end if isempty(cfg.trials), errors('No trials were selected in cfg.trials'); end nTrials = length(cfg.trials); % get the latencies begTrialLatency = spike.trialtime(cfg.trials,1); endTrialLatency = spike.trialtime(cfg.trials,2); trialDur = endTrialLatency - begTrialLatency; % select the latencies if strcmp(cfg.latency,'minperiod') cfg.latency = [max(begTrialLatency) min(endTrialLatency)]; elseif strcmp(cfg.latency,'maxperiod') cfg.latency = [min(begTrialLatency) max(endTrialLatency)]; elseif strcmp(cfg.latency,'prestim') cfg.latency = [min(begTrialLatency) 0]; elseif strcmp(cfg.latency,'poststim') cfg.latency = [0 max(endTrialLatency)]; end % check whether the time window fits with the data if (cfg.latency(1) < min(begTrialLatency)), cfg.latency(1) = min(begTrialLatency); warning('Correcting begin latency of averaging window'); end if (cfg.latency(2) > max(endTrialLatency)), cfg.latency(2) = max(endTrialLatency); warning('Correcting begin latency of averaging window'); end % get the maximum number of lags in samples fsample = (1/cfg.binsize); if cfg.maxlag>(cfg.latency(2)-cfg.latency(1)) warning('Correcting cfg.maxlag since it exceeds latency period'); cfg.maxlag = (cfg.latency(2) - cfg.latency(1)); end nLags = round(cfg.maxlag*fsample); lags = (-nLags:nLags)/fsample; % create the lag axis % check which trials will be used based on the latency fullDur = trialDur>=(cfg.maxlag); % only trials which are larger than maximum lag overlaps = endTrialLatency>(cfg.latency(1)+cfg.maxlag) & begTrialLatency<(cfg.latency(2)-cfg.maxlag); hasWindow = ones(nTrials,1); if strcmp(cfg.vartriallen,'no') % only select trials that fully cover our latency window startsLater = single(begTrialLatency) > (single(cfg.latency(1)) + 0.5*cfg.binsize); endsEarlier = single(endTrialLatency) < (single(cfg.latency(2)) - 0.5*cfg.binsize); hasWindow = ~(startsLater | endsEarlier); % check this in all other funcs end trialSel = fullDur(:) & overlaps(:) & hasWindow(:); cfg.trials = cfg.trials(trialSel); begTrialLatency = begTrialLatency(trialSel); endTrialLatency = endTrialLatency(trialSel); if isempty(cfg.trials), warning('No trials were selected'); end if length(cfg.trials)<2&&doShiftPredictor error('Shift predictor can only be calculated with more than 1 selected trial.'); end % if we allow variable trial lengths if strcmp(cfg.vartriallen,'yes') && doShiftPredictor && ~strcmp(cfg.outputunit,'proportion') warning('using cfg.vartriallen = "yes" and shift predictor method: please use cfg.outputunit = "proportion"'); end nTrials = length(cfg.trials); % only now reset nTrials % preallocate the sum and the single trials and the shift predictor keepTrials = strcmp(cfg.keeptrials,'yes'); s = zeros(nChans,nChans,2*nLags); if keepTrials warning('storing single trials for cross correlation is memory expensive, please check'); singleTrials = zeros(nTrials,nChans,nChans,2*nLags); end if strcmp(cfg.method,'shiftpredictor'), singleTrials(1,:,:,:) = NaN; end if ((cfg.latency(2)-cfg.latency(1))/cfg.maxlag)<2.5 warning('selected latency will cause highly variable xcorr at borders'); end doMex = 1; ft_progress('init', 'text', 'Please wait...'); for iTrial = 1:nTrials origTrial = cfg.trials(iTrial); ft_progress(iTrial/nTrials, 'Processing trial %d from %d', iTrial, nTrials); for iCmb = 1:nCmbs % take only the times that are in this trial and latency window indx = cmbindx(iCmb,:); inTrial1 = spike.trial{indx(1)}==origTrial; inTrial2 = spike.trial{indx(2)}==origTrial; inWindow1 = spike.time{indx(1)}>=cfg.latency(1) & spike.time{indx(1)}<=cfg.latency(2); inWindow2 = spike.time{indx(2)}>=cfg.latency(1) & spike.time{indx(2)}<=cfg.latency(2); ts1 = sort(spike.time{indx(1)}(inTrial1(:) & inWindow1(:))); ts2 = sort(spike.time{indx(2)}(inTrial2(:) & inWindow2(:))); switch cfg.method case 'xcorr' % compute the xcorr if both are non-empty if ~isempty(ts1) && ~isempty(ts2) if indx(1)<=indx(2) [x] = spike_crossx_matlab(ts1(:),ts2(:),cfg.binsize,nLags*2+1); % removed the mex file for now, until issue on windows is resolved else [x] = spike_crossx_matlab(ts2(:),ts1(:),cfg.binsize,nLags*2+1); % removed the mex file for now, until issue on windows is resolved end % remove the center peaks from the auto-correlogram if indx(1)==indx(2), x(nLags:nLags+1) = 0; end if strcmp(cfg.debias,'yes') lags = (-nLags:nLags)*cfg.binsize; lags = (lags(2:end)+lags(1:end-1))/2; T = nanmin([endTrialLatency(iTrial);cfg.latency(2)])-nanmax([begTrialLatency(iTrial);cfg.latency(1)]); sc = (T./(T-abs(lags(:)))); sc = length(sc)*sc./sum(sc); x = x(:).*sc(:); end % sum the xcorr s(indx(1),indx(2),:) = s(indx(1),indx(2),:) + shiftdim(x(:),-2); s(indx(2),indx(1),:) = s(indx(2),indx(1),:) + shiftdim(flipud(x(:)),-2); % store individual trials if requested if keepTrials singleTrials(iTrial,indx(1),indx(2),:) = shiftdim(x(:),-3); singleTrials(iTrial,indx(2),indx(1),:) = shiftdim(flipud(x(:)),-3); end end case 'shiftpredictor' if iTrial>1 % symmetric, get x21 to x12 and x22 to x11 inTrial1_old = spike.trial{indx(1)}==cfg.trials(iTrial-1); ts1_old = sort(spike.time{indx(1)}(inTrial1_old(:) & inWindow1(:))); inTrial2_old = spike.trial{indx(2)}==cfg.trials(iTrial-1); ts2_old = sort(spike.time{indx(2)}(inTrial2_old(:) & inWindow2(:))); % compute both combinations for k = 1:2 % take chan from this and previous channel if k==1 A = ts1; B = ts2_old; else A = ts1_old; B = ts2; end if ~isempty(A) && ~isempty(B), if indx(1)<=indx(2) [x] = spike_crossx_matlab(A(:),B(:),cfg.binsize,nLags*2+1); else [x] = spike_crossx_matlab(B(:),A(:),cfg.binsize,nLags*2+1); end % remove the center peaks from the auto-correlogram if indx(1)==indx(2), x(nLags:nLags+1) = 0; end if strcmp(cfg.debias,'yes') lags = (-nLags:nLags)*cfg.binsize; lags = (lags(2:end)+lags(1:end-1))/2; T = nanmin([endTrialLatency(iTrial);cfg.latency(2)])-nanmax([begTrialLatency(iTrial);cfg.latency(1)]); sc = (T./(T-abs(lags(:)))); sc = length(sc)*sc./sum(sc); x = x(:).*sc(:); end % compute the sum s(indx(1),indx(2),:) = s(indx(1),indx(2),:) + shiftdim(x(:),-2); s(indx(2),indx(1),:) = s(indx(2),indx(1),:) + shiftdim(flipud(x(:)),-2); if keepTrials singleTrials(iTrial,indx(1),indx(2),:) = shiftdim(x(:)/2,-3); singleTrials(iTrial,indx(2),indx(1),:) = shiftdim(flipud(x(:))/2,-3); end end end end end % symmetric shift predictor loop end % combinations end % trial loop ft_progress('close') % multiply the shift sum by a factor so it has the same scale as raw dofShiftPred = 2*(nTrials-1); if doShiftPredictor, s = s*nTrials/dofShiftPred; end switch cfg.outputunit case 'proportion' sm = repmat(nansum(s,3),[1 1 nLags*2]); s = s./sm; if keepTrials singleTrials = singleTrials./repmat(shiftdim(sm,-1),[nTrials 1 1 1]); end case 'center' center = repmat(s(:,:,nLags+1),[1 1 nLags*2]); s = s./center; if keepTrials singleTrials = singleTrials./repmat(shiftdim(center,-1),[nTrials 1 1 1]); end end % return the results stat.(cfg.method) = s; lags = (-nLags:nLags)*cfg.binsize; lags = (lags(2:end)+lags(1:end-1))/2; stat.time = lags; stat.dimord = 'chan_chan_time'; if keepTrials stat.trial = singleTrials; stat.dimord = 'trial_chan_chan_time'; end stat.label = spike.label(chansel); % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous spike ft_postamble history stat function [C] = spike_crossx_matlab(tX,tY,binsize,nbins) tX = sort(tX(:)); tY = sort(tY(:)); minLag = - binsize * (nbins-1) / 2; j = 0:nbins-1; B = minLag + j * binsize; tX(tX<(tY(1)+minLag) | tX>(tY(end)-minLag)) = []; if isempty(tX), C = zeros(1,length(B)-1); return; end tY(tY>(tX(end)-minLag) | tY<(tX(1)+minLag)) = []; if isempty(tY), C = zeros(1,length(B)-1); return; end nX = length(tX); nY = length(tY); % compute all distances at once using a multiplication trick if (nX*nY)<2*10^7 % allow matrix to grow to about 150 MB, should always work D = log(exp(-tX(:))*exp(tY(:)')); D = D(:); D(abs(D)>abs(minLag)) = []; [C] = histc(D,B); C(end) = []; else % break it down in pieces such that nX*nY<2*10*7 k = 2; nXs = round(nX/k); while (nXs*nY)>=(2*10^7) k = k+1; nXs = round(nX/k); end % get the indices steps = round(nX/k); begs = [1:steps:steps*k]; ends = begs+(steps-1); rm = begs>nX; begs(rm) = []; ends(rm) = []; ends(end) = nX; nSteps = length(begs); D = []; C = zeros(1,length(B)); for iStep = 1:nSteps d = log(exp(-tX(begs(iStep):ends(iStep)))*exp(tY(:)')); d = d(:); d(abs(d)>abs(minLag)) = []; C = C + histc(d,B)'; end C(end) = []; end if isempty(C) C = zeros(1,length(B)-1); end
github
lcnbeapp/beapp-master
ft_spike_plot_isi.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spike_plot_isi.m
4,783
utf_8
ae1249245a55f1f3f2a73625f0bfaf8a
function [cfg] = ft_spike_plot_isi(cfg, isih) % FT_SPIKE_PLOT_ISI makes an inter-spike-interval bar plot. % % Use as % ft_spike_plot_isi(cfg, isih) % % Inputs: % ISIH is the output from FT_SPIKE_ISIHIST % % Configurations: % cfg.spikechannel = string or index or logical array to to select 1 spike channel. % (default = 1). % cfg.ylim = [min max] or 'auto' (default) % If 'auto', we plot from 0 to 110% of maximum plotted value); % cfg.plotfit = 'yes' (default) or 'no'. This requires that when calling % FT_SPIKESTATION_ISI, cfg.gammafit = 'yes'. % % Outputs: % hdl.fit = handle for line fit. Use SET and GET to access. % hdl.isih = handle for bar isi histogram. Use SET and GET to access. % Copyright (C) 2010, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % get the default options cfg.spikechannel = ft_getopt(cfg,'spikechannel', 'all'); cfg.ylim = ft_getopt(cfg,'ylim', 'auto'); cfg.plotfit = ft_getopt(cfg,'plotfit', 'no'); % ensure that the options are valid cfg = ft_checkopt(cfg,'spikechannel',{'cell', 'char', 'double'}); cfg = ft_checkopt(cfg,'ylim', {'char','ascendingdoublebivector'}); cfg = ft_checkopt(cfg,'plotfit', 'char', {'yes', 'no'}); % get the spikechannels cfg.channel = ft_channelselection(cfg.spikechannel, isih.label); spikesel = match_str(isih.label, cfg.channel); nUnits = length(spikesel); % number of spike channels if nUnits~=1, error('One spikechannel should be selected by means of cfg.spikechannel'); end % plot the average isih isiHdl = bar(isih.time,isih.avg(spikesel,:),'k'); set(isiHdl,'BarWidth', 1) if strcmp(cfg.plotfit,'yes') if ~isfield(isih,'gamfit'), error('isih.gamfit should be present when cfg.plotfit = yes'); end % generate the probabilities according to the gamma model pGamma = gampdf(isih.time, isih.gamfit(spikesel,1), isih.gamfit(spikesel,2)); sel = isfinite(pGamma); pGamma = pGamma(sel)./sum(pGamma(sel)); % scale the fit in the same way (total area is equal) sumIsih = sum(isih.avg(spikesel,:),2); pGamma = pGamma*sumIsih; % plot the fit hold on fitHdl = plot(isih.time(sel), pGamma,'r'); else pGamma = 0; end try if strcmp(isih.cfg.outputunit, 'proportion') ylabel('probability') elseif strcmp(isih.cfg.outputunit, 'spikecount') ylabel('spikecount') end catch ylabel('intensity'); end xlabel('bin edges (sec)') % set the x axis set(gca,'XLim', [min(isih.time) max(isih.time)]) % set the y axis if strcmp(cfg.ylim, 'auto') y = [isih.avg(spikesel,:) pGamma]; cfg.ylim = [0 max(y(:))*1.1+eps]; end set(gca,'YLim', cfg.ylim) set(gca,'TickDir','out') % store the handles if strcmp(cfg.plotfit,'yes'), H.fit = fitHdl; end H.isih = isiHdl; % as usual, make sure that panning and zooming does not distort the y limits set(zoom,'ActionPostCallback',{@mypostcallback,cfg.ylim,[min(isih.time) max(isih.time)]}); set(pan,'ActionPostCallback',{@mypostcallback,cfg.ylim,[min(isih.time) max(isih.time)]}); % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous isih %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = mypostcallback(fig,evd,limY,limX) % get the x limits and reset them ax = evd.Axes; xlim = get(ax(1), 'XLim'); ylim = get(ax(1), 'YLim'); if limX(1)>xlim(1), xlim(1) = limX(1); end if limX(2)<xlim(2), xlim(2) = limX(2); end if limY(1)>ylim(1), ylim(1) = limY(1); end if limY(2)<ylim(2), ylim(2) = limY(2); end set(ax(1), 'XLim',xlim) set(ax(1), 'YLim',ylim);
github
lcnbeapp/beapp-master
ft_spike_plot_jpsth.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spike_plot_jpsth.m
13,192
utf_8
d52c82a28b5a7f91c7301fd2bd7baaa8
function [cfg] = ft_spike_plot_jpsth(cfg, jpsth) % FT_SPIKE_PLOT_JPSTH makes a plot from JPSTH structure. % % Use as % ft_spike_plot_jpsth(cfg, jpsth) % % Inputs: % JPSTH must be the output structure from FT_SPIKE_JPSTH and contain the % field JPSTH.avg. If cfg.psth = 'yes', the field JPSTH.psth must be % present as well. % % General configurations: % cfg.channelcmb = string or index of single channel combination to trigger on. % See SPIKESTATION_FT_SUB_CHANNELCOMBINATION for details. % cfg.psth = 'yes' (default) or 'no'. Plot PSTH with JPSTH if 'yes'; % cfg.latency = [begin end] in seconds or 'max' (default), 'prestim' or 'poststim'; % cfg.colorbar = 'yes' (default) or 'no' % cfg.colormap = N-by-3 colormap (see COLORMAP). or 'auto' (default,hot(256)) % cfg.interpolate = integer (default = 1), we perform interpolating % with extra number of spacings determined by % cfg.interpolate. For example cfg.interpolate = 5 % means 5 times more dense axis. % cfg.window = 'string' or N-by-N matrix % 'no': apply no smoothing % ' gausswin' use a Gaussian smooth function % ' boxcar' use a box-car to smooth % cfg.gaussvar = variance (default = 1/16 of window length in sec). % cfg.winlen = cfg.window length in seconds (default = 5*binwidth). % length of our window is 2*round*(cfg.winlen/binwidth) % where binwidth is the binwidth of the jpsth (jpsth.time(2)-jpsth.time(1)). % % See also FT_SPIKE_JPSTH, FT_SPIKE_PSTH % FIXME: extend the windowing functions a bit % Copyright (C) 2010, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % get the default options cfg.channelcmb = ft_getopt(cfg,'channelcmb', 'all'); cfg.psth = ft_getopt(cfg,'psth', 'yes'); cfg.latency = ft_getopt(cfg,'latency','maxperiod'); cfg.colorbar = ft_getopt(cfg,'colorbar', 'yes'); cfg.colormap = ft_getopt(cfg,'colormap', jet(256)); cfg.interpolate = ft_getopt(cfg,'interpolate', 1); cfg.window = ft_getopt(cfg,'window', 'no'); cfg.winlen = ft_getopt(cfg,'winlen', 5*(mean(diff(jpsth.time)))); cfg.gaussvar = ft_getopt(cfg,'gaussvar', (cfg.winlen/4).^2); % ensure that the options are valid cfg = ft_checkopt(cfg,'channelcmb', {'char', 'cell'}); cfg = ft_checkopt(cfg,'psth', 'char', {'yes', 'no'}); cfg = ft_checkopt(cfg,'latency', {'char', 'ascendingdoublebivector'}); cfg = ft_checkopt(cfg,'colorbar', 'char', {'yes', 'no'}); cfg = ft_checkopt(cfg,'colormap','double'); cfg = ft_checkopt(cfg,'interpolate', 'doublescalar'); cfg = ft_checkopt(cfg,'window','char', {'no', 'gausswin', 'boxcar'}); cfg = ft_checkopt(cfg,'winlen', 'double'); cfg = ft_checkopt(cfg,'gaussvar', 'double'); cfg = ft_checkconfig(cfg, 'allowed', {'channelcmb', 'psth', 'latency', 'colorbar', 'colormap', 'interpolate', 'window', 'winlen', 'gaussvar'}); % determine the corresponding indices of the requested channel combinations cfg.channelcmb = ft_channelcombination(cfg.channelcmb, jpsth.label); cmbindx = zeros(size(cfg.channelcmb)); for k=1:size(cfg.channelcmb,1) cmbindx(k,1) = strmatch(cfg.channelcmb(k,1), jpsth.label, 'exact'); cmbindx(k,2) = strmatch(cfg.channelcmb(k,2), jpsth.label, 'exact'); end nCmbs = size(cmbindx,1); if nCmbs~=1, error('Currently only supported for a single channel combination'); end % for convenience create a separate variable if isfield(jpsth,'jpsth') dens = squeeze(jpsth.jpsth(cmbindx(1,1),cmbindx(1,2),:,:)); % density else dens = squeeze(jpsth.shiftpredictor(cmbindx(1,1),cmbindx(1,2),:,:)); % density end % get rid of the NaNs at the borders isNaN = 1; k = 1; while isNaN if any(isnan(jpsth.psth(cmbindx,k))), disp('deleting NaNs at the borders') jpsth.psth(:,k) = []; dens(k,:) = []; dens(:,k) = []; jpsth.time(k) = []; else isNaN = 0; end end isNaN = 1; k = size(jpsth.psth,2); while isNaN if any(isnan(jpsth.psth(cmbindx,k))), disp('deleting NaNs at the borders') jpsth.psth(:,k) = []; dens(k,:) = []; dens(:,k) = []; jpsth.time(k) = []; k = size(jpsth.psth,2); else isNaN = 0; end end % select the time minTime = jpsth.time(1); maxTime = jpsth.time(end); if strcmp(cfg.latency,'maxperiod') cfg.latency = [minTime maxTime]; elseif strcmp(cfg.latency,'poststim') cfg.latency = [0 maxTime]; elseif strcmp(cfg.latency,'prestim') cfg.latency = [minTime 0]; end % check whether the time window fits with the data if (cfg.latency(1) < minTime), cfg.latency(1) = minTime; warning('Correcting begin latency of averaging window'); end if (cfg.latency(2) > maxTime), cfg.latency(2) = maxTime; warning('Correcting end latency of averaging window'); end % get the samples of our window, and the binwidth of the JPSTH timeSel = jpsth.time>=cfg.latency(1) & jpsth.time <= cfg.latency(2); sampleTime = mean(diff(jpsth.time)); % get the binwidt % smooth the jpsth with a kernel if requested if ~strcmp(cfg.window,'no') % construct the kernel winTime = [fliplr(0:-sampleTime:-cfg.winlen) sampleTime:sampleTime:cfg.winlen]; winLen = length(winTime); if strcmp(cfg.window, 'gausswin') % multivariate gaussian A = winTime'*ones(1,winLen); B = A'; T = [A(:) B(:)]; % makes rows with each time combination on it covmat = diag([cfg.gaussvar cfg.gaussvar]); % covariance matrix win = mvnpdf(T,0,covmat); % multivariate gaussian function elseif strcmp(cfg.window, 'boxcar') win = ones(winLen); end % turn into discrete probabilities again (sum(p)=1); win = win./sum(win(:)); win = reshape(win,[],winLen); % do 2-D convolution and rescale dens = conv2(dens,win,'same'); outputOnes = conv2(ones(size(dens)),win,'same'); rescale = 1./outputOnes; dens = dens.*rescale; end bins = jpsth.time; ax(1) = newplot; % create a new axis object origPos = get(ax(1), 'Position'); pos = origPos; if cfg.interpolate>1 binAxis = linspace(min(bins), max(bins), round(length(bins)*cfg.interpolate)); % CHANGE THIS densInterp = interp2(bins(:), bins(:), dens, binAxis(:), binAxis(:)', 'spline'); jpsthHdl = imagesc(binAxis, binAxis, densInterp); else jpsthHdl = imagesc(bins,bins,dens); end axis xy; colormap(cfg.colormap); % set the colormap view(ax(1),2); % use the top view grid(ax(1),'off'); % toggle grid off % we need to leave some space for the colorbar on the top if strcmp(cfg.colorbar,'yes'), pos(3) = pos(3)*0.95; end % plot the histogram if requested if strcmp(cfg.psth,'yes') startPos = pos(1:2) + pos(3:4)*0.2 ; % shift the height and the width 20% sz = pos(3:4)*0.8; % decrease the size of width and height set(ax(1), 'ActivePositionProperty', 'position', 'Position', [startPos sz]) % scale the isi such that it becomes 1/5 of the return plot for iChan = 1:2 % get the data and create the strings that should be the labels psth = jpsth.psth(cmbindx(1,iChan),timeSel); label = jpsth.label{cmbindx(1,iChan)}; if iChan==2 startPos = pos(1:2) + pos(3:4).*[0.2 0] ; % shift the width 20% sz = pos(3:4).*[0.8 0.2]; % and decrease the size of width and height ax(2) = axes('Units', get(ax(1), 'Units'), 'Position', [startPos sz],... 'Parent', get(ax(1), 'Parent')); psthHdl(iChan) = bar(jpsth.time(timeSel),psth,'k'); % plot the psth under the jpsth set(ax(2),'YDir', 'reverse') ylabel(label) else startPos = pos(1:2) + pos(3:4).*[0 0.2] ; % shift the height 20% sz = pos(3:4).*[0.2 0.8]; % and decrease the size of width and height ax(3) = axes('Units', get(ax(1), 'Units'), 'Position', [startPos sz],... 'Parent', get(ax(1), 'Parent')); psthHdl(iChan) = barh(jpsth.time(timeSel),psth,'k'); % plot the psth left set(ax(3),'XDir', 'reverse') xlabel(label) end end set(ax(2), 'YAxisLocation', 'Right', 'XGrid', 'off'); % change the y axis location set(ax(3), 'XAxisLocation', 'Top', 'XGrid', 'off'); % change the x axis location set(psthHdl, 'BarWidth', 1); % make sure bars have no space between % change the limits to get the same time limits set(ax(2),'XLim', cfg.latency) set(ax(3),'YLim', cfg.latency) set(get(ax(2),'XLabel'),'String', 'time (sec)') set(get(ax(3),'YLabel'),'String', 'time (sec)') set(ax(1), 'YTickLabel', {},'XTickLabel', {}); % we remove the labels from JPSTH now H.psthleft = psthHdl(2); H.psthbottom = psthHdl(1); elseif strcmp(cfg.psth,'no') xlabel('time (sec)') ylabel('time (sec') set(ax(1), 'ActivePositionProperty', 'position', 'Position',pos) end % create the colorbar if requested if strcmp(cfg.colorbar,'yes') caxis([min(dens(:))-0.05 max(dens(:))+0.05]) colormap(cfg.colormap); % create the colormap as the user wants H.colorbarHdl = colorbar; % create a colorbar % create a position vector and reset the position, it should be alligned right of JPSTH startPos = [(pos(1) + 0.96*origPos(3)) (pos(2) + pos(4)*0.25)]; sizePos = [0.04*origPos(3) 0.75*pos(4)]; set(H.colorbarHdl, 'Position', [startPos sizePos]) % set the text, try all the possible configurations try isNormalized = strcmp(jpsth.cfg.normalization,'yes'); catch isNormalized = 0; end try unit = jpsth.cfg.previous.outputunit; if strcmp(unit,'rate') isRate = 1; elseif strcmp(unit,'spikecount') isRate = 2; end catch isRate = 3; end if isNormalized colorbarLabel = 'Normalized Joint Activity'; elseif isRate==1 colorbarLabel = 'Joint Firing Rate (spikes^2/sec^2)'; elseif isRate==2 colorbarLabel = 'Joint Spike Count (spikes^2)'; else colorbarLabel = 'Joint Peristimulus Activity'; end try if strcmp(jpsth.cfg.shiftpredictor,'yes') colorbarLabel = strcat(colorbarLabel,' Shift Predictor'); end catch,end set(get(H.colorbarHdl,'YLabel'),'String',colorbarLabel) end set(ax,'TickDir','out') set(ax(1),'XLim', cfg.latency,'YLim', cfg.latency) % get the psth limits for constraining the zooming and panning psthLim = {}; if strcmp(cfg.psth,'yes') psthLim{1} = get(ax(2),'YLim'); psthLim{2} = get(ax(3),'XLim'); end % collect the handles H.ax = ax; H.jpsth = jpsthHdl; H.cfg = cfg; % constrain the zooming and zoom psth together with the jpsth, remove ticklabels jpsth set(zoom,'ActionPostCallback',{@mypostcallback,ax,cfg.latency,psthLim}); set(pan,'ActionPostCallback',{@mypostcallback,ax,cfg.latency,psthLim}); % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous jpsth %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = mypostcallback(fig,evd,ax,lim,psthLim) currentAxes = evd.Axes; xlim = get(currentAxes, 'XLim'); ylim = get(currentAxes, 'YLim'); if currentAxes==ax(1) % reset the x limits to the shared limits if lim(1)>xlim(1), xlim(1) = lim(1); end if lim(2)<xlim(2), xlim(2) = lim(2); end set(ax(1:2), 'XLim',xlim) % reset the y limits if lim(1)>ylim(1), ylim(1) = lim(1); end if lim(2)<ylim(2), ylim(2) = lim(2); end set(ax([1 3]), 'YLim',ylim) elseif currentAxes == ax(2) % reset the x and y limits if lim(1)>xlim(1), xlim(1) = lim(1); end if lim(2)<xlim(2), xlim(2) = lim(2); end if psthLim{1}(1)>ylim(1), ylim(1) = psthLim{1}(1); end if psthLim{1}(2)<ylim(2), ylim(2) = psthLim{1}(2); end set(ax(1:2), 'XLim',xlim) set(ax(3), 'YLim', xlim) set(ax(2),'YLim', ylim) elseif currentAxes == ax(3) % y limits are shared limits here if lim(1)>ylim(1), ylim(1) = lim(1); end if lim(2)<ylim(2), ylim(2) = lim(2); end % psth limit is specific to its x axis if psthLim{2}(1)>xlim(1), xlim(1) = psthLim{2}(1); end if psthLim{2}(2)<xlim(2), xlim(2) = psthLim{2}(2); end set(ax(1:2), 'XLim',ylim) set(ax(3), 'YLim', ylim) set(ax(3),'XLim', xlim) end set(ax(1), 'YTickLabel', {}); set(ax(1), 'XTickLabel', {});
github
lcnbeapp/beapp-master
ft_spike_plot_isireturn.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/ft_spike_plot_isireturn.m
12,153
utf_8
8622e6b75dbc92336c1b2713baa56e48
function [cfg] = ft_spike_plot_isireturn(cfg, isih) % FT_SPIKE_PLOT_ISIRETURN makes a return plot from ISIH structure. A return % plot (also called Poincare plot) plots the isi to the next spike versus the isi % from the next spike to the second next spike, and thus gives insight in % the second order isi statistics. This func also plots the raw % isi-histogram on left and bottom and thereby give a rather complete % visualization of the spike-train interval statistics. % % Use as % ft_spike_plot_isireturn(cfg, data) % % Inputs: % ISIH must be the output structure from FT_SPIKE_ISI and contain the field % ISIH.isi. % % General configurations: % cfg.spikechannel = string or index of single spike channel to trigger on (default = 1) % Only one spikechannel can be plotted at a time. % cfg.density = 'yes' or 'no', if 'yes', we will use color shading on top of % the individual datapoints to indicate the density. % cfg.scatter = 'yes' (default) or 'no'. If 'yes', we plot the individual values. % cfg.dt = resolution of the 2-D histogram, or of the kernel plot in seconds. Since we % have to smooth for a finite number of values, cfg.dt determines % the resolution of our smooth density plot. % cfg.colormap = N-by-3 colormap (see COLORMAP). Default = hot(256); % cfg.interpolate = integer (default = 1), we perform interpolating % with extra number of spacings determined by % cfg.interpolate. For example cfg.interpolate = 5 % means 5 times more dense axis. % cfg.window = 'no', 'gausswin' or 'boxcar' % 'gausswin' is N-by-N multivariate gaussian, where the diagonal of the % covariance matrix is set by cfg.gaussvar. % 'boxcar' is N-by-N rectangular window. % cfg.gaussvar = variance (default = 1/16 of window length in sec). % cfg.winlen = window length in seconds (default = 5*cfg.dt). The total % length of our window is 2*round*(cfg.winlen/cfg.dt) +1; % Copyright (C) 2010, Martin Vinck % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are used by the ft_preamble/ft_postamble function and scripts ft_revision = '$Id$'; ft_nargin = nargin; ft_nargout = nargout; % do the general setup of the function ft_defaults ft_preamble init ft_preamble callinfo ft_preamble trackconfig % get the default options cfg.spikechannel = ft_getopt(cfg, 'spikechannel', isih.label{1}); cfg.scatter = ft_getopt(cfg, 'scatter', 'yes'); cfg.density = ft_getopt(cfg,'density', 'yes'); cfg.colormap = ft_getopt(cfg,'colormap', 'auto'); cfg.interpolate = ft_getopt(cfg, 'interpolate', 1); cfg.scattersize = ft_getopt(cfg,'scattersize', 0.3); cfg.dt = ft_getopt(cfg,'dt', 0.001); cfg.window = ft_getopt(cfg,'window', 'gausswin'); cfg.winlen = ft_getopt(cfg,'winlen', cfg.dt*5); cfg.gaussvar = ft_getopt(cfg,'gaussvar', (cfg.winlen/4).^2); cfg = ft_checkopt(cfg, 'spikechannel', {'char', 'cell', 'double'}); cfg = ft_checkopt(cfg, 'scatter','char', {'yes', 'no'}); cfg = ft_checkopt(cfg, 'density', 'char', {'yes', 'no'}); cfg = ft_checkopt(cfg, 'colormap', {'double', 'char'}); cfg = ft_checkopt(cfg, 'interpolate', 'doublescalar'); cfg = ft_checkopt(cfg, 'scattersize', 'doublescalar'); cfg = ft_checkopt(cfg, 'dt', 'double'); cfg = ft_checkopt(cfg, 'window','char',{'no', 'gausswin', 'boxcar'}); cfg = ft_checkopt(cfg, 'winlen', 'double'); cfg = ft_checkopt(cfg, 'gaussvar', 'double'); cfg.interpolate = round(cfg.interpolate); % check if all the required fields are there isih = ft_checkdata(isih,'datatype', 'timelock', 'feedback', 'yes'); if ~isfield(isih,'isi'), error('input struct should contain the fields isi, label and time'), end cfg = ft_checkconfig(cfg, 'allowed', {'spikechannel', 'scatter', 'density', 'colormap', 'interpolate', 'scattersize', 'dt', 'window', 'winlen', 'gaussvar'}); % get the spikechannels: maybe replace this by one function with checking etc. in it cfg.spikechannel = ft_channelselection(cfg.spikechannel, isih.label); spikesel = match_str(isih.label, cfg.spikechannel); nUnits = length(spikesel); % number of spike channels if nUnits~=1, error('Only one unit can be selected at a time'); end isi = isih.isi{spikesel}; % create the axis ax(1) = newplot; [origPos,pos] = deal(get(ax(1), 'Position')); if strcmp(cfg.density,'yes'), pos(3) = pos(3)*0.95; end % because of the color bar which takes place bins = min(isih.time):cfg.dt:max(isih.time); nbins = length(bins); % two-dimensional kernel smoothing to get a density behind our scatterplot if strcmp(cfg.density,'yes') isivld1 = (~isnan(isi(1:end-1))&~isnan(isi(2:end))); isivld2 = (isi(1:end-1)<=max(isih.time)-cfg.dt&isi(2:end)<=max(isih.time)-cfg.dt); isivld = isivld1&isivld2; hold on % make a 2-D histogram, we need this for both the kernel and the hist [N,indx1] = histc(isi(find(isivld)),bins); [N,indx2] = histc(isi(find(isivld)+1),bins); % remove the outer counts rmv = indx1==length(bins)|indx2==length(bins); indx1(rmv) = []; indx2(rmv) = []; dens = full(sparse(indx2,indx1,ones(1,length(indx1)),nbins,nbins)); if ~strcmp(cfg.window,'no') if cfg.winlen<cfg.dt, error('please configure cfg.winlen such that cfg.winlen>=cfg.dt'); end winTime = [fliplr(0:-cfg.dt:-cfg.winlen) cfg.dt:cfg.dt:cfg.winlen]; winLen = length(winTime); if strcmp(cfg.window, 'gausswin') % multivariate gaussian A = winTime'*ones(1,winLen); B = A'; T = [A(:) B(:)]; % makes rows with each time combination on it covmat = diag([cfg.gaussvar cfg.gaussvar]); % covariance matrix win = mvnpdf(T,0,covmat); % multivariate gaussian function elseif strcmp(cfg.window, 'boxcar') win = ones(winLen); end % turn into discrete probabilities again (sum(p)=1); win = win./sum(win); win = reshape(win,[],length(winTime)); % reshape to matrix corresponding to grid again % do 2-D convolution and rescale dens = conv2(dens,win,'same'); outputOnes = conv2(ones(size(dens)),win,'same'); rescale = 1./outputOnes; dens = dens.*rescale; end % create the surface hdl.density = imagesc(bins+cfg.dt/2,bins+cfg.dt/2,dens); if cfg.interpolate>1 binAxis = linspace(min(bins)-0.5*(bins(2)-bins(1)), max(bins)+0.5*(bins(2)-bins(1)), length(bins)*cfg.interpolate); dens = interp2(bins(:), bins(:), dens, binAxis(:), binAxis(:)', 'linear'); hdl.density = imagesc(binAxis, binAxis, dens); end if isrealmat(cfg.colormap) && size(cfg.colormap,2)==3 colormap(cfg.colormap); elseif strcmp(cfg.colormap, 'auto') cfg.colormap = flipud(hot(600)); cfg.colormap = cfg.colormap(1:450,:); else error('cfg.colormap should be N-by-3 numerical matrix') end view(ax(1),2); % use the top view grid(ax(1),'off') end hold on % create scatter return plot and get the handle if strcmp(cfg.scatter, 'yes') hdl.scatter = plot(isi(1:end-1), isi(2:end),'ko'); set(hdl.scatter,'MarkerFaceColor', 'k','MarkerSize', cfg.scattersize) end %keyboard % plot the histogram (user can cut away in adobe of canvas himself if needed) posisih = [pos(1:2) + pos(3:4)*0.2 pos(3:4)*0.8]; % shift the height and the width 20% set(ax(1), 'ActivePositionProperty', 'position', 'Position', posisih) startPos = pos(1:2) + pos(3:4).*[0.2 0] ; % shift the width 20% sz = pos(3:4).*[0.8 0.2]; % and decrease the size of width and height ax(2) = axes('Units', get(ax(1), 'Units'), 'Position', [startPos sz],... 'Parent', get(ax(1), 'Parent')); isihist = isih.avg(spikesel,:); %divide by proportion and 5 to get 20% of size hdl.isi(1) = bar(isih.time(:),isihist,'k'); set(ax(2),'YDir', 'reverse') startPos = pos(1:2) + pos(3:4).*[0 0.2] ; % shift the height 20% sz = pos(3:4).*[0.2 0.8]; % and decrease the size of width and height ax(3) = axes('Units', get(ax(1), 'Units'), 'Position', [startPos sz],... 'Parent', get(ax(1), 'Parent')); hdl.isi(2) = barh(isih.time(:),isihist,'k'); set(hdl.isi,'BarWidth',1) set(ax(2:3), 'Box', 'off') set(ax(3),'XDir', 'reverse') set(ax(1), 'YTickLabel', {},'XTickLabel',{}, 'XTick',[],'YTick', []); % take care of all the x and y limits at once set(ax,'Box', 'off','TickDir','out') set(ax(1),'XLim', [0 max(isih.time)],'YLim',[0 max(isih.time)]); limIsi = [0 max(isih.avg(spikesel,:))*1.05]; set(ax(2),'XLim', [0 max(isih.time)],'YLim',limIsi); set(ax(3),'YLim', [0 max(isih.time)],'XLim',limIsi); set(ax(2),'YAxisLocation', 'Right') set(ax(3),'XAxisLocation', 'Top') set(get(ax(2),'Xlabel'),'String','isi(n) (sec)') set(get(ax(3),'Ylabel'),'String','isi(n+1) (sec)') % create the colorbar (who doesn't want one) caxis([min(dens(:)) max(dens(:))]); colormap(cfg.colormap); % create the colormap as the user wants colorbarHdl = colorbar; % create a colorbar % create a position vector and reset the position, it should be alligned right of isih startPos = [(pos(1) + 0.96*origPos(3)) (pos(2) + pos(4)*0.25)]; sizePos = [0.04*origPos(3) 0.75*pos(4)]; set(colorbarHdl, 'Position', [startPos sizePos]) set(get(colorbarHdl,'YLabel'),'String','Number of spikes per bin'); % set the text hdl.colorbar = colorbarHdl; hdl.ax = ax; hdl.cfg = cfg; % constrain the zooming and zoom psth together with the isih, remove ticklabels isih set(zoom,'ActionPostCallback',{@mypostcallback,ax,[0 max(isih.time)],limIsi}); set(pan,'ActionPostCallback',{@mypostcallback,ax,[0 max(isih.time)],limIsi}); % do the general cleanup and bookkeeping at the end of the function ft_postamble trackconfig ft_postamble callinfo ft_postamble previous isih %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [] = mypostcallback(fig,evd,ax,lim,limIsi) currentAxes = evd.Axes; indx = find(currentAxes==ax); if currentAxes==ax(1) % get the x limits and reset them xlim = get(ax(1), 'XLim'); ylim = get(ax(1), 'YLim'); [axlim] = [min(xlim(1),ylim(1)) max(xlim(2),ylim(2))]; % make the zoom symmetric if lim(1)>axlim(1), axlim(1) = lim(1); end if lim(2)<axlim(2), axlim(2) = lim(2); end set(ax(1:2), 'XLim',axlim) set(ax([1 3]), 'YLim',axlim); elseif currentAxes == ax(2) xlim = get(ax(2), 'XLim'); if lim(1)>xlim(1), xlim(1) = lim(1); end if lim(2)<xlim(2), xlim(2) = lim(2); end set(ax(1:2), 'XLim',xlim) set(ax(3), 'YLim', xlim) ylim = get(ax(2), 'YLim'); if limIsi(1)>ylim(1), ylim(1) = limIsi(1); end if limIsi(2)<ylim(2), ylim(2) = limIsi(2); end set(ax(2), 'YLim', ylim) set(ax(3), 'XLim', ylim) elseif currentAxes == ax(3) ylim = get(ax(3), 'YLim'); if lim(1)>ylim(1), ylim(1) = lim(1); end if lim(2)<ylim(2), ylim(2) = lim(2); end set(ax([1 3]), 'YLim',ylim); set(ax(2), 'XLim', ylim) xlim = get(ax(3), 'XLim'); if limIsi(1)>xlim(1), xlim(1) = limIsi(1); end if limIsi(2)<xlim(2), xlim(2) = limIsi(2); end set(ax(3), 'XLim', xlim) set(ax(2), 'YLim', xlim) end
github
lcnbeapp/beapp-master
test_ft_spiketriggeredspectrum_stat.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/spike/test/test_ft_spiketriggeredspectrum_stat.m
2,343
utf_8
c0b669f66bc952bb2a588904bf5e9faf
function test_ft_spiketriggeredspectrum_stat() % MEM 1gb % WALLTIME 00:10:00 % TEST test_ft_spiketriggeredspectrum_stat % TEST ft_spiketriggeredspectrum_stat nSpikes = 10000; randPhases = []; kappa = 1; nChans = 3; for iChan = 1:nChans for iFreq = 1:6 randPhases(:,iChan,iFreq) = randnwrap(nSpikes+1,kappa/iChan); end end figure, rose(randPhases(:,1,1)) sts = []; sts.fourierspctrm{1} = rand(size(randPhases)).*exp(1i*randPhases); % random weighting sts.trial{1} = sort(ceil(rand(1,nSpikes)*100)); sts.time{1} = rand(1,nSpikes); for iChan = 1:nChans sts.lfplabel{iChan} = strcat('chan', num2str(iChan)); end sts.cfg = []; sts.dimord = 'rpt_chan_freq'; sts.freq = 10:10:60; sts.label = {'unit1'}; sts.trialtime = repmat([0,1],[100 1]); cfg = []; cfg.timwin = 0.5; cfg.winstepsize = 0.001; cfg.method = 'ppc0'; sts_tfr = ft_spiketriggeredspectrum_stat(cfg,sts); figure, imagesc(sts_tfr.time, sts_tfr.freq, squeeze(sts_tfr.ppc0(1,:,:))), colorbar % cfg.method = 'ppc1'; sts_tfr = ft_spiketriggeredspectrum_stat(cfg,sts); figure, imagesc(sts_tfr.time, sts_tfr.freq, squeeze(sts_tfr.ppc1(1,:,:))), colorbar % cfg = []; cfg.method = 'ppc1'; sts_tfr = ft_spiketriggeredspectrum_stat(cfg,sts); figure, plot(sts_tfr.freq, squeeze(sts_tfr.ppc1(1,:,:))), colorbar %% % now make a case where no phase locking should be present % TEST test_ft_spiketriggeredspectrum_tfr % ft_spiketriggeredspectrum_tfr nSpikes = 10000; randPhases = []; kappa = 1; nChans = 3; for iChan = 1:nChans for iFreq = 1:6 randPhases(:,iChan,iFreq) = randnwrap(nSpikes+1,0.001/iChan); end end figure, rose(randPhases(:,1,1)) sts = []; sts.fourierspctrm{1} = rand(size(randPhases)).*exp(i*randPhases); % random weighting sts.trial{1} = sort(ceil(rand(1,nSpikes)*100)); sts.time{1} = rand(1,nSpikes); for iChan = 1:nChans sts.lfplabel{iChan} = strcat('chan', num2str(iChan)); end sts.cfg = []; sts.dimord = 'rpt_chan_freq'; sts.freq = 10:10:60; sts.label = {'unit1'}; sts.trialtime = repmat([0,1],[100 1]); cfg = []; cfg.timwin = 0.5; cfg.winstepsize = 0.001; cfg.method = 'ppc0'; sts_tfr = ft_spiketriggeredspectrum_stat(cfg,sts); figure, imagesc(sts_tfr.time, sts_tfr.freq, squeeze(sts_tfr.ppc0(1,:,:))), colorbar function r=randnwrap(n,k) r=angle(exp(1i*randn(n,1)*sqrt(1/k)));
github
lcnbeapp/beapp-master
nmt_transform_coord.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/nutmegtrip/nmt_transform_coord.m
1,383
utf_8
45ec93e41ec1e8943ab8f2c2ea73dd0e
function [xyz_o,y_o,z_o] = nmt_transform_coord(varargin) % [XYZ_O]=NUT_COORDTFM(A,XYZ_I) % [X_O,Y_O,Z_O]=NUT_COORDTFM(A,X_I,Y_I,Z_I) % Performs coordinate transformation using transform matrix A. % Supply either xyz_i as an N x 3 matrix containing cartesian coordinates % or x_i, y_i, and z_i in separate N x 1 vectors. % A should be 4 x 4. switch nargin case 4 % if given x,y,z in separate N x 1 vectors [A,x_i,y_i,z_i] = deal(varargin{:}); xyz=[x_i y_i z_i ones(length(z_i),1)]*A'; xyz_o=xyz(:,1); % really just x in this case y_o=xyz(:,2); z_o=xyz(:,3); if(~isequal(xyz(:,4),ones(size(xyz(:,4)))))% if fourth column is not a bunch of ones, something went wrong warning('something may have gone awry with this coordinate transform.'); end case 2 % if given N x 3 matrix with x,y,z coords [A,xyz_i] = deal(varargin{:}); xyz_o=[xyz_i ones(size(xyz_i,1),1)]*A'; % if(~isequal(xyz_o(:,4),ones(size(xyz_o(:,4)))))% if fourth column is not a bunch of ones, something went wrong if(norm(xyz_o(:,4)-1,'fro')>1e-13)% if fourth column is not a bunch of ones, something went wrong warning('something may have gone awry with this coordinate transform.'); end xyz_o(:,4)=[]; % destroy last column of ones otherwise error('You''re doing something wrong.'); end
github
lcnbeapp/beapp-master
getdimord.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/nutmegtrip/private/getdimord.m
20,107
utf_8
706f4f45a5d4ae7535c204b8c010f76b
function dimord = getdimord(data, field, varargin) % GETDIMORD % % Use as % dimord = getdimord(data, field) % % See also GETDIMSIZ, GETDATFIELD if ~isfield(data, field) && isfield(data, 'avg') && isfield(data.avg, field) field = ['avg.' field]; elseif ~isfield(data, field) && isfield(data, 'trial') && isfield(data.trial, field) field = ['trial.' field]; elseif ~isfield(data, field) error('field "%s" not present in data', field); end if strncmp(field, 'avg.', 4) prefix = ''; field = field(5:end); % strip the avg data.(field) = data.avg.(field); % copy the avg into the main structure data = rmfield(data, 'avg'); elseif strncmp(field, 'trial.', 6) prefix = '(rpt)_'; field = field(7:end); % strip the trial data.(field) = data.trial(1).(field); % copy the first trial into the main structure data = rmfield(data, 'trial'); else prefix = ''; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 1: the specific dimord is simply present %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(data, [field 'dimord']) dimord = data.([field 'dimord']); return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if not present, we need some additional information about the data strucure %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nan means that the value is not known and might remain unknown % inf means that the value is not known but should be known ntime = inf; nfreq = inf; nchan = inf; nchancmb = inf; nsubj = nan; nrpt = nan; nrpttap = nan; npos = inf; nori = nan; % this will be 3 in many cases ntopochan = inf; nspike = inf; % this is only for the first spike channel nlag = nan; ndim1 = nan; ndim2 = nan; ndim3 = nan; % use an anonymous function assign = @(var, val) assignin('caller', var, val); % it is possible to pass additional ATTEMPTs such as nrpt, nrpttap, etc for i=1:2:length(varargin) assign(varargin{i}, varargin{i+1}); end % try to determine the size of each possible dimension in the data if isfield(data, 'label') nchan = length(data.label); end if isfield(data, 'labelcmb') nchancmb = size(data.labelcmb, 1); end if isfield(data, 'time') if iscell(data.time) && ~isempty(data.time) tmp = getdimsiz(data, 'time'); ntime = tmp(3); % raw data may contain variable length trials else ntime = length(data.time); end end if isfield(data, 'freq') nfreq = length(data.freq); end if isfield(data, 'trial') && ft_datatype(data, 'raw') nrpt = length(data.trial); end if isfield(data, 'trialtime') && ft_datatype(data, 'spike') nrpt = size(data.trialtime,1); end if isfield(data, 'cumtapcnt') nrpt = size(data.cumtapcnt,1); if numel(data.cumtapcnt)==length(data.cumtapcnt) % it is a vector, hence it only represents repetitions nrpttap = sum(data.cumtapcnt); else % it is a matrix, hence it is repetitions by frequencies % this happens after mtmconvol with keeptrials nrpttap = sum(data.cumtapcnt,2); if any(nrpttap~=nrpttap(1)) warning('unexpected variation of the number of tapers over trials') nrpttap = nan; else nrpttap = nrpttap(1); end end end if isfield(data, 'pos') npos = size(data.pos,1); elseif isfield(data, 'dim') npos = prod(data.dim); end if isfield(data, 'dim') ndim1 = data.dim(1); ndim2 = data.dim(2); ndim3 = data.dim(3); end if isfield(data, 'csdlabel') % this is used in PCC beamformers if length(data.csdlabel)==npos % each position has its own labels len = cellfun(@numel, data.csdlabel); len = len(len~=0); if all(len==len(1)) % they all have the same length nori = len(1); end else % one list of labels for all positions nori = length(data.csdlabel); end elseif isfinite(npos) % assume that there are three dipole orientations per source nori = 3; end if isfield(data, 'topolabel') % this is used in ICA and PCA decompositions ntopochan = length(data.topolabel); end if isfield(data, 'timestamp') && iscell(data.timestamp) nspike = length(data.timestamp{1}); % spike data: only for the first channel end if ft_datatype(data, 'mvar') && isfield(data, 'coeffs') nlag = size(data.coeffs,3); end % determine the size of the actual data datsiz = getdimsiz(data, field); tok = {'subj' 'rpt' 'rpttap' 'chan' 'chancmb' 'freq' 'time' 'pos' 'ori' 'topochan' 'lag' 'dim1' 'dim2' 'dim3'}; siz = [nsubj nrpt nrpttap nchan nchancmb nfreq ntime npos nori ntopochan nlag ndim1 ndim2 ndim3]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 2: a general dimord is present and might apply %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(data, 'dimord') dimtok = tokenize(data.dimord, '_'); if length(dimtok)>length(datsiz) && check_trailingdimsunitlength(data, dimtok((length(datsiz)+1):end)) % add the trailing singleton dimensions to datsiz, if needed datsiz = [datsiz ones(1,max(0,length(dimtok)-length(datsiz)))]; end if length(dimtok)==length(datsiz) || (length(dimtok)==(length(datsiz)-1) && datsiz(end)==1) success = false(size(dimtok)); for i=1:length(dimtok) sel = strcmp(tok, dimtok{i}); if any(sel) && datsiz(i)==siz(sel) success(i) = true; elseif strcmp(dimtok{i}, 'subj') % the number of subjects cannot be determined, and will be indicated as nan success(i) = true; elseif strcmp(dimtok{i}, 'rpt') % the number of trials is hard to determine, and might be indicated as nan success(i) = true; end end % for if all(success) dimord = data.dimord; return end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 3: look at the size of some common fields that are known %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch field % the logic for this code is to first check whether the size of a field % has an exact match to a potential dimensionality, if not, check for a % partial match (ignoring nans) % note that the case for a cell dimension (typically pos) is handled at % the end of this section case {'pos'} if isequalwithoutnans(datsiz, [npos 3]) dimord = 'pos_unknown'; end case {'individual'} if isequalwithoutnans(datsiz, [nsubj nchan ntime]) dimord = 'subj_chan_time'; end case {'avg' 'var' 'dof'} if isequal(datsiz, [nrpt nchan ntime]) dimord = 'rpt_chan_time'; elseif isequal(datsiz, [nchan ntime]) dimord = 'chan_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan ntime]) dimord = 'rpt_chan_time'; elseif isequalwithoutnans(datsiz, [nchan ntime]) dimord = 'chan_time'; end case {'powspctrm' 'fourierspctrm'} if isequal(datsiz, [nrpt nchan nfreq ntime]) dimord = 'rpt_chan_freq_time'; elseif isequal(datsiz, [nrpt nchan nfreq]) dimord = 'rpt_chan_freq'; elseif isequal(datsiz, [nchan nfreq ntime]) dimord = 'chan_freq_time'; elseif isequal(datsiz, [nchan nfreq]) dimord = 'chan_freq'; elseif isequalwithoutnans(datsiz, [nrpt nchan nfreq ntime]) dimord = 'rpt_chan_freq_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan nfreq]) dimord = 'rpt_chan_freq'; elseif isequalwithoutnans(datsiz, [nchan nfreq ntime]) dimord = 'chan_freq_time'; elseif isequalwithoutnans(datsiz, [nchan nfreq]) dimord = 'chan_freq'; end case {'crsspctrm' 'cohspctrm'} if isequal(datsiz, [nrpt nchancmb nfreq ntime]) dimord = 'rpt_chancmb_freq_time'; elseif isequal(datsiz, [nrpt nchancmb nfreq]) dimord = 'rpt_chancmb_freq'; elseif isequal(datsiz, [nchancmb nfreq ntime]) dimord = 'chancmb_freq_time'; elseif isequal(datsiz, [nchancmb nfreq]) dimord = 'chancmb_freq'; elseif isequal(datsiz, [nrpt nchan nchan nfreq ntime]) dimord = 'rpt_chan_chan_freq_time'; elseif isequal(datsiz, [nrpt nchan nchan nfreq]) dimord = 'rpt_chan_chan_freq'; elseif isequal(datsiz, [nchan nchan nfreq ntime]) dimord = 'chan_chan_freq_time'; elseif isequal(datsiz, [nchan nchan nfreq]) dimord = 'chan_chan_freq'; elseif isequal(datsiz, [npos nori]) dimord = 'pos_ori'; elseif isequal(datsiz, [npos 1]) dimord = 'pos'; elseif isequalwithoutnans(datsiz, [nrpt nchancmb nfreq ntime]) dimord = 'rpt_chancmb_freq_time'; elseif isequalwithoutnans(datsiz, [nrpt nchancmb nfreq]) dimord = 'rpt_chancmb_freq'; elseif isequalwithoutnans(datsiz, [nchancmb nfreq ntime]) dimord = 'chancmb_freq_time'; elseif isequalwithoutnans(datsiz, [nchancmb nfreq]) dimord = 'chancmb_freq'; elseif isequalwithoutnans(datsiz, [nrpt nchan nchan nfreq ntime]) dimord = 'rpt_chan_chan_freq_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan nchan nfreq]) dimord = 'rpt_chan_chan_freq'; elseif isequalwithoutnans(datsiz, [nchan nchan nfreq ntime]) dimord = 'chan_chan_freq_time'; elseif isequalwithoutnans(datsiz, [nchan nchan nfreq]) dimord = 'chan_chan_freq'; elseif isequalwithoutnans(datsiz, [npos nori]) dimord = 'pos_ori'; elseif isequalwithoutnans(datsiz, [npos 1]) dimord = 'pos'; end case {'cov' 'coh' 'csd' 'noisecov' 'noisecsd'} % these occur in timelock and in source structures if isequal(datsiz, [nrpt nchan nchan]) dimord = 'rpt_chan_chan'; elseif isequal(datsiz, [nchan nchan]) dimord = 'chan_chan'; elseif isequal(datsiz, [npos nori nori]) dimord = 'pos_ori_ori'; elseif isequal(datsiz, [npos nrpt nori nori]) dimord = 'pos_rpt_ori_ori'; elseif isequalwithoutnans(datsiz, [nrpt nchan nchan]) dimord = 'rpt_chan_chan'; elseif isequalwithoutnans(datsiz, [nchan nchan]) dimord = 'chan_chan'; elseif isequalwithoutnans(datsiz, [npos nori nori]) dimord = 'pos_ori_ori'; elseif isequalwithoutnans(datsiz, [npos nrpt nori nori]) dimord = 'pos_rpt_ori_ori'; end case {'tf'} if isequal(datsiz, [npos nfreq ntime]) dimord = 'pos_freq_time'; end case {'pow'} if isequal(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequal(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequal(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequal(datsiz, [nrpt npos ntime]) dimord = 'rpt_pos_time'; elseif isequal(datsiz, [nrpt npos nfreq]) dimord = 'rpt_pos_freq'; elseif isequal(datsiz, [npos 1]) % in case there are no repetitions dimord = 'pos'; elseif isequalwithoutnans(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequalwithoutnans(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequalwithoutnans(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequalwithoutnans(datsiz, [nrpt npos ntime]) dimord = 'rpt_pos_time'; elseif isequalwithoutnans(datsiz, [nrpt npos nfreq]) dimord = 'rpt_pos_freq'; end case {'mom','itc','aa','stat','pval','statitc','pitc'} if isequal(datsiz, [npos nori nrpt]) dimord = 'pos_ori_rpt'; elseif isequal(datsiz, [npos nori ntime]) dimord = 'pos_ori_time'; elseif isequal(datsiz, [npos nori nfreq]) dimord = 'pos_ori_nfreq'; elseif isequal(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequal(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequal(datsiz, [npos 3]) dimord = 'pos_ori'; elseif isequal(datsiz, [npos 1]) dimord = 'pos'; elseif isequal(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequalwithoutnans(datsiz, [npos nori nrpt]) dimord = 'pos_ori_rpt'; elseif isequalwithoutnans(datsiz, [npos nori ntime]) dimord = 'pos_ori_time'; elseif isequalwithoutnans(datsiz, [npos nori nfreq]) dimord = 'pos_ori_nfreq'; elseif isequalwithoutnans(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequalwithoutnans(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequalwithoutnans(datsiz, [npos 3]) dimord = 'pos_ori'; elseif isequalwithoutnans(datsiz, [npos 1]) dimord = 'pos'; elseif isequalwithoutnans(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequalwithoutnans(datsiz, [npos nrpt nori ntime]) dimord = 'pos_rpt_ori_time'; elseif isequalwithoutnans(datsiz, [npos nrpt 1 ntime]) dimord = 'pos_rpt_ori_time'; elseif isequal(datsiz, [npos nfreq ntime]) dimord = 'pos_freq_time'; end case {'filter'} if isequalwithoutnans(datsiz, [npos nori nchan]) || (isequal(datsiz([1 2]), [npos nori]) && isinf(nchan)) dimord = 'pos_ori_chan'; end case {'leadfield'} if isequalwithoutnans(datsiz, [npos nchan nori]) || (isequal(datsiz([1 3]), [npos nori]) && isinf(nchan)) dimord = 'pos_chan_ori'; end case {'ori' 'eta'} if isequal(datsiz, [npos nori]) || isequal(datsiz, [npos 3]) dimord = 'pos_ori'; end case {'csdlabel'} if isequal(datsiz, [npos nori]) || isequal(datsiz, [npos 3]) dimord = 'pos_ori'; end case {'trial'} if ~iscell(data.(field)) && isequalwithoutnans(datsiz, [nrpt nchan ntime]) dimord = 'rpt_chan_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan ntime]) dimord = '{rpt}_chan_time'; elseif isequalwithoutnans(datsiz, [nchan nspike]) || isequalwithoutnans(datsiz, [nchan 1 nspike]) dimord = '{chan}_spike'; end case {'sampleinfo' 'trialinfo' 'trialtime'} if isequalwithoutnans(datsiz, [nrpt nan]) dimord = 'rpt_other'; end case {'cumtapcnt' 'cumsumcnt'} if isequalwithoutnans(datsiz, [nrpt nan]) dimord = 'rpt_other'; end case {'topo'} if isequalwithoutnans(datsiz, [ntopochan nchan]) dimord = 'topochan_chan'; end case {'unmixing'} if isequalwithoutnans(datsiz, [nchan ntopochan]) dimord = 'chan_topochan'; end case {'inside'} if isequalwithoutnans(datsiz, [npos]) dimord = 'pos'; end case {'timestamp' 'time'} if ft_datatype(data, 'spike') && iscell(data.(field)) && datsiz(1)==nchan dimord = '{chan}_spike'; elseif ft_datatype(data, 'raw') && iscell(data.(field)) && datsiz(1)==nrpt dimord = '{rpt}_time'; elseif isvector(data.(field)) && isequal(datsiz, [1 ntime ones(1,numel(datsiz)-2)]) dimord = 'time'; end case {'freq'} if isvector(data.(field)) && isequal(datsiz, [1 nfreq]) dimord = 'freq'; end otherwise if isfield(data, 'dim') && isequal(datsiz, data.dim) dimord = 'dim1_dim2_dim3'; end end % switch field % deal with possible first pos which is a cell if exist('dimord', 'var') && strcmp(dimord(1:3), 'pos') && iscell(data.(field)) dimord = ['{pos}' dimord(4:end)]; end if ~exist('dimord', 'var') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 4: there is only one way that the dimensions can be interpreted %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% dimtok = cell(size(datsiz)); for i=1:length(datsiz) sel = find(siz==datsiz(i)); if length(sel)==1 % there is exactly one corresponding dimension dimtok{i} = tok{sel}; else % there are zero or multiple corresponding dimensions dimtok{i} = []; end end if all(~cellfun(@isempty, dimtok)) if iscell(data.(field)) dimtok{1} = ['{' dimtok{1} '}']; end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); return end end % if dimord does not exist if ~exist('dimord', 'var') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 5: compare the size with the known size of each dimension %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% sel = ~isnan(siz) & ~isinf(siz); % nan means that the value is not known and might remain unknown % inf means that the value is not known and but should be known if length(unique(siz(sel)))==length(siz(sel)) % this should only be done if there is no chance of confusing dimensions dimtok = cell(size(datsiz)); dimtok(datsiz==npos) = {'pos'}; dimtok(datsiz==nori) = {'ori'}; dimtok(datsiz==nrpttap) = {'rpttap'}; dimtok(datsiz==nrpt) = {'rpt'}; dimtok(datsiz==nsubj) = {'subj'}; dimtok(datsiz==nchancmb) = {'chancmb'}; dimtok(datsiz==nchan) = {'chan'}; dimtok(datsiz==nfreq) = {'freq'}; dimtok(datsiz==ntime) = {'time'}; dimtok(datsiz==ndim1) = {'dim1'}; dimtok(datsiz==ndim2) = {'dim2'}; dimtok(datsiz==ndim3) = {'dim3'}; if isempty(dimtok{end}) && datsiz(end)==1 % remove the unknown trailing singleton dimension dimtok = dimtok(1:end-1); elseif isequal(dimtok{1}, 'pos') && isempty(dimtok{2}) && datsiz(2)==1 % remove the unknown leading singleton dimension dimtok(2) = []; end if all(~cellfun(@isempty, dimtok)) if iscell(data.(field)) dimtok{1} = ['{' dimtok{1} '}']; end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); return end end end % if dimord does not exist if ~exist('dimord', 'var') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 6: check whether it is a 3-D volume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isequal(datsiz, [ndim1 ndim2 ndim3]) dimord = 'dim1_dim2_dim3'; end end % if dimord does not exist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % FINAL RESORT: return "unknown" for all unknown dimensions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist('dimord', 'var') % this should not happen % if it does, it might help in diagnosis to have a very informative warning message % since there have been problems with trials not being selected correctly due to the warning going unnoticed % it is better to throw an error than a warning warning('could not determine dimord of "%s" in the following data', field) disp(data); dimtok(cellfun(@isempty, dimtok)) = {'unknown'}; if all(~cellfun(@isempty, dimtok)) if iscell(data.(field)) dimtok{1} = ['{' dimtok{1} '}']; end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); end end % add '(rpt)' in case of source.trial dimord = [prefix dimord]; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ok = isequalwithoutnans(a, b) % this is *only* used to compare matrix sizes, so we can ignore any singleton last dimension numdiff = numel(b)-numel(a); if numdiff > 0 % assume singleton dimensions missing in a a = [a(:); ones(numdiff, 1)]; b = b(:); elseif numdiff < 0 % assume singleton dimensions missing in b b = [b(:); ones(abs(numdiff), 1)]; a = a(:); end c = ~isnan(a(:)) & ~isnan(b(:)); ok = isequal(a(c), b(c)); end % function isequalwithoutnans %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ok = check_trailingdimsunitlength(data, dimtok) ok = false; for k = 1:numel(dimtok) switch dimtok{k} case 'chan' ok = numel(data.label)==1; otherwise if isfield(data, dimtok{k}); % check whether field exists ok = numel(data.(dimtok{k}))==1; end; end if ok, break; end end end % function check_trailingdimsunitlength
github
lcnbeapp/beapp-master
freezeColors.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/nutmegtrip/private/freezeColors.m
9,815
utf_8
2068d7a4f7a74d251e2519c4c5c1c171
function freezeColors(varargin) % freezeColors Lock colors of plot, enabling multiple colormaps per figure. (v2.3) % % Problem: There is only one colormap per figure. This function provides % an easy solution when plots using different colomaps are desired % in the same figure. % % freezeColors freezes the colors of graphics objects in the current axis so % that subsequent changes to the colormap (or caxis) will not change the % colors of these objects. freezeColors works on any graphics object % with CData in indexed-color mode: surfaces, images, scattergroups, % bargroups, patches, etc. It works by converting CData to true-color rgb % based on the colormap active at the time freezeColors is called. % % The original indexed color data is saved, and can be restored using % unfreezeColors, making the plot once again subject to the colormap and % caxis. % % % Usage: % freezeColors applies to all objects in current axis (gca), % freezeColors(axh) same, but works on axis axh. % % Example: % subplot(2,1,1); imagesc(X); colormap hot; freezeColors % subplot(2,1,2); imagesc(Y); colormap hsv; freezeColors etc... % % Note: colorbars must also be frozen. Due to Matlab 'improvements' this can % no longer be done with freezeColors. Instead, please % use the function CBFREEZE by Carlos Adrian Vargas Aguilera % that can be downloaded from the MATLAB File Exchange % (http://www.mathworks.com/matlabcentral/fileexchange/24371) % % h=colorbar; cbfreeze(h), or simply cbfreeze(colorbar) % % For additional examples, see test/test_main.m % % Side effect on render mode: freezeColors does not work with the painters % renderer, because Matlab doesn't support rgb color data in % painters mode. If the current renderer is painters, freezeColors % changes it to zbuffer. This may have unexpected effects on other aspects % of your plots. % % See also unfreezeColors, freezeColors_pub.html, cbfreeze. % % % John Iversen ([email protected]) 3/23/05 % % Changes: % JRI ([email protected]) 4/19/06 Correctly handles scaled integer cdata % JRI 9/1/06 should now handle all objects with cdata: images, surfaces, % scatterplots. (v 2.1) % JRI 11/11/06 Preserves NaN colors. Hidden option (v 2.2, not uploaded) % JRI 3/17/07 Preserve caxis after freezing--maintains colorbar scale (v 2.3) % JRI 4/12/07 Check for painters mode as Matlab doesn't support rgb in it. % JRI 4/9/08 Fix preserving caxis for objects within hggroups (e.g. contourf) % JRI 4/7/10 Change documentation for colorbars % Hidden option for NaN colors: % Missing data are often represented by NaN in the indexed color % data, which renders transparently. This transparency will be preserved % when freezing colors. If instead you wish such gaps to be filled with % a real color, add 'nancolor',[r g b] to the end of the arguments. E.g. % freezeColors('nancolor',[r g b]) or freezeColors(axh,'nancolor',[r g b]), % where [r g b] is a color vector. This works on images & pcolor, but not on % surfaces. % Thanks to Fabiano Busdraghi and Jody Klymak for the suggestions. Bugfixes % attributed in the code. % Free for all uses, but please retain the following: % Original Author: % John Iversen, 2005-10 % [email protected] appdatacode = 'JRI__freezeColorsData'; [h, nancolor] = checkArgs(varargin); %gather all children with scaled or indexed CData cdatah = getCDataHandles(h); %current colormap cmap = colormap; nColors = size(cmap,1); cax = caxis; % convert object color indexes into colormap to true-color data using % current colormap for hh = cdatah', g = get(hh); %preserve parent axis clim parentAx = getParentAxes(hh); originalClim = get(parentAx, 'clim'); % Note: Special handling of patches: For some reason, setting % cdata on patches created by bar() yields an error, % so instead we'll set facevertexcdata instead for patches. if ~strcmp(g.Type,'patch'), cdata = g.CData; else cdata = g.FaceVertexCData; end %get cdata mapping (most objects (except scattergroup) have it) if isfield(g,'CDataMapping'), scalemode = g.CDataMapping; else scalemode = 'scaled'; end %save original indexed data for use with unfreezeColors siz = size(cdata); setappdata(hh, appdatacode, {cdata scalemode}); %convert cdata to indexes into colormap if strcmp(scalemode,'scaled'), %4/19/06 JRI, Accommodate scaled display of integer cdata: % in MATLAB, uint * double = uint, so must coerce cdata to double % Thanks to O Yamashita for pointing this need out idx = ceil( (double(cdata) - cax(1)) / (cax(2)-cax(1)) * nColors); else %direct mapping idx = cdata; %10/8/09 in case direct data is non-int (e.g. image;freezeColors) % (Floor mimics how matlab converts data into colormap index.) % Thanks to D Armyr for the catch idx = floor(idx); end %clamp to [1, nColors] idx(idx<1) = 1; idx(idx>nColors) = nColors; %handle nans in idx nanmask = isnan(idx); idx(nanmask)=1; %temporarily replace w/ a valid colormap index %make true-color data--using current colormap realcolor = zeros(siz); for i = 1:3, c = cmap(idx,i); c = reshape(c,siz); c(nanmask) = nancolor(i); %restore Nan (or nancolor if specified) realcolor(:,:,i) = c; end %apply new true-color color data %true-color is not supported in painters renderer, so switch out of that if strcmp(get(gcf,'renderer'), 'painters'), set(gcf,'renderer','zbuffer'); end %replace original CData with true-color data if ~strcmp(g.Type,'patch'), set(hh,'CData',realcolor); else set(hh,'faceVertexCData',permute(realcolor,[1 3 2])) end %restore clim (so colorbar will show correct limits) if ~isempty(parentAx), set(parentAx,'clim',originalClim) end end %loop on indexed-color objects % ============================================================================ % % Local functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% getCDataHandles -- get handles of all descendents with indexed CData %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hout = getCDataHandles(h) % getCDataHandles Find all objects with indexed CData %recursively descend object tree, finding objects with indexed CData % An exception: don't include children of objects that themselves have CData: % for example, scattergroups are non-standard hggroups, with CData. Changing % such a group's CData automatically changes the CData of its children, % (as well as the children's handles), so there's no need to act on them. error(nargchk(1,1,nargin,'struct')) hout = []; if isempty(h),return;end ch = get(h,'children'); for hh = ch' g = get(hh); if isfield(g,'CData'), %does object have CData? %is it indexed/scaled? if ~isempty(g.CData) && isnumeric(g.CData) && size(g.CData,3)==1, hout = [hout; hh]; %#ok<AGROW> %yes, add to list end else %no CData, see if object has any interesting children hout = [hout; getCDataHandles(hh)]; %#ok<AGROW> end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% getParentAxes -- return handle of axes object to which a given object belongs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hAx = getParentAxes(h) % getParentAxes Return enclosing axes of a given object (could be self) error(nargchk(1,1,nargin,'struct')) %object itself may be an axis if strcmp(get(h,'type'),'axes'), hAx = h; return end parent = get(h,'parent'); if (strcmp(get(parent,'type'), 'axes')), hAx = parent; else hAx = getParentAxes(parent); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% checkArgs -- Validate input arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [h, nancolor] = checkArgs(args) % checkArgs Validate input arguments to freezeColors nargs = length(args); error(nargchk(0,3,nargs,'struct')) %grab handle from first argument if we have an odd number of arguments if mod(nargs,2), h = args{1}; if ~ishandle(h), error('JRI:freezeColors:checkArgs:invalidHandle',... 'The first argument must be a valid graphics handle (to an axis)') end % 4/2010 check if object to be frozen is a colorbar if strcmp(get(h,'Tag'),'Colorbar'), if ~exist('cbfreeze.m'), warning('JRI:freezeColors:checkArgs:cannotFreezeColorbar',... ['You seem to be attempting to freeze a colorbar. This no longer'... 'works. Please read the help for freezeColors for the solution.']) else cbfreeze(h); return end end args{1} = []; nargs = nargs-1; else h = gca; end %set nancolor if that option was specified nancolor = [nan nan nan]; if nargs == 2, if strcmpi(args{end-1},'nancolor'), nancolor = args{end}; if ~all(size(nancolor)==[1 3]), error('JRI:freezeColors:checkArgs:badColorArgument',... 'nancolor must be [r g b] vector'); end nancolor(nancolor>1) = 1; nancolor(nancolor<0) = 0; else error('JRI:freezeColors:checkArgs:unrecognizedOption',... 'Unrecognized option (%s). Only ''nancolor'' is valid.',args{end-1}) end end
github
lcnbeapp/beapp-master
nmt_update_panel.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/nutmegtrip/private/nmt_update_panel.m
7,882
utf_8
6d1fc15425b5436887f56bbc1fd41370
function nmt_update_panel(axsel) global st %% update time series, if applicable if(isfield(st.nmt,'time')) %& ~isfield(st.nmt,'freq')) set(st.nmt.gui.timeguih,'Visible','On'); % ensure plot is visible switch(st.nmt.cfg.plottype) case 'tf' clim = max(abs(st.nmt.fun{axsel}(:))) * [-1 1]; set(st.nmt.gui.freqguih,'Visible','On'); % ensure plot is visible if(all(st.nmt.freq(1,:) == [0 0])) % if the first row contains evoked data st.nmt.gui.h_tf = nmt_tfplot(st.nmt.gui.ax_ts(axsel),st.nmt.time,st.nmt.freq(2:end,:),squeeze(st.nmt.fun{axsel}(st.nmt.cfg.vox_idx,:,2:end)),clim,@nmt_repos_start); else st.nmt.gui.h_tf = nmt_tfplot(st.nmt.gui.ax_ts(axsel),st.nmt.time,st.nmt.freq,squeeze(st.nmt.fun{axsel}(st.nmt.cfg.vox_idx,:,:)),clim,@nmt_repos_start); end case 'ts' if(isfinite(st.nmt.cfg.vox_idx)) plot(st.nmt.gui.ax_ts(axsel),st.nmt.time,squeeze(st.nmt.fun{axsel}(st.nmt.cfg.vox_idx,:,:))); grid(st.nmt.gui.ax_ts(axsel),'on'); else plot(st.nmt.gui.ax_ts(axsel),st.nmt.time,nan(length(st.nmt.time),1)); end % set y-axis range based on whole volume range (single time point), or % selected timeslice range if(st.nmt.cfg.time_idx(1)==st.nmt.cfg.time_idx(2)) ymin = min(st.nmt.fun{axsel}(:)); ymax = max(st.nmt.fun{axsel}(:)); else ymin = min(min(st.nmt.fun{axsel}(:,st.nmt.cfg.time_idx(1):st.nmt.cfg.time_idx(2)))); ymax = max(max(st.nmt.fun{axsel}(:,st.nmt.cfg.time_idx(1):st.nmt.cfg.time_idx(2)))); end set(st.nmt.gui.ax_ts(axsel),'YLim',[ymin ymax]); end set(st.nmt.gui.ax_ts(axsel),'XLim',st.nmt.time([1 end])); xlabel(st.nmt.gui.ax_ts(axsel),['Time (s)']); %% plot vertical line indicating selected time point switch(st.nmt.cfg.plottype) case 'ts' ylim=get(st.nmt.gui.ax_ts(axsel),'YLim'); case 'tf' ylim = [st.nmt.freq(st.nmt.cfg.freq_idx(1),1) st.nmt.freq(st.nmt.cfg.freq_idx(2),2)]; end axes(st.nmt.gui.ax_ts(axsel)); zlim = get(st.nmt.gui.ax_ts(axsel),'ZLim'); % selection patch needs to have a Z higher than the TF range so that it's not hidden by the TF plot h=patch([st.nmt.time(st.nmt.cfg.time_idx(1)) st.nmt.time(st.nmt.cfg.time_idx(2)) st.nmt.time(st.nmt.cfg.time_idx(2)) st.nmt.time(st.nmt.cfg.time_idx(1))]',[ylim(1) ylim(1) ylim(2) ylim(2)]',[zlim(2) zlim(2) zlim(2) zlim(2)],[1 0.4 0.4],'EdgeColor','red'); set(st.nmt.gui.ax_ts(axsel),'ButtonDownFcn',@nmt_repos_start); switch('disabled') % TODO: hook for overlaying time series on TF plot; % perhaps better solution is independent nmt_spm_plot call for each funparameter case 'tf' if(st.nmt.cfg.evokedoverlay) % trick to overlay time series taken from plotyy.m ylim=get(st.nmt.gui.ax_ts(axsel,2),'YLim'); ts=squeeze(st.nmt.fun{axsel}(st.nmt.cfg.vox_idx,:,1)); axes(st.nmt.gui.ax_ts(axsel,2)); plot(st.nmt.gui.ax_ts(axsel,2),st.nmt.time,ts); set(st.nmt.gui.ax_ts(axsel,2),'YAxisLocation','right','Color','none', ... 'XGrid','off','YGrid','off','Box','off', ... 'HitTest','off','Visible','on'); end end %% update GUI textboxes set(st.nmt.gui.t1,'String',num2str(st.nmt.time(st.nmt.cfg.time_idx(1)))); set(st.nmt.gui.t2,'String',num2str(st.nmt.time(st.nmt.cfg.time_idx(2)))); if(1) set(st.nmt.gui.f1,'Value',st.nmt.cfg.freq_idx(1)); set(st.nmt.gui.f2,'Value',st.nmt.cfg.freq_idx(2)); else set(st.nmt.gui.f1,'String',num2str(st.nmt.freq(st.nmt.cfg.freq_idx(1),1))); set(st.nmt.gui.f2,'String',num2str(st.nmt.freq(st.nmt.cfg.freq_idx(2),2))); end %% optionally add topoplot switch(st.nmt.cfg.topoplot) case 'timelock' cfgplot.xlim = st.nmt.time(st.nmt.cfg.time_idx); cfgplot.zlim = 'maxabs'; nmt_addtopo(cfgplot,st.nmt.timelock); case {'spatialfilter','leadfield','leadfieldX','leadfieldY','leadfieldZ','leadfieldori'} % FIXME: this isn't so elegant :-) % currently steals some information from timelock structure topo.label = st.nmt.timelock.label; topo.grad = st.nmt.timelock.grad; topo.dimord = 'chan_time'; topo.time = [0 1 2 3]; % not really time, but selection of magnitude or x/y/z components switch(cfg.topoplot) case 'spatialfilter' topo.time = 0; % fake time (take vector norm) cfgplot.xlim = [topo.time topo.time]; cfgplot.zlim = 'maxabs'; topo.avg = st.nmt.spatialfilter{st.nmt.cfg.vox_idx}'; case {'leadfield','leadfieldX','leadfieldY','leadfieldZ'} switch(cfg.topoplot) case 'leadfield' topo.time = 0; % fake time (take vector norm) topo.avg = nut_rownorm(st.nmt.grid.leadfield{st.nmt.cfg.vox_idx}); % TODO: remove dependency on nut_rownorm (from NUTMEG) case 'leadfieldX' topo.time = 1; topo.avg = st.nmt.grid.leadfield{st.nmt.cfg.vox_idx}; case 'leadfieldY' topo.time = 2; topo.avg = st.nmt.grid.leadfield{st.nmt.cfg.vox_idx}; case 'leadfieldZ' topo.time = 3; topo.avg = st.nmt.grid.leadfield{st.nmt.cfg.vox_idx}; end cfgplot.xlim = [topo.time topo.time]; cfgplot.zlim = 'maxabs'; % case 'leadfieldX' % topo.time = 1; % fake time (corresponds to x-orientation) % cfgplot.xlim = [topo.time topo.time]; % cfgplot.zlim = 'maxabs'; % topo.avg = st.nmt.grid.leadfield{st.nmt.cfg.vox_idx}; % case 'leadfieldY' % topo.time = 2; % fake time (corresponds to y-orientation) % cfgplot.xlim = [topo.time topo.time]; % cfgplot.zlim = 'maxabs'; % topo.avg = st.nmt.grid.leadfield{st.nmt.cfg.vox_idx}; % case 'leadfieldZ' % topo.time = 3; % fake time (corresponds to z-orientation) % cfgplot.xlim = [topo.time topo.time]; % cfgplot.zlim = 'maxabs'; % topo.avg = nut_rownorm(st.nmt.grid.leadfield{st.nmt.cfg.vox_idx}); % case 'leadfieldori' % error('TODO: not yet implemented'); end nmt_addtopo(cfgplot,topo); case {'no',''} % do nothing otherwise error('requested cfg.topoplot parameter is not supported.'); end end function nmt_repos_start(varargin) global st set(gcbf,'windowbuttonmotionfcn',@nmt_repos_move, 'windowbuttonupfcn',@nmt_repos_end); nmt_timeselect('ts'); %_______________________________________________________________________ %_______________________________________________________________________ function nmt_repos_move(varargin) nmt_timeselect('ts'); %_______________________________________________________________________ %_______________________________________________________________________ function nmt_repos_end(varargin) set(gcbf,'windowbuttonmotionfcn','', 'windowbuttonupfcn','');
github
lcnbeapp/beapp-master
getdimsiz.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/contrib/nutmegtrip/private/getdimsiz.m
2,235
utf_8
340d495a654f2f6752aa1af7ac915390
function dimsiz = getdimsiz(data, field) % GETDIMSIZ % % Use as % dimsiz = getdimsiz(data, field) % % If the length of the vector that is returned is smaller than the % number of dimensions that you would expect from GETDIMORD, you % should assume that it has trailing singleton dimensions. % % Example use % dimord = getdimord(datastructure, fieldname); % dimtok = tokenize(dimord, '_'); % dimsiz = getdimsiz(datastructure, fieldname); % dimsiz(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions % % See also GETDIMORD, GETDATFIELD if ~isfield(data, field) && isfield(data, 'avg') && isfield(data.avg, field) field = ['avg.' field]; elseif ~isfield(data, field) && isfield(data, 'trial') && isfield(data.trial, field) field = ['trial.' field]; elseif ~isfield(data, field) error('field "%s" not present in data', field); end if strncmp(field, 'avg.', 4) prefix = []; field = field(5:end); % strip the avg data.(field) = data.avg.(field); % move the avg into the main structure data = rmfield(data, 'avg'); elseif strncmp(field, 'trial.', 6) prefix = numel(data.trial); field = field(7:end); % strip the trial data.(field) = data.trial(1).(field); % move the first trial into the main structure data = rmfield(data, 'trial'); else prefix = []; end dimsiz = cellmatsize(data.(field)); % add nrpt in case of source.trial dimsiz = [prefix dimsiz]; end % main function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to determine the size of data representations like {pos}_ori_time % FIXME this will fail for {xxx_yyy}_zzz %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function siz = cellmatsize(x) if iscell(x) if isempty(x) siz = 0; return % nothing else to do elseif isvector(x) cellsize = numel(x); % the number of elements in the cell-array else cellsize = size(x); x = x(:); % convert to vector for further size detection end [dum, indx] = max(cellfun(@numel, x)); matsize = size(x{indx}); % the size of the content of the cell-array siz = [cellsize matsize]; % concatenate the two else siz = size(x); end end % function cellmatsize
github
lcnbeapp/beapp-master
getdimord.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/getdimord.m
20,107
utf_8
706f4f45a5d4ae7535c204b8c010f76b
function dimord = getdimord(data, field, varargin) % GETDIMORD % % Use as % dimord = getdimord(data, field) % % See also GETDIMSIZ, GETDATFIELD if ~isfield(data, field) && isfield(data, 'avg') && isfield(data.avg, field) field = ['avg.' field]; elseif ~isfield(data, field) && isfield(data, 'trial') && isfield(data.trial, field) field = ['trial.' field]; elseif ~isfield(data, field) error('field "%s" not present in data', field); end if strncmp(field, 'avg.', 4) prefix = ''; field = field(5:end); % strip the avg data.(field) = data.avg.(field); % copy the avg into the main structure data = rmfield(data, 'avg'); elseif strncmp(field, 'trial.', 6) prefix = '(rpt)_'; field = field(7:end); % strip the trial data.(field) = data.trial(1).(field); % copy the first trial into the main structure data = rmfield(data, 'trial'); else prefix = ''; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 1: the specific dimord is simply present %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(data, [field 'dimord']) dimord = data.([field 'dimord']); return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if not present, we need some additional information about the data strucure %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nan means that the value is not known and might remain unknown % inf means that the value is not known but should be known ntime = inf; nfreq = inf; nchan = inf; nchancmb = inf; nsubj = nan; nrpt = nan; nrpttap = nan; npos = inf; nori = nan; % this will be 3 in many cases ntopochan = inf; nspike = inf; % this is only for the first spike channel nlag = nan; ndim1 = nan; ndim2 = nan; ndim3 = nan; % use an anonymous function assign = @(var, val) assignin('caller', var, val); % it is possible to pass additional ATTEMPTs such as nrpt, nrpttap, etc for i=1:2:length(varargin) assign(varargin{i}, varargin{i+1}); end % try to determine the size of each possible dimension in the data if isfield(data, 'label') nchan = length(data.label); end if isfield(data, 'labelcmb') nchancmb = size(data.labelcmb, 1); end if isfield(data, 'time') if iscell(data.time) && ~isempty(data.time) tmp = getdimsiz(data, 'time'); ntime = tmp(3); % raw data may contain variable length trials else ntime = length(data.time); end end if isfield(data, 'freq') nfreq = length(data.freq); end if isfield(data, 'trial') && ft_datatype(data, 'raw') nrpt = length(data.trial); end if isfield(data, 'trialtime') && ft_datatype(data, 'spike') nrpt = size(data.trialtime,1); end if isfield(data, 'cumtapcnt') nrpt = size(data.cumtapcnt,1); if numel(data.cumtapcnt)==length(data.cumtapcnt) % it is a vector, hence it only represents repetitions nrpttap = sum(data.cumtapcnt); else % it is a matrix, hence it is repetitions by frequencies % this happens after mtmconvol with keeptrials nrpttap = sum(data.cumtapcnt,2); if any(nrpttap~=nrpttap(1)) warning('unexpected variation of the number of tapers over trials') nrpttap = nan; else nrpttap = nrpttap(1); end end end if isfield(data, 'pos') npos = size(data.pos,1); elseif isfield(data, 'dim') npos = prod(data.dim); end if isfield(data, 'dim') ndim1 = data.dim(1); ndim2 = data.dim(2); ndim3 = data.dim(3); end if isfield(data, 'csdlabel') % this is used in PCC beamformers if length(data.csdlabel)==npos % each position has its own labels len = cellfun(@numel, data.csdlabel); len = len(len~=0); if all(len==len(1)) % they all have the same length nori = len(1); end else % one list of labels for all positions nori = length(data.csdlabel); end elseif isfinite(npos) % assume that there are three dipole orientations per source nori = 3; end if isfield(data, 'topolabel') % this is used in ICA and PCA decompositions ntopochan = length(data.topolabel); end if isfield(data, 'timestamp') && iscell(data.timestamp) nspike = length(data.timestamp{1}); % spike data: only for the first channel end if ft_datatype(data, 'mvar') && isfield(data, 'coeffs') nlag = size(data.coeffs,3); end % determine the size of the actual data datsiz = getdimsiz(data, field); tok = {'subj' 'rpt' 'rpttap' 'chan' 'chancmb' 'freq' 'time' 'pos' 'ori' 'topochan' 'lag' 'dim1' 'dim2' 'dim3'}; siz = [nsubj nrpt nrpttap nchan nchancmb nfreq ntime npos nori ntopochan nlag ndim1 ndim2 ndim3]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 2: a general dimord is present and might apply %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(data, 'dimord') dimtok = tokenize(data.dimord, '_'); if length(dimtok)>length(datsiz) && check_trailingdimsunitlength(data, dimtok((length(datsiz)+1):end)) % add the trailing singleton dimensions to datsiz, if needed datsiz = [datsiz ones(1,max(0,length(dimtok)-length(datsiz)))]; end if length(dimtok)==length(datsiz) || (length(dimtok)==(length(datsiz)-1) && datsiz(end)==1) success = false(size(dimtok)); for i=1:length(dimtok) sel = strcmp(tok, dimtok{i}); if any(sel) && datsiz(i)==siz(sel) success(i) = true; elseif strcmp(dimtok{i}, 'subj') % the number of subjects cannot be determined, and will be indicated as nan success(i) = true; elseif strcmp(dimtok{i}, 'rpt') % the number of trials is hard to determine, and might be indicated as nan success(i) = true; end end % for if all(success) dimord = data.dimord; return end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 3: look at the size of some common fields that are known %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch field % the logic for this code is to first check whether the size of a field % has an exact match to a potential dimensionality, if not, check for a % partial match (ignoring nans) % note that the case for a cell dimension (typically pos) is handled at % the end of this section case {'pos'} if isequalwithoutnans(datsiz, [npos 3]) dimord = 'pos_unknown'; end case {'individual'} if isequalwithoutnans(datsiz, [nsubj nchan ntime]) dimord = 'subj_chan_time'; end case {'avg' 'var' 'dof'} if isequal(datsiz, [nrpt nchan ntime]) dimord = 'rpt_chan_time'; elseif isequal(datsiz, [nchan ntime]) dimord = 'chan_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan ntime]) dimord = 'rpt_chan_time'; elseif isequalwithoutnans(datsiz, [nchan ntime]) dimord = 'chan_time'; end case {'powspctrm' 'fourierspctrm'} if isequal(datsiz, [nrpt nchan nfreq ntime]) dimord = 'rpt_chan_freq_time'; elseif isequal(datsiz, [nrpt nchan nfreq]) dimord = 'rpt_chan_freq'; elseif isequal(datsiz, [nchan nfreq ntime]) dimord = 'chan_freq_time'; elseif isequal(datsiz, [nchan nfreq]) dimord = 'chan_freq'; elseif isequalwithoutnans(datsiz, [nrpt nchan nfreq ntime]) dimord = 'rpt_chan_freq_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan nfreq]) dimord = 'rpt_chan_freq'; elseif isequalwithoutnans(datsiz, [nchan nfreq ntime]) dimord = 'chan_freq_time'; elseif isequalwithoutnans(datsiz, [nchan nfreq]) dimord = 'chan_freq'; end case {'crsspctrm' 'cohspctrm'} if isequal(datsiz, [nrpt nchancmb nfreq ntime]) dimord = 'rpt_chancmb_freq_time'; elseif isequal(datsiz, [nrpt nchancmb nfreq]) dimord = 'rpt_chancmb_freq'; elseif isequal(datsiz, [nchancmb nfreq ntime]) dimord = 'chancmb_freq_time'; elseif isequal(datsiz, [nchancmb nfreq]) dimord = 'chancmb_freq'; elseif isequal(datsiz, [nrpt nchan nchan nfreq ntime]) dimord = 'rpt_chan_chan_freq_time'; elseif isequal(datsiz, [nrpt nchan nchan nfreq]) dimord = 'rpt_chan_chan_freq'; elseif isequal(datsiz, [nchan nchan nfreq ntime]) dimord = 'chan_chan_freq_time'; elseif isequal(datsiz, [nchan nchan nfreq]) dimord = 'chan_chan_freq'; elseif isequal(datsiz, [npos nori]) dimord = 'pos_ori'; elseif isequal(datsiz, [npos 1]) dimord = 'pos'; elseif isequalwithoutnans(datsiz, [nrpt nchancmb nfreq ntime]) dimord = 'rpt_chancmb_freq_time'; elseif isequalwithoutnans(datsiz, [nrpt nchancmb nfreq]) dimord = 'rpt_chancmb_freq'; elseif isequalwithoutnans(datsiz, [nchancmb nfreq ntime]) dimord = 'chancmb_freq_time'; elseif isequalwithoutnans(datsiz, [nchancmb nfreq]) dimord = 'chancmb_freq'; elseif isequalwithoutnans(datsiz, [nrpt nchan nchan nfreq ntime]) dimord = 'rpt_chan_chan_freq_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan nchan nfreq]) dimord = 'rpt_chan_chan_freq'; elseif isequalwithoutnans(datsiz, [nchan nchan nfreq ntime]) dimord = 'chan_chan_freq_time'; elseif isequalwithoutnans(datsiz, [nchan nchan nfreq]) dimord = 'chan_chan_freq'; elseif isequalwithoutnans(datsiz, [npos nori]) dimord = 'pos_ori'; elseif isequalwithoutnans(datsiz, [npos 1]) dimord = 'pos'; end case {'cov' 'coh' 'csd' 'noisecov' 'noisecsd'} % these occur in timelock and in source structures if isequal(datsiz, [nrpt nchan nchan]) dimord = 'rpt_chan_chan'; elseif isequal(datsiz, [nchan nchan]) dimord = 'chan_chan'; elseif isequal(datsiz, [npos nori nori]) dimord = 'pos_ori_ori'; elseif isequal(datsiz, [npos nrpt nori nori]) dimord = 'pos_rpt_ori_ori'; elseif isequalwithoutnans(datsiz, [nrpt nchan nchan]) dimord = 'rpt_chan_chan'; elseif isequalwithoutnans(datsiz, [nchan nchan]) dimord = 'chan_chan'; elseif isequalwithoutnans(datsiz, [npos nori nori]) dimord = 'pos_ori_ori'; elseif isequalwithoutnans(datsiz, [npos nrpt nori nori]) dimord = 'pos_rpt_ori_ori'; end case {'tf'} if isequal(datsiz, [npos nfreq ntime]) dimord = 'pos_freq_time'; end case {'pow'} if isequal(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequal(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequal(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequal(datsiz, [nrpt npos ntime]) dimord = 'rpt_pos_time'; elseif isequal(datsiz, [nrpt npos nfreq]) dimord = 'rpt_pos_freq'; elseif isequal(datsiz, [npos 1]) % in case there are no repetitions dimord = 'pos'; elseif isequalwithoutnans(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequalwithoutnans(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequalwithoutnans(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequalwithoutnans(datsiz, [nrpt npos ntime]) dimord = 'rpt_pos_time'; elseif isequalwithoutnans(datsiz, [nrpt npos nfreq]) dimord = 'rpt_pos_freq'; end case {'mom','itc','aa','stat','pval','statitc','pitc'} if isequal(datsiz, [npos nori nrpt]) dimord = 'pos_ori_rpt'; elseif isequal(datsiz, [npos nori ntime]) dimord = 'pos_ori_time'; elseif isequal(datsiz, [npos nori nfreq]) dimord = 'pos_ori_nfreq'; elseif isequal(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequal(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequal(datsiz, [npos 3]) dimord = 'pos_ori'; elseif isequal(datsiz, [npos 1]) dimord = 'pos'; elseif isequal(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequalwithoutnans(datsiz, [npos nori nrpt]) dimord = 'pos_ori_rpt'; elseif isequalwithoutnans(datsiz, [npos nori ntime]) dimord = 'pos_ori_time'; elseif isequalwithoutnans(datsiz, [npos nori nfreq]) dimord = 'pos_ori_nfreq'; elseif isequalwithoutnans(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequalwithoutnans(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequalwithoutnans(datsiz, [npos 3]) dimord = 'pos_ori'; elseif isequalwithoutnans(datsiz, [npos 1]) dimord = 'pos'; elseif isequalwithoutnans(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequalwithoutnans(datsiz, [npos nrpt nori ntime]) dimord = 'pos_rpt_ori_time'; elseif isequalwithoutnans(datsiz, [npos nrpt 1 ntime]) dimord = 'pos_rpt_ori_time'; elseif isequal(datsiz, [npos nfreq ntime]) dimord = 'pos_freq_time'; end case {'filter'} if isequalwithoutnans(datsiz, [npos nori nchan]) || (isequal(datsiz([1 2]), [npos nori]) && isinf(nchan)) dimord = 'pos_ori_chan'; end case {'leadfield'} if isequalwithoutnans(datsiz, [npos nchan nori]) || (isequal(datsiz([1 3]), [npos nori]) && isinf(nchan)) dimord = 'pos_chan_ori'; end case {'ori' 'eta'} if isequal(datsiz, [npos nori]) || isequal(datsiz, [npos 3]) dimord = 'pos_ori'; end case {'csdlabel'} if isequal(datsiz, [npos nori]) || isequal(datsiz, [npos 3]) dimord = 'pos_ori'; end case {'trial'} if ~iscell(data.(field)) && isequalwithoutnans(datsiz, [nrpt nchan ntime]) dimord = 'rpt_chan_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan ntime]) dimord = '{rpt}_chan_time'; elseif isequalwithoutnans(datsiz, [nchan nspike]) || isequalwithoutnans(datsiz, [nchan 1 nspike]) dimord = '{chan}_spike'; end case {'sampleinfo' 'trialinfo' 'trialtime'} if isequalwithoutnans(datsiz, [nrpt nan]) dimord = 'rpt_other'; end case {'cumtapcnt' 'cumsumcnt'} if isequalwithoutnans(datsiz, [nrpt nan]) dimord = 'rpt_other'; end case {'topo'} if isequalwithoutnans(datsiz, [ntopochan nchan]) dimord = 'topochan_chan'; end case {'unmixing'} if isequalwithoutnans(datsiz, [nchan ntopochan]) dimord = 'chan_topochan'; end case {'inside'} if isequalwithoutnans(datsiz, [npos]) dimord = 'pos'; end case {'timestamp' 'time'} if ft_datatype(data, 'spike') && iscell(data.(field)) && datsiz(1)==nchan dimord = '{chan}_spike'; elseif ft_datatype(data, 'raw') && iscell(data.(field)) && datsiz(1)==nrpt dimord = '{rpt}_time'; elseif isvector(data.(field)) && isequal(datsiz, [1 ntime ones(1,numel(datsiz)-2)]) dimord = 'time'; end case {'freq'} if isvector(data.(field)) && isequal(datsiz, [1 nfreq]) dimord = 'freq'; end otherwise if isfield(data, 'dim') && isequal(datsiz, data.dim) dimord = 'dim1_dim2_dim3'; end end % switch field % deal with possible first pos which is a cell if exist('dimord', 'var') && strcmp(dimord(1:3), 'pos') && iscell(data.(field)) dimord = ['{pos}' dimord(4:end)]; end if ~exist('dimord', 'var') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 4: there is only one way that the dimensions can be interpreted %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% dimtok = cell(size(datsiz)); for i=1:length(datsiz) sel = find(siz==datsiz(i)); if length(sel)==1 % there is exactly one corresponding dimension dimtok{i} = tok{sel}; else % there are zero or multiple corresponding dimensions dimtok{i} = []; end end if all(~cellfun(@isempty, dimtok)) if iscell(data.(field)) dimtok{1} = ['{' dimtok{1} '}']; end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); return end end % if dimord does not exist if ~exist('dimord', 'var') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 5: compare the size with the known size of each dimension %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% sel = ~isnan(siz) & ~isinf(siz); % nan means that the value is not known and might remain unknown % inf means that the value is not known and but should be known if length(unique(siz(sel)))==length(siz(sel)) % this should only be done if there is no chance of confusing dimensions dimtok = cell(size(datsiz)); dimtok(datsiz==npos) = {'pos'}; dimtok(datsiz==nori) = {'ori'}; dimtok(datsiz==nrpttap) = {'rpttap'}; dimtok(datsiz==nrpt) = {'rpt'}; dimtok(datsiz==nsubj) = {'subj'}; dimtok(datsiz==nchancmb) = {'chancmb'}; dimtok(datsiz==nchan) = {'chan'}; dimtok(datsiz==nfreq) = {'freq'}; dimtok(datsiz==ntime) = {'time'}; dimtok(datsiz==ndim1) = {'dim1'}; dimtok(datsiz==ndim2) = {'dim2'}; dimtok(datsiz==ndim3) = {'dim3'}; if isempty(dimtok{end}) && datsiz(end)==1 % remove the unknown trailing singleton dimension dimtok = dimtok(1:end-1); elseif isequal(dimtok{1}, 'pos') && isempty(dimtok{2}) && datsiz(2)==1 % remove the unknown leading singleton dimension dimtok(2) = []; end if all(~cellfun(@isempty, dimtok)) if iscell(data.(field)) dimtok{1} = ['{' dimtok{1} '}']; end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); return end end end % if dimord does not exist if ~exist('dimord', 'var') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 6: check whether it is a 3-D volume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isequal(datsiz, [ndim1 ndim2 ndim3]) dimord = 'dim1_dim2_dim3'; end end % if dimord does not exist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % FINAL RESORT: return "unknown" for all unknown dimensions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist('dimord', 'var') % this should not happen % if it does, it might help in diagnosis to have a very informative warning message % since there have been problems with trials not being selected correctly due to the warning going unnoticed % it is better to throw an error than a warning warning('could not determine dimord of "%s" in the following data', field) disp(data); dimtok(cellfun(@isempty, dimtok)) = {'unknown'}; if all(~cellfun(@isempty, dimtok)) if iscell(data.(field)) dimtok{1} = ['{' dimtok{1} '}']; end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); end end % add '(rpt)' in case of source.trial dimord = [prefix dimord]; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ok = isequalwithoutnans(a, b) % this is *only* used to compare matrix sizes, so we can ignore any singleton last dimension numdiff = numel(b)-numel(a); if numdiff > 0 % assume singleton dimensions missing in a a = [a(:); ones(numdiff, 1)]; b = b(:); elseif numdiff < 0 % assume singleton dimensions missing in b b = [b(:); ones(abs(numdiff), 1)]; a = a(:); end c = ~isnan(a(:)) & ~isnan(b(:)); ok = isequal(a(c), b(c)); end % function isequalwithoutnans %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ok = check_trailingdimsunitlength(data, dimtok) ok = false; for k = 1:numel(dimtok) switch dimtok{k} case 'chan' ok = numel(data.label)==1; otherwise if isfield(data, dimtok{k}); % check whether field exists ok = numel(data.(dimtok{k}))==1; end; end if ok, break; end end end % function check_trailingdimsunitlength
github
lcnbeapp/beapp-master
pinvNx2.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/pinvNx2.m
1,116
utf_8
a10c4b3cf66f4a8756fdb95d62b5e04a
function y = pinvNx2(x) % PINVNX2 computes a pseudo-inverse of the slices of an Nx2xM real-valued matrix. % Output has dimensionality 2xNxM. This implementation is generally faster % than calling pinv in a for-loop, once M > 2 siz = [size(x) 1]; xtx = zeros([2,2,siz(3:end)]); xtx(1,1,:,:) = sum(x(:,1,:,:).^2,1); xtx(2,2,:,:) = sum(x(:,2,:,:).^2,1); tmp = sum(x(:,1,:,:).*x(:,2,:,:),1); xtx(1,2,:,:) = tmp; xtx(2,1,:,:) = tmp; ixtx = inv2x2(xtx); y = mtimes2xN(ixtx, permute(x, [2 1 3:ndims(x)])); function [d] = inv2x2(x) % INV2X2 computes inverse of matrix x, where x = 2x2xN, using explicit analytic definition adjx = [x(2,2,:,:) -x(1,2,:,:); -x(2,1,:,:) x(1,1,:,:)]; denom = x(1,1,:,:).*x(2,2,:,:) - x(1,2,:,:).*x(2,1,:,:); d = adjx./denom([1 1],[1 1],:,:); function [z] = mtimes2xN(x, y) % MTIMES2XN computes x*y where x = 2x2xM and y = 2xNxM % and output dimensionatity is 2xNxM siz = size(y); z = zeros(siz); for k = 1:siz(2) z(1,k,:,:) = x(1,1,:,:).*y(1,k,:,:) + x(1,2,:,:).*y(2,k,:,:); z(2,k,:,:) = x(2,1,:,:).*y(1,k,:,:) + x(2,2,:,:).*y(2,k,:,:); end
github
lcnbeapp/beapp-master
avw_hdr_make.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/avw_hdr_make.m
4,168
utf_8
c530411ae12b3b3ce7cc6adfa1512f8c
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$ $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$]'; 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
lcnbeapp/beapp-master
prepare_mesh_headshape.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/prepare_mesh_headshape.m
8,455
utf_8
26d86124f7d9a9099dfc853ed4f9d203
function mesh = prepare_mesh_headshape(cfg) % PREPARE_MESH_HEADSHAPE % % See also PREPARE_MESH_MANUAL, PREPARE_MESH_SEGMENTATION % Copyrights (C) 2009, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % get the specific options cfg.headshape = ft_getopt(cfg, 'headshape'); if isa(cfg, 'config') % convert the config-object back into a normal structure cfg = struct(cfg); end if isa(cfg.headshape, 'config') % convert the nested config-object back into a normal structure cfg.headshape = struct(cfg.headshape); end % get the surface describing the head shape if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pos') % use the headshape surface specified in the configuration headshape = cfg.headshape; elseif isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt') % use the headshape surface specified in the configuration headshape = fixpos(cfg.headshape); elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3 % use the headshape points specified in the configuration headshape.pos = cfg.headshape; elseif ischar(cfg.headshape) % read the headshape from file headshape = ft_read_headshape(cfg.headshape); else error('cfg.headshape is not specified correctly') end % usually a headshape only describes a single surface boundaries, but there are cases % that multiple surfaces are included, e.g. skin_surface, outer_skull_surface, inner_skull_surface nmesh = numel(headshape); if ~isfield(headshape, 'tri') % generate a closed triangulation from the surface points for i=1:nmesh headshape(i).pos = unique(headshape(i).pos, 'rows'); headshape(i).tri = projecttri(headshape(i).pos); end end if ~isempty(cfg.numvertices) && ~strcmp(cfg.numvertices, 'same') for i=1:nmesh tri1 = headshape(i).tri; pos1 = headshape(i).pos; % The number of vertices is multiplied by 3 in order to have more % points on the original mesh than on the sphere mesh (see below). % The rationale for this is that every projection point on the sphere % has three corresponding points on the mesh if (cfg.numvertices>size(pos1,1)) [tri1, pos1] = refinepatch(headshape(i).tri, headshape(i).pos, 3*cfg.numvertices); else [tri1, pos1] = reducepatch(headshape(i).tri, headshape(i).pos, 3*cfg.numvertices); end % remove double vertices [pos1, tri1] = remove_double_vertices(pos1, tri1); % replace the probably unevenly distributed triangulation with a regular one % and retriangulate it to the desired accuracy [pos2, tri2] = mysphere(cfg.numvertices); % this is a regular triangulation [pos1, tri1] = retriangulate(pos1, tri1, pos2, tri2, 2); [pos1, tri1] = fairsurface(pos1, tri1, 1);% this helps redistribute the superimposed points % remove double vertices [headshape(i).pos,headshape(i).tri] = remove_double_vertices(pos1, tri1); fprintf('returning %d vertices, %d triangles\n', size(headshape(i).pos,1), size(headshape(i).tri,1)); end end % the output should only describe one or multiple boundaries and should not % include any other fields mesh = rmfield(headshape, setdiff(fieldnames(headshape), {'pos', 'tri'})); function [tri1, pos1] = refinepatch(tri, pos, numvertices) fprintf('the original mesh has %d vertices against the %d requested\n',size(pos,1),numvertices/3); fprintf('trying to refine the compartment...\n'); [pos1, tri1] = refine(pos, tri, 'updown', numvertices); function [pos, tri] = mysphere(N) % This is a copy of MSPHERE without the confusing output message % Returns a triangulated sphere with approximately M vertices % that are nicely distributed over the sphere. The vertices are aligned % along equally spaced horizontal contours according to an algorithm of % Dave Russel. % % Use as % [pos, tri] = msphere(M) % % See also SPHERE, NSPHERE, ICOSAHEDRON, REFINE % Copyright (C) 1994, Dave Rusin storeM = []; storelen = []; increaseM = 0; while (1) % put a single vertex at the top phi = [0]; th = [0]; M = round((pi/4)*sqrt(N)) + increaseM; for k=1:M newphi = (k/M)*pi; Q = round(2*M*sin(newphi)); for j=1:Q phi(end+1) = newphi; th(end+1) = (j/Q)*2*pi; % in case of even number of contours if mod(M,2) & k>(M/2) th(end) = th(end) + pi/Q; end end end % put a single vertex at the bottom phi(end+1) = [pi]; th(end+1) = [0]; % store this vertex packing storeM(end+1).th = th; storeM(end ).phi = phi; storelen(end+1) = length(phi); if storelen(end)>N break; else increaseM = increaseM+1; % fprintf('increasing M by %d\n', increaseM); end end % take the vertex packing that most closely matches the requirement [m, i] = min(abs(storelen-N)); th = storeM(i).th; phi = storeM(i).phi; % convert from spherical to cartehsian coordinates [x, y, z] = sph2cart(th, pi/2-phi, 1); pos = [x' y' z']; tri = convhulln(pos); function [pos1, tri1] = fairsurface(pos, tri, N) % FAIRSURFACE modify the mesh in order to reduce overlong edges, and % smooth out "rough" areas. This is a non-shrinking smoothing algorithm. % The procedure uses an elastic model : At each vertex, the neighbouring % triangles and vertices connected directly are used. Each edge is % considered elastic and can be lengthened or shortened, depending % on their length. Displacement are done in 3D, so that holes and % bumps are attenuated. % % Use as % [pos, tri] = fairsurface(pos, tri, N); % where N is the number of smoothing iterations. % % This implements: % G.Taubin, A signal processing approach to fair surface design, 1995 % This function corresponds to spm_eeg_inv_ElastM % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Christophe Phillips & Jeremie Mattout % spm_eeg_inv_ElastM.m 1437 2008-04-17 10:34:39Z christophe % % $Id$ ts = []; ts.XYZmm = pos'; ts.tri = tri'; ts.nr(1) = size(pos,1); ts.nr(2) = size(tri,1); % Connection vertex-to-vertex %-------------------------------------------------------------------------- M_con = sparse([ts.tri(1,:)';ts.tri(1,:)';ts.tri(2,:)';ts.tri(3,:)';ts.tri(2,:)';ts.tri(3,:)'], ... [ts.tri(2,:)';ts.tri(3,:)';ts.tri(1,:)';ts.tri(1,:)';ts.tri(3,:)';ts.tri(2,:)'], ... ones(ts.nr(2)*6,1),ts.nr(1),ts.nr(1)); kpb = .1; % Cutt-off frequency lam = .5; mu = lam/(lam*kpb-1); % Parameters for elasticity. XYZmm = ts.XYZmm; % smoothing iterations %-------------------------------------------------------------------------- for j=1:N XYZmm_o = zeros(3,ts.nr(1)) ; XYZmm_o2 = zeros(3,ts.nr(1)) ; for i=1:ts.nr(1) ln = find(M_con(:,i)); d_i = sqrt(sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).^2)); if sum(d_i)==0 w_i = zeros(size(d_i)); else w_i = d_i/sum(d_i); end XYZmm_o(:,i) = XYZmm(:,i) + ... lam * sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).*(ones(3,1)*w_i),2); end for i=1:ts.nr(1) ln = find(M_con(:,i)); d_i = sqrt(sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).^2)); if sum(d_i)==0 w_i = zeros(size(d_i)); else w_i = d_i/sum(d_i); end XYZmm_o2(:,i) = XYZmm_o(:,i) + ... mu * sum((XYZmm_o(:,ln)-XYZmm_o(:,i)*ones(1,length(ln))).*(ones(3,1)*w_i),2); end XYZmm = XYZmm_o2; end % collect output results %-------------------------------------------------------------------------- pos1 = XYZmm'; tri1 = tri; if 0 % this is some test/demo code mesh = []; [mesh.pos, mesh.tri] = icosahedron162; scale = 1+0.3*randn(size(pos,1),1); mesh.pos = mesh.pos .* [scale scale scale]; figure ft_plot_mesh(mesh) [mesh.pos, mesh.tri] = fairsurface(mesh.pos, mesh.tri, 10); figure ft_plot_mesh(mesh) end
github
lcnbeapp/beapp-master
normals.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/normals.m
2,528
utf_8
96701c7ebda7e6efca8095b3adb6081c
function [nrm] = normals(pnt, tri, opt) % NORMALS compute the surface normals of a triangular mesh % for each triangle or for each vertex % % [nrm] = normals(pnt, tri, opt) % where opt is either 'vertex' or 'triangle' % Copyright (C) 2002-2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ 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); ntri = size(tri,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_tri = zeros(ntri, 3); % for i=1:ntri % v2 = pnt(tri(i,2),:) - pnt(tri(i,1),:); % v3 = pnt(tri(i,3),:) - pnt(tri(i,1),:); % nrm_tri(i,:) = cross(v2, v3); % end % vectorized version of the previous part v2 = pnt(tri(:,2),:) - pnt(tri(:,1),:); v3 = pnt(tri(:,3),:) - pnt(tri(:,1),:); nrm_tri = cross(v2, v3); if strcmp(opt, 'vertex') % compute vertex normals nrm_pnt = zeros(npnt, 3); for i=1:ntri nrm_pnt(tri(i,1),:) = nrm_pnt(tri(i,1),:) + nrm_tri(i,:); nrm_pnt(tri(i,2),:) = nrm_pnt(tri(i,2),:) + nrm_tri(i,:); nrm_pnt(tri(i,3),:) = nrm_pnt(tri(i,3),:) + nrm_tri(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_tri ./ (sqrt(sum(nrm_tri.^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
lcnbeapp/beapp-master
rejectvisual_trial.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/rejectvisual_trial.m
9,360
utf_8
70c608ed1010a7f2dde378e7ceb36ea1
function [chansel, trlsel, cfg] = rejectvisual_trial(cfg, data) % SUBFUNCTION for ft_rejectvisual % determine the initial selection of trials ntrl = length(data.trial); if isequal(cfg.trials, 'all') % support specification like 'all' cfg.trials = 1:ntrl; end trlsel = false(1,ntrl); trlsel(cfg.trials) = true; % determine the initial selection of channels nchan = length(data.label); cfg.channel = ft_channelselection(cfg.channel, data.label); % support specification like 'all' chansel = false(1,nchan); chansel(match_str(data.label, cfg.channel)) = true; % compute the sampling frequency from the first two timepoints fsample = 1/mean(diff(data.time{1})); % compute the offset from the time axes offset = zeros(ntrl,1); for i=1:ntrl offset(i) = time2offset(data.time{i}, fsample); end if (isfield(cfg, 'preproc') && ~isempty(cfg.preproc)) 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, data.time{i}, cfg.preproc); end ft_progress('close'); end % 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
lcnbeapp/beapp-master
wizard_base.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/wizard_base.m
11,622
utf_8
cd0fcbdbd539128983f819e31e3d920b
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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % 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
lcnbeapp/beapp-master
mesh_spectrum.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/mesh_spectrum.m
1,373
utf_8
e29d504eadc1676f855eb0c8ba8b3267
% Mesh spectrum function [L,H,d] = ct_mesh_spectrum(S,n,varargin) %[L,H,d] = ct_mesh_spectrum(S,n,mode) % Compute the mesh laplace matrix and its spectrum % input, % S: mesh file, it has to have a pnt and a tri field % n: number of mesh harmonic functions % mode: 'full' for the full graph, 'half' if you want to do the first and % the second half independently (this is useful if your graph is composed % by two connected components) % output, % L: mesh laplacian matrix % H: matrix containing a mesh harmonic functions per column % d: spectrum of the negative Laplacian matrix, its units are 1/space^2 % (spatial frequencies are obtained as sqrt(d)) if nargin==2||varargin{1}==1 pnt{1} = S.pos; tri{1} = S.tri; elseif varargin{1}==2 pnt{1} = S.pos(1:end/2,:); tri{1} = S.tri(1:end/2,:); pnt{2} = S.pos(end/2+1:end,:); tri{2} = S.tri(end/2+1:end,:) - size(pnt{1},1); end for j = 1:length(pnt) if length(pnt)==2&&j == 1 disp('Computing the spectrum of the the first hemisphere') elseif length(pnt)==2&&j == 2 disp('Computing the spectrum of the the second hemisphere') end [L{j},~] = mesh_laplacian(pnt{j},tri{j}); L{j} = (L{j} + L{j}')/2; disp('Computing the spectrum of the negative Laplacian matrix') [H{j},D] = eigs(L{j},n,'sm'); d{j} = diag(D); disp('Diagonalization completed') end
github
lcnbeapp/beapp-master
spikesort.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/spikesort.m
5,832
utf_8
fed348ceea614e5eeddbd547090e7922
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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this can be used for printing detailled user feedback fb = false; % get the options presort = ft_getopt(varargin, 'presort'); 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
lcnbeapp/beapp-master
shiftpredict.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/shiftpredict.m
8,678
utf_8
df8a7daa983de83d580b19297e9ab23a
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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ 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
lcnbeapp/beapp-master
volumeedit.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/volumeedit.m
15,832
utf_8
66df68c10de81ef176ced3ba888a8e9b
function [dataout] = volumeedit(data, varargin) % VOLUMEEDIT allows for editing of a (booleanized) volume, in order to % remove unwanted voxels. Interaction proceeds with the keyboard and the % mouse. % Copyright (C) 2013, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ revision = '$Id$'; bckgrnd = ft_getopt(varargin, 'background', []); datain = data; data = data~=0; dim = size(data); xi = round(dim(1)/2); yi = round(dim(2)/2); zi = round(dim(3)/2); xi = max(xi, 1); xi = min(xi, dim(1)); yi = max(yi, 1); yi = min(yi, dim(2)); zi = max(zi, 1); zi = min(zi, dim(3)); % enforce the size of the subplots to be isotropic xdim = dim(1) + dim(2); ydim = dim(2) + dim(3); xsize(1) = 0.82*dim(1)/xdim; xsize(2) = 0.82*dim(2)/xdim; ysize(1) = 0.82*dim(3)/ydim; ysize(2) = 0.82*dim(2)/ydim; % create figure h = figure; set(h, 'color', [1 1 1]); % set(h, 'pointer', 'custom'); % set(h, 'pointershapecdata', nan(16)); set(h, 'visible', 'on'); set(h, 'windowbuttondownfcn', @cb_buttonpress); set(h, 'windowbuttonupfcn', @cb_buttonrelease); set(h, 'windowkeypressfcn', @cb_keyboard); % axis handles h1 = axes('position',[0.07 0.07+ysize(2)+0.05 xsize(1) ysize(1)]); %hold on; h2 = axes('position',[0.07+xsize(1)+0.05 0.07+ysize(2)+0.05 xsize(2) ysize(1)]); %hold on; h3 = axes('position',[0.07 0.07 xsize(1) ysize(2)]); %hold on; % background handles if ~isempty(bckgrnd) bckgrnd = double(bckgrnd./max(bckgrnd(:))); bckgrnd = repmat(bckgrnd, [1 1 1 3]); hb1 = imagesc(squeeze(bckgrnd(xi,:,:,:)), 'parent',h1); hb2 = imagesc(permute(bckgrnd(:,:,zi,:),[2 1 4 3]), 'parent',h2); hb3 = imagesc(squeeze(bckgrnd(:,yi,:,:)), 'parent',h3); else hb1 = []; hb2 = []; hb3 = []; end % slice handles dat1 = double(squeeze(data(xi,:,:))); dat2 = double(data(:,:,zi))'; dat3 = double(squeeze(data(:,yi,:))); if ~isempty(bckgrnd) set(h1,'nextplot','add'); set(h2,'nextplot','add'); set(h3,'nextplot','add'); hs1 = imagesc(dat1,'parent',h1,'alphadata',0.5*ones(size(dat1))); colormap hot; hs2 = imagesc(dat2,'parent',h2,'alphadata',0.5*ones(size(dat2))); colormap hot; hs3 = imagesc(dat3,'parent',h3,'alphadata',0.5*ones(size(dat3))); colormap hot; set(h1,'nextplot','replace'); set(h2,'nextplot','replace'); set(h3,'nextplot','replace'); else hs1 = imagesc(dat1,'parent',h1); %colormap gray; hs2 = imagesc(dat2,'parent',h2); %colormap gray; hs3 = imagesc(dat3,'parent',h3); %colormap gray; end set(h1, 'tag', 'jk', 'clim', [0 1]); set(h2, 'tag', 'ji', 'clim', [0 1]); set(h3, 'tag', 'ik', 'clim', [0 1]); % crosshair handles hch1 = crosshair([zi yi], 'parent', h1, 'color', 'y'); hch2 = crosshair([xi yi], 'parent', h2, 'color', 'y'); hch3 = crosshair([zi xi], 'parent', h3, 'color', 'y'); % erasercontour he1(1,:) = line(zi-3.5+[0 0 7 7 0],yi-3.5+[0 7 7 0 0],'color','r','parent',h1); he2(1,:) = line(xi-3.5+[0 0 7 7 0],yi-3.5+[0 7 7 0 0],'color','r','parent',h2); he3(1,:) = line(zi-3.5+[0 0 7 7 0],xi-3.5+[0 7 7 0 0],'color','r','parent',h3); % create structure to be passed to gui opt.data = data~=0; if ~isempty(bckgrnd) opt.bckgrnd = bckgrnd; end opt.handlesana = [hb1 hb2 hb3]; opt.handlesaxes = [h1 h2 h3]; opt.handlescross = [hch1(:)';hch2(:)';hch3(:)']; opt.handlesslice = [hs1 hs2 hs3]; opt.handleseraser = [he1(:)';he2(:)';he3(:)']; opt.ijk = [xi yi zi]; opt.dim = dim; opt.quit = 0; opt.mask = opt.data~=0; opt.radius = [3 3 3]; setappdata(h, 'opt', opt); cb_redraw(h); while opt.quit==0 uiwait(h); opt = getappdata(h, 'opt'); % needed to update the opt.quit end opt = getappdata(h, 'opt'); delete(h); dataout = datain; dataout(~opt.mask) = 0; dataout(opt.mask) = 1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_keyboard(h, eventdata) if isempty(eventdata) % determine the key that corresponds to the uicontrol element that was activated key = get(h, 'userdata'); else % determine the key that was pressed on the keyboard key = parseKeyboardEvent(eventdata); end % get focus back to figure if ~strcmp(get(h, 'type'), 'figure') set(h, 'enable', 'off'); drawnow; set(h, 'enable', 'on'); end h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); tag = get(curr_ax, 'tag'); switch tag case 'jk' xy = [2 3]; case 'ji' xy = [2 1]; case 'ik' xy = [1 3]; otherwise end switch key case 'leftarrow' opt.ijk(xy(2)) = opt.ijk(xy(2)) - 1; setappdata(h, 'opt', opt); cb_redraw(h); case 'rightarrow' opt.ijk(xy(2)) = opt.ijk(xy(2)) + 1; setappdata(h, 'opt', opt); cb_redraw(h); case 'uparrow' opt.ijk(xy(1)) = opt.ijk(xy(1)) - 1; setappdata(h, 'opt', opt); cb_redraw(h); case 'downarrow' opt.ijk(xy(1)) = opt.ijk(xy(1)) + 1; setappdata(h, 'opt', opt); cb_redraw(h); case 'd' % delete current voxel cb_eraser(h); cb_redraw(h); case 'q' setappdata(h, 'opt', opt); cb_cleanup(h); case 'r' % select the radius of the eraser box response = inputdlg(sprintf('radius of eraser box (in voxels)'), 'specify', 1, {num2str(opt.radius)}); if ~isempty(response) response = str2double(tokenize(response{1},' ')); opt.radius = round(response); opt.radius = min(opt.radius, 100); opt.radius = max(opt.radius, 1); if numel(opt.radius)==1, opt.radius = [1 1 1]*opt.radius; end setappdata(h, 'opt', opt); cb_erasercontour(h); end case 'control+control' % do nothing case 'shift+shift' % do nothing case 'alt+alt' % do nothing otherwise setappdata(h, 'opt', opt); %cb_help(h); end uiresume(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_eraser(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); n = opt.radius; if numel(n)==1, n = [n n n]; end xi = opt.ijk(1)+(-n(1):n(1)); xi(xi>opt.dim(1)) = []; xi(xi<1) = []; yi = opt.ijk(2)+(-n(2):n(2)); yi(yi>opt.dim(2)) = []; yi(yi<1) = []; zi = opt.ijk(3)+(-n(3):n(3)); zi(zi>opt.dim(3)) = []; zi(zi<1) = []; if opt.erase opt.mask(xi,yi,zi) = false; else opt.mask(xi,yi,zi) = true; end setappdata(h, 'opt', opt); uiresume(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_erasercontour(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); ijk = opt.ijk; n = opt.radius*2+1; if numel(n)==1, n = [n n n]; end set(opt.handleseraser(1),'xdata',ijk(3)-n(3)/2+[0 0 n(3) n(3) 0]); set(opt.handleseraser(1),'ydata',ijk(2)-n(2)/2+[0 n(2) n(2) 0 0]); set(opt.handleseraser(2),'xdata',ijk(1)-n(1)/2+[0 0 n(1) n(1) 0]); set(opt.handleseraser(2),'ydata',ijk(2)-n(2)/2+[0 n(2) n(2) 0 0]); set(opt.handleseraser(3),'xdata',ijk(3)-n(3)/2+[0 0 n(3) n(3) 0]); set(opt.handleseraser(3),'ydata',ijk(1)-n(1)/2+[0 n(1) n(1) 0 0]); uiresume(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_redraw(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); xi = opt.ijk(1); yi = opt.ijk(2); zi = opt.ijk(3); if isfield(opt, 'bckgrnd') dat1b = squeeze(opt.bckgrnd(xi,:,:,:)); dat2b = permute(opt.bckgrnd(:,:,zi,:),[2 1 4 3]); dat3b = squeeze(opt.bckgrnd(:,yi,:,:)); set(opt.handlesaxes(1),'nextplot','add'); set(opt.handlesaxes(2),'nextplot','add'); set(opt.handlesaxes(3),'nextplot','add'); set(opt.handlesana(1), 'CData', dat1b); set(opt.handlesana(2), 'CData', dat2b); set(opt.handlesana(3), 'CData', dat3b); set(opt.handlesaxes(1),'nextplot','replace'); set(opt.handlesaxes(2),'nextplot','replace'); set(opt.handlesaxes(3),'nextplot','replace'); end tmpdata = opt.data; tmpdata(~opt.mask) = 0; tmpdata(opt.mask) = 1; xi2 = xi+(-opt.radius(1):opt.radius(1)); xi2(xi2<1) = 1; xi2(xi2>opt.dim(1)) = opt.dim(1); yi2 = yi+(-opt.radius(2):opt.radius(2)); yi2(yi2<1) = 1; yi2(yi2>opt.dim(2)) = opt.dim(2); zi2 = zi+(-opt.radius(3):opt.radius(3)); zi2(zi2<1) = 1; zi2(zi2>opt.dim(3)) = opt.dim(3); dat1 = double(squeeze(sum(tmpdata(xi2,:,:),1))>0)*0.5+double(squeeze(tmpdata(xi,:,:)))*0.5; dat2 = double(sum(tmpdata(:,:,zi2),3)'>0)*0.5+double(tmpdata(:,:,zi)'>0)*0.5; dat3 = double(squeeze(sum(tmpdata(:,yi2,:),2))>0)*0.5+double(squeeze(tmpdata(:,yi,:))>0)*0.5; set(opt.handlesslice(1), 'CData', dat1); set(opt.handlesslice(2), 'CData', dat2); set(opt.handlesslice(3), 'CData', dat3); if isfield(opt, 'bckgrnd') msk1 = 0.5*double(dat1>0); msk2 = 0.5*double(dat2>0); msk3 = 0.5*double(dat3>0); set(opt.handlesslice(1), 'AlphaData', msk1); set(opt.handlesslice(2), 'AlphaData', msk2); set(opt.handlesslice(3), 'AlphaData', msk3); end crosshair([zi yi], 'handle', opt.handlescross(1,:)); crosshair([xi yi], 'handle', opt.handlescross(2,:)); crosshair([zi xi], 'handle', opt.handlescross(3,:)); cb_erasercontour(h); set(h, 'currentaxes', curr_ax); setappdata(h, 'opt', opt); uiresume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_buttonpress(h, eventdata) h = getparent(h); cb_getposition(h); seltype = get(h, 'selectiontype'); switch seltype case 'normal' % just update to new position, nothing else to be done here case 'alt' opt = getappdata(h, 'opt'); opt.erase = true; setappdata(h, 'opt', opt); cb_eraser(h); set(h, 'windowbuttonmotionfcn', @cb_tracemouse); case 'extend' opt = getappdata(h, 'opt'); opt.erase = false; setappdata(h, 'opt', opt); cb_eraser(h); set(h, 'windowbuttonmotionfcn', @cb_tracemouse); otherwise end cb_redraw(h); uiresume; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_buttonrelease(h, eventdata) seltype = get(h, 'selectiontype'); switch seltype case 'normal' % just update to new position, nothing else to be done here case 'alt' set(h, 'windowbuttonmotionfcn', ''); case 'extend' set(h, 'windowbuttonmotionfcn', ''); otherwise end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_tracemouse(h, eventdata) h = getparent(h); cb_getposition(h); opt = getappdata(h, 'opt'); n = opt.radius; if numel(n)==1, n = [n n n]; end xi = opt.ijk(1)+(-n(1):n(1)); xi(xi>opt.dim(1)) = []; xi(xi<1) = []; yi = opt.ijk(2)+(-n(2):n(2)); yi(yi>opt.dim(2)) = []; yi(yi<1) = []; zi = opt.ijk(3)+(-n(3):n(3)); zi(zi>opt.dim(3)) = []; zi(zi<1) = []; if opt.erase opt.mask(xi,yi,zi) = false; else opt.mask(xi,yi,zi) = true; end setappdata(h, 'opt', opt); cb_redraw(h); uiresume; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_getposition(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); pos = get(curr_ax, 'currentpoint'); tag = get(curr_ax, 'tag'); switch tag case 'jk' opt.ijk([3,2]) = round(pos(1,1:2)); case 'ji' opt.ijk([1,2]) = round(pos(1,1:2)); case 'ik' opt.ijk([3,1]) = round(pos(1,1:2)); otherwise end opt.ijk = min(opt.ijk, opt.dim); opt.ijk = max(opt.ijk, [1 1 1]); setappdata(h, 'opt', opt); uiresume; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_cleanup(h, eventdata) opt = getappdata(h, 'opt'); opt.quit = true; setappdata(h, 'opt', opt); uiresume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = getparent(h) p = h; while p~=0 h = p; p = get(h, 'parent'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = parseKeyboardEvent(eventdata) key = eventdata.Key; % handle possible numpad events (different for Windows and UNIX systems) % NOTE: shift+numpad number does not work on UNIX, since the shift % modifier is always sent for numpad events if isunix() shiftInd = match_str(eventdata.Modifier, 'shift'); if ~isnan(str2double(eventdata.Character)) && ~isempty(shiftInd) % now we now it was a numpad keystroke (numeric character sent AND % shift modifier present) key = eventdata.Character; eventdata.Modifier(shiftInd) = []; % strip the shift modifier end elseif ispc() if strfind(eventdata.Key, 'numpad') key = eventdata.Character; end end if ~isempty(eventdata.Modifier) key = [eventdata.Modifier{1} '+' key]; end
github
lcnbeapp/beapp-master
statistics_wrapper.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/statistics_wrapper.m
28,152
utf_8
0434a84d6c5a056986bcd7655d59597f
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 FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS and % FT_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 FT_STATISTICS_xxx, where cfg.method='xxx'. At % this moment, we have implemented two statistical subfunctions: % FT_STATISTICS_ANALYTIC, which calculates analytic significance probabilities and critical % values (exact or asymptotic), and FT_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 FT_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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % 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 cfg.latency = ft_getopt(cfg, 'latency', 'all'); cfg.frequency = ft_getopt(cfg, 'frequency', 'all'); cfg.roi = ft_getopt(cfg, 'roi', []); cfg.avgovertime = ft_getopt(cfg, 'avgovertime', 'no'); cfg.avgoverfreq = ft_getopt(cfg, 'avgoverfreq', 'no'); cfg.avgoverroi = ft_getopt(cfg, 'avgoverroi', 'no'); % determine the type of the input and hence the output data if ~exist('OCTAVE_VERSION', 'builtin') [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 if istimelock || isfreq, % these defaults only apply to channel level data cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.avgoverchan = ft_getopt(cfg, 'avgoverchan', 'no'); 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 FT_VOLUMENORMALISE 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 FT_VOLUMENORMALISE 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 FT_VOLUMENORMALISE 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) if islogical(cfg.roi{i}) tmp = cfg.roi{i}; else tmpcfg.roi = cfg.roi{i}; tmpcfg.inputcoord = cfg.inputcoord; tmpcfg.atlas = cfg.atlas; tmp = ft_volumelookup(tmpcfg, varargin{1}); end 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; if ischar(cfg.roi{i}) roilabel{end+1} = cfg.roi{i}; else roilabel{end+1} = ['ROI ' num2str(i)]; end 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 % check whether the original input data contains a dim, which would allow % for 3D reshaping and clustering with bwlabeln if isfield(varargin{1}, 'transform') || ((isfield(varargin{1}, 'dim') && prod(varargin{1}.dim)==size(varargin{1}.pos,1))) cfg.connectivity = 'bwlabeln'; 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 = []; % verify that neighbours are present in case needed (not needed when % averaging over channels) if ~(isfield(cfg, 'avgoverchan') && istrue(cfg.avgoverchan)) &&... ~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(['ft_statistics_' cfg.method], 'file') statmethod = str2func(['ft_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 (%d) does not match the number of observations in the data (%d)', size(cfg.design,2), size(dat,2)); 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),'ft_statistics_montecarlo') % because ft_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); else [stat] = statmethod(cfg, dat, design); 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 try stat.freq = varargin{1}.freq; end try stat.time = varargin{1}.time; 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 extradim = 1; elseif isfield(varargin{1}, 'inside') && isfield(varargin{1}, 'freq') && isfield(varargin{1}, 'time') && numel(tmp)==length(varargin{1}.inside)*length(varargin{1}.freq)*length(varargin{1}.time) % the statistic is a higher dimensional matrix (here as a function of freq) computed only on the % inside voxels newtmp = zeros(length(varargin{1}.inside)+length(varargin{1}.outside), length(varargin{1}.freq), length(varargin{1}.time)); if islogical(tmp) newtmp(varargin{1}.inside, :, :) = reshape(tmp, length(varargin{1}.inside), length(varargin{1}.freq), []); newtmp(varargin{1}.outside, :, :) = false; else newtmp(varargin{1}.inside, :, :) = reshape(tmp, length(varargin{1}.inside), length(varargin{1}.freq), []); newtmp(varargin{1}.outside, :, :) = nan; end tmp = newtmp; clear newtmp; extradim = length(varargin{1}.freq); elseif isfield(varargin{1}, 'inside') && isfield(varargin{1}, 'freq') && numel(tmp)==length(varargin{1}.inside)*length(varargin{1}.freq) % the statistic is a higher dimensional matrix (here as a function of freq) computed only on the % inside voxels newtmp = zeros(length(varargin{1}.inside)+length(varargin{1}.outside), length(varargin{1}.freq)); if islogical(tmp) newtmp(varargin{1}.inside, :) = reshape(tmp, length(varargin{1}.inside), []); newtmp(varargin{1}.outside, :) = false; else newtmp(varargin{1}.inside, :) = reshape(tmp, length(varargin{1}.inside), []); newtmp(varargin{1}.outside, :) = nan; end tmp = newtmp; clear newtmp; extradim = length(varargin{1}.freq); elseif isfield(varargin{1}, 'inside') && isfield(varargin{1}, 'time') && numel(tmp)==length(varargin{1}.inside)*length(varargin{1}.time) % the statistic is a higher dimensional matrix (here as a function of time) computed only on the % inside voxels newtmp = zeros(length(varargin{1}.inside)+length(varargin{1}.outside), length(varargin{1}.time)); if islogical(tmp) newtmp(varargin{1}.inside, :) = reshape(tmp, length(varargin{1}.inside), []); newtmp(varargin{1}.outside, :) = false; else newtmp(varargin{1}.inside, :) = reshape(tmp, length(varargin{1}.inside), []); newtmp(varargin{1}.outside, :) = nan; end tmp = newtmp; clear newtmp; extradim = length(varargin{1}.time); else extradim = 1; 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)); else stat = setsubfield(stat, statfield{i}, tmp); 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 resembles 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 ntrltap = sum(varargin{i}.cumtapcnt); dat{i} = zeros(Ninside, ntrltap); for j=1:Ninside k = varargin{1}.inside(j); if ischar(varargin{i}.avg.csdlabel{1}) % this represents the 'old-style' csdlabel, one list for all dipoles dipsel = find(strcmp(varargin{i}.avg.csdlabel, 'scandip')); else % this represents the 'new-style' csdlabel, one list for each of the dipoles dipsel = find(strcmp(varargin{i}.avg.csdlabel{k}, 'scandip')); end 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(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(varargin{1}, 'dim') cfg.dim = varargin{1}.dim; else cfg.dim = size(varargin{1}.trial(1).(cfg.parameter)); cfg.dim(1) = numel(varargin{1}.inside); cfg.insideorig = varargin{1}.inside; cfg.inside = varargin{1}.inside; end %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); if isfield(varargin{1}, 'dim') dim = varargin{1}.dim; inside = false(prod(dim),1); else dim = numel(varargin{1}.inside); inside = false(size(varargin{1}.pos,1),1); end inside(varargin{1}.inside) = true; tmp = getsubfield(varargin{1}, cfg.parameter); if size(tmp,2)>1 if isfield(varargin{1}, 'freq') Nvoxel = Nvoxel*numel(varargin{1}.freq); dim = [dim numel(varargin{1}.freq)]; inside = repmat(inside, [1 numel(varargin{1}.freq)]); end if isfield(varargin{1}, 'time') Nvoxel = Nvoxel*numel(varargin{1}.time); dim = [dim numel(varargin{1}.time)]; if isfield(varargin{1},'freq') inside = repmat(inside, [1 1 numel(varargin{1}.time)]); else inside = repmat(inside, [1 numel(varargin{1}.time)]); end end end dat = zeros(Nvoxel, Nsource); for i=1:Nsource tmp = getsubfield(varargin{i}, cfg.parameter); dat(:,i) = tmp(:); end insideorig = find(inside(:,1)); inside = find(inside(:)); if isfield(varargin{1}, 'inside') if isfield(varargin{1}, 'pos') npos = size(varargin{1}.pos,1); elseif isfield(varargin{1}, 'dim') npos = prod(varargin{1}.dim); else npos = length(varargin{1}.inside); % uninformative, at least prevents crash end fprintf('only selecting voxels inside the brain for statistics (%.1f%%)\n', 100*length(varargin{1}.inside)/npos); dat = dat(inside,:); end % remember the dimension of the source data cfg.dim = dim; % remember which voxels are inside the brain cfg.inside = inside(:); cfg.insideorig = insideorig; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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
lcnbeapp/beapp-master
csp.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/csp.m
1,702
utf_8
3eb6c73192bc8163344c9b5e70a04877
function [W] = csp(C1, C2, m) % CSP calculates the common spatial pattern (CSP) projection. % % Use as: % [W] = csp(C1, C2, m) % % This function implements the intents of the CSP algorithm described in [1]. % Specifically, CSP finds m spatial projections that maximize the variance (or % band power) in one condition (described by the [p x p] channel-covariance % matrix C1), and simultaneously minimizes the variance in the other (C2): % % W C1 W' = D % % and % % W (C1 + C2) W' = I, % % Where D is a diagonal matrix with decreasing values on it's diagonal, and I % is the identity matrix of matching shape. % The resulting [m x p] matrix can be used to project a zero-centered [p x n] % trial matrix X: % % S = W X. % % % Although the CSP is the de facto standard method for feature extraction for % motor imagery induced event-related desynchronization, it is not strictly % necessary [2]. % % [1] Zoltan J. Koles. The quantitative extraction and topographic mapping of % the abnormal components in the clinical EEG. Electroencephalography and % Clinical Neurophysiology, 79(6):440--447, December 1991. % % [2] Jason Farquhar. A linear feature space for simultaneous learning of % spatio-spectral filters in BCI. Neural Networks, 22:1278--1285, 2009. % Copyright (c) 2012, Boris Reuderink P = whiten(C1 + C2, 1e-14); % decorrelate over conditions [B, Lamb, B2] = svd(P * C1 * P'); % rotation to decorrelate within condition. W = B' * P; % keep m projections at ends keep = circshift(1:size(W, 1) <= m, [0, -m/2]); W = W(keep,:); function P = whiten(C, rtol) [U, l, U2] = svd(C); l = diag(l); keep = l > max(l) * rtol; P = diag(l(keep).^(-.5)) * U(:,keep)';
github
lcnbeapp/beapp-master
read_besa_src.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/read_besa_src.m
2,659
utf_8
43681bd06aada6e69bddc42dbb47c254
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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ 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
lcnbeapp/beapp-master
splint.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/splint.m
6,340
utf_8
18b814d3a2a955804ded0f7bd7ea6eec
function [V2, L2, L1] = splint(elc1, V1, elc2, order, degree, lambda) % 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 % order order of splines % degree degree of Legendre polynomials % lambda regularization parameter % % 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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ 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, order, degree); G = gx+eye(size(gx))*lambda; % Apply regularization as in comments in Perrin 1989 % 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, order, degree); 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, N) % M = 4; % constant in denominator, set in ft_scalpcurrentdensity % N is the number of terms for series expansion, set in ft_scalpcurrentdensity % 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(x>1) = 1; % to avoid rounding off errors x(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
lcnbeapp/beapp-master
find_nearest.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/find_nearest.m
5,997
utf_8
d222cf9a4bf0492d012b52b1fc171646
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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this can be used for printing detailled user feedback fb = false; 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) % this can be used for printing detailled user feedback fb = false; 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
lcnbeapp/beapp-master
prepare_mesh_segmentation.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/prepare_mesh_segmentation.m
7,346
utf_8
d189606268a3d46e958dacce53df76ee
function bnd = prepare_mesh_segmentation(cfg, mri) % PREPARE_MESH_SEGMENTATION % % See also PREPARE_MESH_MANUAL, PREPARE_MESH_HEADSHAPE, PREPARE_MESH_HEXAHEDRAL % Copyrights (C) 2009, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % ensure that the input is consistent with what this function expects mri = ft_checkdata(mri, 'datatype', {'volume', 'segmentation'}, 'hasunit', 'yes'); % get the default options cfg.spmversion = ft_getopt(cfg, 'spmversion', 'spm8'); cfg.method = ft_getopt(cfg, 'method', 'projectmesh'); if all(isfield(mri, {'gray', 'white', 'csf'})) cfg.tissue = ft_getopt(cfg, 'tissue', 'brain'); % set the default cfg.numvertices = ft_getopt(cfg, 'numvertices', 3000); % set the default else % do not set defaults for tissue and numvertices cfg.tissue = ft_getopt(cfg, 'tissue'); cfg.numvertices = ft_getopt(cfg, 'numvertices'); end % check that SPM is on the path, try to add the preferred version if strcmpi(cfg.spmversion, 'spm2'), ft_hastoolbox('SPM2',1); elseif strcmpi(cfg.spmversion, 'spm8'), ft_hastoolbox('SPM8',1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % try to determine the tissue (if not specified) % special exceptional case first if isempty(cfg.tissue) && numel(cfg.numvertices)==1 && isfield(mri,'white') && isfield(mri,'gray') && isfield(mri,'csf') mri=ft_datatype_segmentation(mri, 'segmentationstyle', 'probabilistic', 'hasbrain', 'yes'); cfg.tissue='brain'; end if isempty(cfg.tissue) mri = ft_datatype_segmentation(mri, 'segmentationstyle', 'indexed'); fn = fieldnames(mri); for i=1:numel(fn) if numel(mri.(fn{i}))==prod(mri.dim) && isfield(mri, [fn{i},'label']) segfield=fn{i}; end end if isfield(mri, [segfield 'label']) cfg.tissue = mri.([segfield 'label']); cfg.tissue = cfg.tissue(~cellfun(@isempty, cfg.tissue)); fprintf('making mesh for %s tissue\n', cfg.tissue{:}); else cfg.tissue=setdiff(unique(mri.(segfield)(:)),0); fprintf('making mesh for tissue with segmentation value %d\n', cfg.tissue); end end if ischar(cfg.tissue) % it should either be something like {'brain', 'skull', 'scalp'}, or something like [1 2 3] cfg.tissue = {cfg.tissue}; end if numel(cfg.tissue)>1 && numel(cfg.numvertices)==1 % use the same number of vertices for each tissue cfg.numvertices = repmat(cfg.numvertices, size(cfg.tissue)); elseif numel(cfg.tissue)~=numel(cfg.numvertices) error('you should specify the number of vertices for each tissue type'); end if iscell(cfg.tissue) % the code below assumes that it is a probabilistic representation if any(strcmp(cfg.tissue, 'brain')) mri = ft_datatype_segmentation(mri, 'segmentationstyle', 'probabilistic', 'hasbrain', 'yes'); else mri = ft_datatype_segmentation(mri, 'segmentationstyle', 'probabilistic'); end else % the code below assumes that it is an indexed representation mri = ft_datatype_segmentation(mri, 'segmentationstyle', 'indexed'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % do the mesh extraction for i =1:numel(cfg.tissue) if iscell(cfg.tissue) % the code below assumes that it is a probabilistic representation % for example {'brain', 'skull', scalp'} try seg = mri.(fixname(cfg.tissue{i})); catch error('Please specify cfg.tissue to correspond to tissue types in the segmented MRI') end tissue = cfg.tissue{i}; else % this assumes that it is an indexed representation % for example [3 2 1] seg = (mri.seg==cfg.tissue(i)); if isfield(mri, 'seglabel') try tissue = mri.seglabel{cfg.tissue(i)}; catch error('Please specify cfg.tissue to correspond to (the name or number of) tissue types in the segmented MRI') end else tissue = sprintf('tissue %d', i); end end if strcmp(cfg.method, 'isosurface') fprintf('triangulating the outer boundary of compartment %d (%s) with the isosurface method\n', i, tissue); else fprintf('triangulating the outer boundary of compartment %d (%s) with %d vertices\n', i, tissue, cfg.numvertices(i)); end % in principle it is possible to do volumesmooth and volumethreshold, but % the user is expected to prepare his segmentation outside this function % seg = volumesmooth(seg, nan, nan); % ensure that the segmentation is binary and that there is a single contiguous region seg = volumethreshold(seg, 0.5, tissue); % the function that generates the mesh will fail if there is a hole in the middle seg = volumefillholes(seg); switch cfg.method case 'isosurface' [tri, pos] = isosurface(seg, 0.5); pos = pos(:,[2 1 3]); % Mathworks isosurface indexes differently case 'iso2mesh' ft_hastoolbox('iso2mesh', 1); opt = []; opt.radbound = 3; % set the target surface mesh element bounding sphere be <3 pixels in radius opt.maxnode = cfg.numvertices(i); opt.maxsurf = 1; [pos, tri] = v2s(seg, 1, opt, 'cgalsurf'); tri = tri(:,1:3); case 'projectmesh' [mrix, mriy, mriz] = ndgrid(1:mri.dim(1), 1:mri.dim(2), 1:mri.dim(3)); ori(1) = mean(mrix(seg(:))); ori(2) = mean(mriy(seg(:))); ori(3) = mean(mriz(seg(:))); [pos, tri] = triangulate_seg(seg, cfg.numvertices(i), ori); otherwise error('unsupported method "%s"', cfg.method); end % case numvoxels(i) = sum(find(seg(:))); % the number of voxels in this tissue bnd(i).pos = ft_warp_apply(mri.transform, pos); bnd(i).tri = tri; bnd(i).unit = mri.unit; end % for each tissue if strcmp(cfg.method, 'iso2surf') % order outside in (trying to be smart here) [dum, order] = sort(numvoxels,'descend'); bnd = bnd(order); % clean up the triangulated meshes bnd = decouplesurf(bnd); % put them back in the original order [dum, order] = sort(order); bnd = bnd(order); end end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bnd = decouplesurf(bnd) for ii = 1:length(bnd)-1 % Despite what the instructions for surfboolean says, surfaces should % be ordered from inside-out!! [newnode, newelem] = surfboolean(bnd(ii+1).pos,bnd(ii+1).tri,'decouple',bnd(ii).pos,bnd(ii).tri); bnd(ii+1).tri = newelem(newelem(:,4)==2,1:3) - size(bnd(ii+1).pos,1); bnd(ii+1).pos = newnode(newnode(:,4)==2,1:3); end % for end %function
github
lcnbeapp/beapp-master
read_besa_avr.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/read_besa_avr.m
3,870
utf_8
f19ef935bf322fb2ccbcced4717efd61
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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ 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
lcnbeapp/beapp-master
topoplot_common.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/topoplot_common.m
39,786
utf_8
e4132354f59b473a71ba3b564ab807d9
function cfg = topoplot_common(cfg, varargin) % TOPOPLOT_COMMON is shared by FT_TOPOPLOTTFR, FT_TOPOPLOTER and FT_TOPOPLOTIC, which % serve as placeholder for the documentation and for the pre/postamble. % Copyright (C) 2005-2011, F.C. Donders Centre % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ revision = '$Id$'; % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'unused', {'cohtargetchannel'}); cfg = ft_checkconfig(cfg, 'renamed', {'cohrefchannel' 'refchannel'}); cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'parameter'}); cfg = ft_checkconfig(cfg, 'deprecated', {'xparam'}); Ndata = numel(varargin); if ~isempty(varargin) && isnumeric(varargin{end}) Ndata = Ndata - 1; indx = varargin{end}; else indx = 1; end % the call with multiple inputs is done by ft_topoplotIC and recursively by ft_topoplotTFR itself if Ndata>1 && ~isnumeric(varargin{end}) for k=1:Ndata if k>1 % create a new figure for the additional input arguments % ensure new figures are all in the same size/position p = get(gcf, 'Position'); f = figure(); set(f, 'Position', p); end if isfield(cfg, 'inputfile') cfg = rmfield(cfg, 'inputfile'); end % the indexing is necessary if ft_topoplotTFR is called from % ft_singleplotER when more input data structures exist. somehow we need to % keep track of which of the data arguments is to be plotted (otherwise the % first data argument is only plotted). yet, we cannot throw away the % other data structures, because in the interactive mode % ft_singleplotER needs all data again and the entry into % ft_singleplotER will be through one of the figures (which thus needs % to have all data avalaible. at the moment I couldn't think of % anything better than using an additional indx variable and letting the % function recursively call itself. topoplot_common(cfg, varargin{1:Ndata}, indx); indx = indx + 1; end return end data = varargin{indx}; data = ft_checkdata(data, 'datatype', {'comp', 'timelock', 'freq'}); % check for option-values to be renamed cfg = ft_checkconfig(cfg, 'renamedval', {'electrodes', 'dotnum', 'numbers'}); cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'}); cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedforward', 'outflow'}); cfg = ft_checkconfig(cfg, 'renamedval', {'directionality', 'feedback', 'inflow'}); % check for renamed options cfg = ft_checkconfig(cfg, 'renamed', {'matrixside', 'directionality'}); cfg = ft_checkconfig(cfg, 'renamed', {'electrodes', 'marker'}); cfg = ft_checkconfig(cfg, 'renamed', {'emarker', 'markersymbol'}); cfg = ft_checkconfig(cfg, 'renamed', {'ecolor', 'markercolor'}); cfg = ft_checkconfig(cfg, 'renamed', {'emarkersize', 'markersize'}); cfg = ft_checkconfig(cfg, 'renamed', {'efontsize', 'markerfontsize'}); cfg = ft_checkconfig(cfg, 'renamed', {'hlmarker', 'highlightsymbol'}); cfg = ft_checkconfig(cfg, 'renamed', {'hlcolor', 'highlightcolor'}); cfg = ft_checkconfig(cfg, 'renamed', {'hlmarkersize', 'highlightsize'}); cfg = ft_checkconfig(cfg, 'renamed', {'maplimits', 'zlim'}); % old ft_checkconfig adapted partially from topoplot.m (backwards backwards compatability) cfg = ft_checkconfig(cfg, 'renamed', {'grid_scale', 'gridscale'}); cfg = ft_checkconfig(cfg, 'renamed', {'interpolate', 'interpolation'}); cfg = ft_checkconfig(cfg, 'renamed', {'numcontour', 'contournum'}); cfg = ft_checkconfig(cfg, 'renamed', {'electrod', 'marker'}); cfg = ft_checkconfig(cfg, 'renamed', {'electcolor', 'markercolor'}); cfg = ft_checkconfig(cfg, 'renamed', {'emsize', 'markersize'}); cfg = ft_checkconfig(cfg, 'renamed', {'efsize', 'markerfontsize'}); cfg = ft_checkconfig(cfg, 'renamed', {'headlimits', 'interplimits'}); % check for forbidden options cfg = ft_checkconfig(cfg, 'forbidden', {'hllinewidth', ... 'headcolor', ... 'hcolor', ... 'hlinewidth', ... 'contcolor', ... 'outline', ... 'highlightfacecolor', ... 'showlabels'}); if ft_platform_supports('griddata-v4') default_interpmethod='v4'; else % Octave does not support 'v4', and 'cubic' not yet implemented default_interpmethod='linear'; end % Set other config defaults cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin'); cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin'); cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin'); cfg.style = ft_getopt(cfg, 'style', 'both'); cfg.gridscale = ft_getopt(cfg, 'gridscale', 67); cfg.interplimits = ft_getopt(cfg, 'interplimits', 'head'); cfg.interpolation = ft_getopt(cfg, 'interpolation', default_interpmethod); cfg.contournum = ft_getopt(cfg, 'contournum', 6); cfg.colorbar = ft_getopt(cfg, 'colorbar', 'no'); cfg.shading = ft_getopt(cfg, 'shading', 'flat'); cfg.comment = ft_getopt(cfg, 'comment', 'auto'); cfg.commentpos = ft_getopt(cfg, 'commentpos', 'leftbottom'); cfg.fontsize = ft_getopt(cfg, 'fontsize', 8); cfg.baseline = ft_getopt(cfg, 'baseline', 'no'); %to avoid warning in timelock/freqbaseline cfg.trials = ft_getopt(cfg, 'trials', 'all', 1); cfg.interactive = ft_getopt(cfg, 'interactive', 'yes'); cfg.hotkeys = ft_getopt(cfg, 'hotkeys', 'no'); cfg.renderer = ft_getopt(cfg, 'renderer', []); % MATLAB sets the default cfg.marker = ft_getopt(cfg, 'marker', 'on'); cfg.markersymbol = ft_getopt(cfg, 'markersymbol', 'o'); cfg.markercolor = ft_getopt(cfg, 'markercolor', [0 0 0]); cfg.markersize = ft_getopt(cfg, 'markersize', 2); cfg.markerfontsize = ft_getopt(cfg, 'markerfontsize', 8); cfg.highlight = ft_getopt(cfg, 'highlight', 'off'); cfg.highlightchannel = ft_getopt(cfg, 'highlightchannel', 'all', 1); % highlight may be 'on', making highlightchannel {} meaningful cfg.highlightsymbol = ft_getopt(cfg, 'highlightsymbol', '*'); cfg.highlightcolor = ft_getopt(cfg, 'highlightcolor', [0 0 0]); cfg.highlightsize = ft_getopt(cfg, 'highlightsize', 6); cfg.highlightfontsize = ft_getopt(cfg, 'highlightfontsize', 8); cfg.labeloffset = ft_getopt(cfg, 'labeloffset', 0.005); cfg.maskparameter = ft_getopt(cfg, 'maskparameter', []); cfg.component = ft_getopt(cfg, 'component', []); cfg.directionality = ft_getopt(cfg, 'directionality', []); cfg.channel = ft_getopt(cfg, 'channel', 'all'); cfg.figurename = ft_getopt(cfg, 'figurename', []); cfg.interpolatenan = ft_getopt(cfg, 'interpolatenan', 'yes'); % compatibility for previous highlighting option if isnumeric(cfg.highlight) cfg.highlightchannel = cfg.highlight; cfg.highlight = 'on'; warning('cfg.highlight is now used for specifying highlighting-mode, use cfg.highlightchannel instead of cfg.highlight for specifying channels') elseif iscell(cfg.highlight) if ~iscell(cfg.highlightchannel) cfg.highlightchannel = cell(1,length(cfg.highlight)); end for icell = 1:length(cfg.highlight) if isnumeric(cfg.highlight{icell}) cfg.highlightchannel{icell} = cfg.highlight{icell}; cfg.highlight{icell} = 'on'; warning('cfg.highlight is now used for specifying highlighting-mode, use cfg.highlightchannel instead of cfg.highlight for specifying channels') end end end % Converting all highlight options to cell-arrays if they're not cell-arrays, % to make defaulting, checking for backwards compatibility and error % checking easier if ~iscell(cfg.highlight), cfg.highlight = {cfg.highlight}; end if isempty(cfg.highlightchannel), cfg.highlightchannel = ''; end if ~iscell(cfg.highlightchannel), cfg.highlightchannel = {cfg.highlightchannel}; end if ischar(cfg.highlightchannel{1}), cfg.highlightchannel = {cfg.highlightchannel}; end % {'all'} is valid input to channelselection, {1:5} isn't if ~iscell(cfg.highlightsymbol), cfg.highlightsymbol = {cfg.highlightsymbol}; end if ~iscell(cfg.highlightcolor), cfg.highlightcolor = {cfg.highlightcolor}; end if ~iscell(cfg.highlightsize), cfg.highlightsize = {cfg.highlightsize}; end if ~iscell(cfg.highlightfontsize), cfg.highlightfontsize = {cfg.highlightfontsize}; end % then make sure all cell-arrays for options have length ncellhigh and default the last element if not present ncellhigh = length(cfg.highlight); if length(cfg.highlightsymbol) < ncellhigh, cfg.highlightsymbol{ncellhigh} = 'o'; end if length(cfg.highlightcolor) < ncellhigh, cfg.highlightcolor{ncellhigh} = [0 0 0]; end if length(cfg.highlightsize) < ncellhigh, cfg.highlightsize{ncellhigh} = 6; end if length(cfg.highlightfontsize) < ncellhigh, cfg.highlightfontsize{ncellhigh} = 8; end % then default all empty cells for icell = 1:ncellhigh if isempty(cfg.highlightsymbol{icell}), cfg.highlightsymbol{icell} = 'o'; end if isempty(cfg.highlightcolor{icell}), cfg.highlightcolor{icell} = [0 0 0]; end if isempty(cfg.highlightsize{icell}), cfg.highlightsize{icell} = 6; end if isempty(cfg.highlightfontsize{icell}), cfg.highlightfontsize{icell} = 8; end end % for backwards compatability if strcmp(cfg.marker,'highlights') warning('using cfg.marker option -highlights- is no longer used, please use cfg.highlight') cfg.marker = 'off'; end % check colormap is proper format and set it if isfield(cfg,'colormap') if size(cfg.colormap,2)~=3, error('topoplot(): Colormap must be a n x 3 matrix'); end colormap(cfg.colormap); ncolors = size(cfg.colormap,1); else ncolors =[]; % let the low-level function deal with this end dtype = ft_datatype(data); % identify the interpretation of the functional data switch dtype case 'raw' data = ft_checkdata(data, 'datatype', 'timelock'); dtype = ft_datatype(data); dimord = data.dimord; case {'timelock' 'freq' 'chan' 'unknown'} dimord = data.dimord; case 'comp' dimord = 'chan_comp'; otherwise end dimtok = tokenize(dimord, '_'); % Set x/y/parameter defaults according to datatype and dimord switch dtype case 'timelock' xparam = 'time'; yparam = ''; cfg.parameter = ft_getopt(cfg, 'parameter', 'avg'); case 'freq' if any(ismember(dimtok, 'time')) xparam = 'time'; yparam = 'freq'; cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm'); else xparam = 'freq'; yparam = ''; cfg.parameter = ft_getopt(cfg, 'parameter', 'powspctrm'); end case 'comp' % Add a pseudo-axis with the component numbers: data.comp = 1:size(data.topo,2); % Specify the components if ~isempty(cfg.component) data.comp = cfg.component; data.topo = data.topo(:,cfg.component); end % Rename the field with topographic label information: data.label = data.topolabel; xparam = 'comp'; yparam = ''; cfg.parameter = ft_getopt(cfg, 'parameter', 'topo'); otherwise % if the input data is not one of the standard data types, or if % the functional data is just one value per channel % in this case xparam, yparam are not defined % and the user should define the parameter if ~isfield(data, 'label'), error('the input data should at least contain a label-field'); end if ~isfield(cfg, 'parameter'), error('the configuration should at least contain a ''parameter'' field'); end if ~isfield(cfg, 'xparam'), cfg.xlim = [1 1]; xparam = ''; end end if isfield(cfg, 'parameter') && ~isfield(data, cfg.parameter) error('cfg.parameter=%s is not present in data structure', cfg.parameter); end % user specified own fields, but no yparam (which is not asked in help) if exist('xparam', 'var') && isfield(cfg, 'parameter') && ~exist('yparam', 'var') yparam = ''; end % check whether rpt/subj is present and remove if necessary and whether hasrpt = any(ismember(dimtok, {'rpt' 'subj'})); if strcmp(dtype, 'timelock') && hasrpt, if ~isfield(data, cfg.parameter) || strcmp(cfg.parameter, 'individual') tmpcfg = []; tmpcfg.trials = cfg.trials; data = ft_timelockanalysis(tmpcfg, data); if ~strcmp(cfg.parameter, 'avg') % rename avg back into the parameter data.(cfg.parameter) = data.avg; data = rmfield(data, 'avg'); end dimord = data.dimord; dimtok = tokenize(dimord, '_'); else fprintf('input data contains repetitions, ignoring these and using ''%s'' field\n', cfg.parameter); end elseif strcmp(dtype, 'freq') && hasrpt, % this also deals with fourier-spectra in the input % or with multiple subjects in a frequency domain stat-structure % on the fly computation of coherence spectrum is not supported if isfield(data, 'crsspctrm'), data = rmfield(data, 'crsspctrm'); end tmpcfg = []; tmpcfg.trials = cfg.trials; tmpcfg.jackknife = 'no'; if isfield(cfg, 'parameter') && ~strcmp(cfg.parameter,'powspctrm') % freqdesctiptives will only work on the powspctrm field % hence a temporary copy of the data is needed tempdata.dimord = data.dimord; tempdata.freq = data.freq; tempdata.label = data.label; tempdata.powspctrm = data.(cfg.parameter); if isfield(data, 'cfg'), tempdata.cfg = data.cfg; end tempdata = ft_freqdescriptives(tmpcfg, tempdata); data.(cfg.parameter) = tempdata.powspctrm; clear tempdata else data = ft_freqdescriptives(tmpcfg, data); end dimord = data.dimord; dimtok = tokenize(dimord, '_'); end if isfield(data, 'label') cfg.channel = ft_channelselection(cfg.channel, data.label); elseif isfield(data, 'labelcmb') cfg.channel = ft_channelselection(cfg.channel, unique(data.labelcmb(:))); end % perform channel selection but only allow this when cfg.interactive = 'no' if isfield(data, 'label') && strcmp(cfg.interactive, 'no') selchannel = ft_channelselection(cfg.channel, data.label); elseif isfield(data, 'labelcmb') && strcmp(cfg.interactive, 'no') selchannel = ft_channelselection(cfg.channel, unique(data.labelcmb(:))); end % Create time-series of small topoplots: if ~ischar(cfg.xlim) && length(cfg.xlim)>2 %&& any(ismember(dimtok, 'time')) % Switch off interactive mode: cfg.interactive = 'no'; xlims = cfg.xlim; % Iteratively call topoplotER with different xlim values: nplots = numel(xlims)-1; nyplot = ceil(sqrt(nplots)); nxplot = ceil(nplots./nyplot); for i=1:length(xlims)-1 subplot(nxplot, nyplot, i); cfg.xlim = xlims(i:i+1); ft_topoplotTFR(cfg, data); end return end % Apply baseline correction: if ~strcmp(cfg.baseline, 'no') if strcmp(xparam, 'freq') || strcmp(yparam, 'freq') data = ft_freqbaseline(cfg, data); else data = ft_timelockbaseline(cfg, data); end end % Handle the bivariate case % Check for bivariate metric with 'chan_chan' in the dimord: selchan = strmatch('chan', dimtok); isfull = length(selchan)>1; % Check for bivariate metric with a labelcmb field: haslabelcmb = isfield(data, 'labelcmb'); if (isfull || haslabelcmb) && (isfield(data, cfg.parameter) && ~strcmp(cfg.parameter, 'powspctrm')) % A reference channel is required: if ~isfield(cfg, 'refchannel') error('no reference channel is specified'); end % check for refchannel being part of selection if ~strcmp(cfg.refchannel,'gui') if haslabelcmb cfg.refchannel = ft_channelselection(cfg.refchannel, unique(data.labelcmb(:))); else cfg.refchannel = ft_channelselection(cfg.refchannel, data.label); end if (isfull && ~any(ismember(data.label, cfg.refchannel))) || ... (haslabelcmb && ~any(ismember(data.labelcmb(:), cfg.refchannel))) error('cfg.refchannel is a not present in the (selected) channels)') end end % Interactively select the reference channel if strcmp(cfg.refchannel, 'gui') % Open a single figure with the channel layout, the user can click on a reference channel h = clf; ft_plot_lay(cfg.layout, 'box', false); title('Select the reference channel by dragging a selection window, more than 1 channel can be selected...'); % add the channel information to the figure info = guidata(gcf); info.x = cfg.layout.pos(:,1); info.y = cfg.layout.pos(:,2); info.label = cfg.layout.label; guidata(h, info); % attach data to the figure with the current axis handle as a name dataname = fixname(num2str(double(gca))); setappdata(gcf,dataname,data); %set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'callback', {@select_topoplotER, cfg, data}}); set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_topoplotER, cfg}, 'event', 'WindowButtonUpFcn'}); set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_topoplotER, cfg}, 'event', 'WindowButtonDownFcn'}); set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_topoplotER, cfg}, 'event', 'WindowButtonMotionFcn'}); return end if ~isfull, % Convert 2-dimensional channel matrix to a single dimension: if isempty(cfg.directionality) sel1 = find(strcmp(cfg.refchannel, data.labelcmb(:,2))); sel2 = find(strcmp(cfg.refchannel, data.labelcmb(:,1))); elseif strcmp(cfg.directionality, 'outflow') sel1 = []; sel2 = find(strcmp(cfg.refchannel, data.labelcmb(:,1))); elseif strcmp(cfg.directionality, 'inflow') sel1 = find(strcmp(cfg.refchannel, data.labelcmb(:,2))); sel2 = []; end fprintf('selected %d channels for %s\n', length(sel1)+length(sel2), cfg.parameter); if length(sel1)+length(sel2)==0 error('there are no channels selected for plotting: you may need to look at the specification of cfg.directionality'); end data.(cfg.parameter) = data.(cfg.parameter)([sel1;sel2],:,:); data.label = [data.labelcmb(sel1,1);data.labelcmb(sel2,2)]; data.labelcmb = data.labelcmb([sel1;sel2],:); data = rmfield(data, 'labelcmb'); else % General case sel = match_str(data.label, cfg.refchannel); siz = [size(data.(cfg.parameter)) 1]; if strcmp(cfg.directionality, 'inflow') || isempty(cfg.directionality) %the interpretation of 'inflow' and 'outflow' depend on %the definition in the bivariate representation of the data %in FieldTrip the row index 'causes' the column index channel %data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(:,sel,:),2),[siz(1) 1 siz(3:end)]); sel1 = 1:siz(1); sel2 = sel; meandir = 2; elseif strcmp(cfg.directionality, 'outflow') %data.(cfg.parameter) = reshape(mean(data.(cfg.parameter)(sel,:,:),1),[siz(1) 1 siz(3:end)]); sel1 = sel; sel2 = 1:siz(1); meandir = 1; elseif strcmp(cfg.directionality, 'inflow-outflow') % do the subtraction and recursively call the function again tmpcfg = cfg; tmpcfg.directionality = 'inflow'; tmpdata = data; tmp = data.(tmpcfg.parameter); siz = [size(tmp) 1]; for k = 1:siz(3) for m = 1:siz(4) tmp(:,:,k,m) = tmp(:,:,k,m)-tmp(:,:,k,m)'; end end tmpdata.(tmpcfg.parameter) = tmp; ft_topoplotTFR(tmpcfg, tmpdata); return; elseif strcmp(cfg.directionality, 'outflow-inflow') % do the subtraction and recursively call the function again tmpcfg = cfg; tmpcfg.directionality = 'outflow'; tmpdata = data; tmp = data.(tmpcfg.parameter); siz = [size(tmp) 1]; for k = 1:siz(3) for m = 1:siz(4) tmp(:,:,k,m) = tmp(:,:,k,m)-tmp(:,:,k,m)'; end end tmpdata.(tmpcfg.parameter) = tmp; ft_topoplotTFR(tmpcfg, tmpdata); return; end end end % Get physical min/max range of x: if strcmp(cfg.xlim,'maxmin') xmin = min(data.(xparam)); xmax = max(data.(xparam)); else xmin = cfg.xlim(1); xmax = cfg.xlim(2); end % Replace value with the index of the nearest bin if ~isempty(xparam) xmin = nearest(data.(xparam), xmin); xmax = nearest(data.(xparam), xmax); end % Get physical min/max range of y: if ~isempty(yparam) if strcmp(cfg.ylim,'maxmin') ymin = min(data.(yparam)); ymax = max(data.(yparam)); else ymin = cfg.ylim(1); ymax = cfg.ylim(2); end % Replace value with the index of the nearest bin: ymin = nearest(data.(yparam), ymin); ymax = nearest(data.(yparam), ymax); end % Take subselection of channels, this only works % if the interactive mode is switched off if exist('selchannel', 'var') sellab = match_str(data.label, selchannel); label = data.label(sellab); else sellab = 1:numel(data.label); label = data.label; end if isfull sel1 = intersect(sel1, sellab); sel2 = intersect(sel2, sellab); end if ~isempty(cfg.parameter) % Make data vector with one value for each channel dat = data.(cfg.parameter); % get dimord dimensions ydim = find(strcmp(yparam, dimtok)); xdim = find(strcmp(xparam, dimtok)); zdim = setdiff(1:ndims(dat), [ydim xdim]); % and permute dat = permute(dat, [zdim(:)' ydim xdim]); if ~isempty(yparam) % time-frequency data if isfull dat = dat(sel1, sel2, ymin:ymax, xmin:xmax); dat = nanmean(nanmean(nanmean(dat, meandir), 4), 3); elseif haslabelcmb dat = dat(sellab, ymin:ymax, xmin:xmax); dat = nanmean(nanmean(dat, 3), 2); else dat = dat(sellab, ymin:ymax, xmin:xmax); dat = nanmean(nanmean(dat, 3), 2); end elseif ~isempty(cfg.component) % component data, nothing to do else % time or frequency data if isfull dat = dat(sel1, sel2, xmin:xmax); dat = nanmean(nanmean(dat, meandir), 3); elseif haslabelcmb dat = dat(sellab, xmin:xmax); dat = nanmean(dat, 2); else dat = dat(sellab, xmin:xmax); dat = nanmean(dat, 2); end end dat = dat(:); else error('cannot make selection of data'); end if isfield(data, cfg.maskparameter) % Make mask vector with one value for each channel msk = data.(cfg.maskparameter); % get dimord dimensions ydim = find(strcmp(yparam, dimtok)); xdim = find(strcmp(xparam, dimtok)); zdim = setdiff(1:ndims(dat), [ydim xdim]); % and permute msk = permute(msk, [zdim(:)' ydim xdim]); if ~isempty(yparam) % time-frequency data if isfull msk = msk(sel1, sel2, ymin:ymax, xmin:xmax); elseif haslabelcmb msk = msk(sellab, ymin:ymax, xmin:xmax); else msk = msk(sellab, ymin:ymax, xmin:xmax); end elseif ~isempty(cfg.component) % component data, nothing to do else % time or frequency data if isfull msk = msk(sel1, sel2, xmin:xmax); elseif haslabelcmb msk = msk(sellab, xmin:xmax); else msk = msk(sellab, xmin:xmax); end end if size(msk,2)>1 || size(msk,3)>1 warning('no masking possible for average over multiple latencies or frequencies -> cfg.maskparameter cleared') msk = []; end else msk = []; end % Select the channels in the data that match with the layout: [seldat, sellay] = match_str(label, cfg.layout.label); if isempty(seldat) error('labels in data and labels in layout do not match'); end dat = dat(seldat); if ~isempty(msk) msk = msk(seldat); end % Select x and y coordinates and labels of the channels in the data chanX = cfg.layout.pos(sellay,1); chanY = cfg.layout.pos(sellay,2); chanLabels = cfg.layout.label(sellay); % Get physical min/max range of z: if strcmp(cfg.zlim,'maxmin') zmin = min(dat); zmax = max(dat); elseif strcmp(cfg.zlim,'maxabs') zmin = -max(max(abs(dat))); zmax = max(max(abs(dat))); elseif strcmp(cfg.zlim,'zeromax') zmin = 0; zmax = max(dat); elseif strcmp(cfg.zlim,'minzero') zmin = min(dat); zmax = 0; else zmin = cfg.zlim(1); zmax = cfg.zlim(2); end % make comment if strcmp(cfg.comment, 'auto') comment = date; if ~isempty(xparam) if strcmp(cfg.xlim,'maxmin') comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, xparam, data.(xparam)(xmin), data.(xparam)(xmax)); else comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, xparam, data.(xparam)(xmin), data.(xparam)(xmax)); end end if ~isempty(yparam) if strcmp(cfg.ylim,'maxmin') comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, yparam, data.(yparam)(ymin), data.(yparam)(ymax)); else comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, yparam, data.(yparam)(ymin), data.(yparam)(ymax)); end end if ~isempty(cfg.parameter) comment = sprintf('%0s\n%0s=[%.3g %.3g]', comment, cfg.parameter, zmin, zmax); end cfg.comment = comment; elseif strcmp(cfg.comment, 'xlim') if strcmp(cfg.xlim,'maxmin') comment = sprintf('%0s=[%.3g %.3g]', xparam, data.(xparam)(xmin), data.(xparam)(xmax)); else comment = sprintf('%0s=[%.3g %.3g]', xparam, data.(xparam)(xmin), data.(xparam)(xmax)); end cfg.comment = comment; elseif ~ischar(cfg.comment) error('cfg.comment must be string'); end if ~strcmp(cfg.comment, 'no') && isfield(cfg,'refchannel') if iscell(cfg.refchannel) cfg.comment = sprintf('%s\nreference=%s %s', comment, cfg.refchannel{:}); else cfg.comment = sprintf('%s\nreference=%s %s', comment, cfg.refchannel); end end % Specify the x and y coordinates of the comment if strcmp(cfg.commentpos,'layout') ind_comment = strmatch('COMNT', cfg.layout.label); x_comment = cfg.layout.pos(ind_comment,1); y_comment = cfg.layout.pos(ind_comment,2); elseif strcmp(cfg.commentpos,'lefttop') x_comment = -0.7; y_comment = 0.6; HorAlign = 'left'; VerAlign = 'top'; elseif strcmp(cfg.commentpos,'leftbottom') x_comment = -0.6; y_comment = -0.6; HorAlign = 'left'; VerAlign = 'bottom'; elseif strcmp(cfg.commentpos,'middletop') x_comment = 0; y_comment = 0.75; HorAlign = 'center'; VerAlign = 'top'; elseif strcmp(cfg.commentpos,'middlebottom') x_comment = 0; y_comment = -0.7; HorAlign = 'center'; VerAlign = 'bottom'; elseif strcmp(cfg.commentpos,'righttop') x_comment = 0.65; y_comment = 0.6; HorAlign = 'right'; VerAlign = 'top'; elseif strcmp(cfg.commentpos,'rightbottom') x_comment = 0.6; y_comment = -0.6; HorAlign = 'right'; VerAlign = 'bottom'; elseif isnumeric(cfg.commentpos) x_comment = cfg.commentpos(1); y_comment = cfg.commentpos(2); HorAlign = 'left'; VerAlign = 'middle'; x_comment = 0.9*((x_comment-min(x))/(max(x)-min(x))-0.5); y_comment = 0.9*((y_comment-min(y))/(max(y)-min(y))-0.5); end % Draw topoplot cla hold on % Set ft_plot_topo specific options if strcmp(cfg.interplimits,'head') interplimits = 'mask'; else interplimits = cfg.interplimits; end if strcmp(cfg.style,'both'); style = 'surfiso'; end if strcmp(cfg.style,'straight'); style = 'surf'; end if strcmp(cfg.style,'contour'); style = 'iso'; end if strcmp(cfg.style,'fill'); style = 'isofill'; end if strcmp(cfg.style,'straight_imsat'); style = 'imsat'; end if strcmp(cfg.style,'both_imsat'); style = 'imsatiso'; end % check for nans nanInds = isnan(dat); if strcmp(cfg.interpolatenan,'yes') && any(nanInds) warning('removing NaNs from the data'); chanX(nanInds) = []; chanY(nanInds) = []; dat(nanInds) = []; if ~isempty(msk) msk(nanInds) = []; end end % Draw plot if ~strcmp(cfg.style,'blank') opt = {'interpmethod',cfg.interpolation,... 'interplim',interplimits,... 'gridscale',cfg.gridscale,... 'outline',cfg.layout.outline,... 'shading',cfg.shading,... 'isolines',cfg.contournum,... 'mask',cfg.layout.mask,... 'style',style,... 'datmask', msk}; if strcmp(style,'imsat') || strcmp(style,'imsatiso') % add clim to opt opt = [opt {'clim',[zmin zmax],'ncolors',ncolors}]; end ft_plot_topo(chanX,chanY,dat,opt{:}); elseif ~strcmp(cfg.style,'blank') ft_plot_lay(cfg.layout,'box','no','label','no','point','no') end % Plotting markers for channels and/or highlighting a selection of channels highlightchansel = []; % used for remembering selection of channels templay.outline = cfg.layout.outline; templay.mask = cfg.layout.mask; % For Highlight (channel-selection) for icell = 1:length(cfg.highlight) if ~strcmp(cfg.highlight{icell},'off') [dum labelindex] = match_str(ft_channelselection(cfg.highlightchannel{icell}, data.label), cfg.layout.label); highlightchansel = [highlightchansel; match_str(data.label,ft_channelselection(cfg.highlightchannel{icell}, data.label))]; templay.pos = cfg.layout.pos(labelindex,:); templay.width = cfg.layout.width(labelindex); templay.height = cfg.layout.height(labelindex); templay.label = cfg.layout.label(labelindex); if strcmp(cfg.highlight{icell}, 'labels') || strcmp(cfg.highlight{icell}, 'numbers') labelflg = 1; else labelflg = 0; end if strcmp(cfg.highlight{icell}, 'numbers') for ichan = 1:length(labelindex) templay.label{ichan} = num2str(match_str(data.label,templay.label{ichan})); end end ft_plot_lay(templay,'box','no','label',labelflg,'point','yes',... 'pointsymbol',cfg.highlightsymbol{icell},... 'pointcolor',cfg.highlightcolor{icell},... 'pointsize',cfg.highlightsize{icell},... 'labelsize',cfg.highlightfontsize{icell},... 'labeloffset',cfg.labeloffset) end end % for icell % For Markers (all channels) if ~strcmp(cfg.marker,'off') channelsToMark = 1:length(data.label); if strcmp(cfg.interpolatenan,'no') channelsNotMark = highlightchansel; else channelsNotMark = union(find(isnan(dat)),highlightchansel); end channelsToMark(channelsNotMark) = []; [dum labelindex] = match_str(ft_channelselection(channelsToMark, data.label),cfg.layout.label); templay.pos = cfg.layout.pos(labelindex,:); templay.width = cfg.layout.width(labelindex); templay.height = cfg.layout.height(labelindex); templay.label = cfg.layout.label(labelindex); if strcmp(cfg.marker, 'labels') || strcmp(cfg.marker, 'numbers') labelflg = 1; else labelflg = 0; end if strcmp(cfg.marker, 'numbers') for ichan = 1:length(labelindex) templay.label{ichan} = num2str(match_str(data.label,templay.label{ichan})); end end ft_plot_lay(templay,'box','no','label',labelflg,'point','yes',... 'pointsymbol',cfg.markersymbol,... 'pointcolor',cfg.markercolor,... 'pointsize',cfg.markersize,... 'labelsize',cfg.markerfontsize,... 'labeloffset',cfg.labeloffset) end if(isfield(cfg,'vector')) vecX = mean(real(data.(cfg.vector)(:,xmin:xmax)),2); vecY = mean(imag(data.(cfg.vector)(:,xmin:xmax)),2); % scale quiver relative to largest gradiometer sample k=0.15/max([max(abs(real(data.(cfg.vector)(:)))) max(abs(imag(data.(cfg.vector)(:))))]); quiver(chanX, chanY, k*vecX, k*vecY,0,'red'); end % Write comment if ~strcmp(cfg.comment,'no') if strcmp(cfg.commentpos, 'title') title(cfg.comment, 'Fontsize', cfg.fontsize); else ft_plot_text(x_comment,y_comment, cfg.comment, 'Fontsize', cfg.fontsize, 'HorizontalAlignment', 'left', 'VerticalAlignment', 'bottom'); end end % plot colorbar: if isfield(cfg, 'colorbar') if strcmp(cfg.colorbar, 'yes') colorbar; elseif ~strcmp(cfg.colorbar, 'no') colorbar('location',cfg.colorbar); end end % Set renderer if specified if ~isempty(cfg.renderer) set(gcf, 'renderer', cfg.renderer) end % The remainder of the code is meant to make the figure interactive hold on; % Set colour axis if ~strcmp(cfg.style, 'blank') caxis([zmin zmax]); end if strcmp('yes',cfg.hotkeys) % Attach data and cfg to figure and attach a key listener to the figure set(gcf, 'KeyPressFcn', {@key_sub, zmin, zmax}) end % Make the figure interactive if strcmp(cfg.interactive, 'yes') % add the channel position information to the figure % this section is required for ft_select_channel to do its work info = guidata(gcf); info.x = cfg.layout.pos(:,1); info.y = cfg.layout.pos(:,2); info.label = cfg.layout.label; guidata(gcf, info); % attach data to the figure with the current axis handle as a name dataname = fixname(num2str(double(gca))); setappdata(gcf,dataname,varargin(1:Ndata)); if any(strcmp(data.dimord, {'chan_time', 'chan_freq', 'subj_chan_time', 'rpt_chan_time', 'chan_chan_freq', 'chancmb_freq', 'rpt_chancmb_freq', 'subj_chancmb_freq'})) set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg}, 'event', 'WindowButtonUpFcn'}); set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg}, 'event', 'WindowButtonDownFcn'}); set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotER, cfg}, 'event', 'WindowButtonMotionFcn'}); elseif any(strcmp(data.dimord, {'chan_freq_time', 'subj_chan_freq_time', 'rpt_chan_freq_time', 'rpttap_chan_freq_time', 'chan_chan_freq_time', 'chancmb_freq_time', 'rpt_chancmb_freq_time', 'subj_chancmb_freq_time'})) set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg}, 'event', 'WindowButtonUpFcn'}); set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg}, 'event', 'WindowButtonDownFcn'}); set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', {@select_singleplotTFR, cfg}, 'event', 'WindowButtonMotionFcn'}); else warning('unsupported dimord "%s" for interactive plotting', data.dimord); end end % set the figure window title, but only if the user has not changed it if isempty(get(gcf, 'Name')) if isfield(cfg,'funcname') funcname = cfg.funcname; else funcname = mfilename; end if isfield(cfg,'dataname') if iscell(cfg.dataname) dataname = cfg.dataname{indx}; else dataname = cfg.dataname; end elseif nargin > 1 dataname = {inputname(2)}; for k = 2:Ndata dataname{end+1} = inputname(k+1); end else % data provided through cfg.inputfile dataname = cfg.inputfile; end if isempty(cfg.figurename) dataname_str=join_str(', ', dataname); set(gcf, 'Name', sprintf('%d: %s: %s', double(gcf), funcname, dataname_str)); set(gcf, 'NumberTitle', 'off'); else set(gcf, 'name', cfg.figurename); set(gcf, 'NumberTitle', 'off'); end end axis off hold off axis equal % add a menu to the figure, but only if the current figure does not have subplots % also, delete any possibly existing previous menu, this is safe because delete([]) does nothing delete(findobj(gcf, 'type', 'uimenu', 'label', 'FieldTrip')); if numel(findobj(gcf, 'type', 'axes')) <= 1 ftmenu = uimenu(gcf, 'Label', 'FieldTrip'); if ft_platform_supports('uimenu') % not supported by Octave uimenu(ftmenu, 'Label', 'Show pipeline', 'Callback', {@menu_pipeline, cfg}); uimenu(ftmenu, 'Label', 'About', 'Callback', @menu_about); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which is called after selecting channels in case of cfg.refchannel='gui' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_topoplotER(label, cfg, varargin) % get appdata belonging to current axis dataname = fixname(num2str(double(gca))); data = getappdata(gcf, dataname); if isfield(cfg, 'inputfile') % the reading has already been done and varargin contains the data cfg = rmfield(cfg, 'inputfile'); end cfg.refchannel = label; fprintf('selected cfg.refchannel = ''%s''\n', cfg.refchannel{:}); p = get(gcf, 'Position'); f = figure; set(f, 'Position', p); cfg.highlight = 'on'; cfg.highlightsymbol = '.'; cfg.highlightcolor = 'r'; cfg.highlightsize = 20; cfg.highlightchannel = cfg.refchannel; ft_topoplotER(cfg, data); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which is called after selecting channels in case of cfg.interactive='yes' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_singleplotER(label, cfg) if ~isempty(label) % get appdata belonging to current axis dataname = fixname(num2str(double(gca))); data = getappdata(gcf, dataname); if isfield(cfg, 'inputfile') % the reading has already been done and varargin contains the data cfg = rmfield(cfg, 'inputfile'); end cfg.xlim = 'maxmin'; cfg.channel = label; % if user specified a zlim, copy it over to the ylim of singleplot if isfield(cfg, 'zlim') cfg.ylim = cfg.zlim; cfg = rmfield(cfg, 'zlim'); end fprintf('selected cfg.channel = {'); for i=1:(length(cfg.channel)-1) fprintf('''%s'', ', cfg.channel{i}); end fprintf('''%s''}\n', cfg.channel{end}); p = get(gcf, 'Position'); f = figure; set(f, 'Position', p); ft_singleplotER(cfg, data{:}); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which is called after selecting channels in case of cfg.interactive='yes' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_singleplotTFR(label, cfg) if ~isempty(label) % get appdata belonging to current axis dataname = fixname(num2str(double(gca))); data = getappdata(gcf, dataname); if isfield(cfg, 'inputfile') % the reading has already been done and varargin contains the data cfg = rmfield(cfg, 'inputfile'); end cfg.xlim = 'maxmin'; cfg.ylim = 'maxmin'; cfg.channel = label; fprintf('selected cfg.channel = {'); for i=1:(length(cfg.channel)-1) fprintf('''%s'', ', cfg.channel{i}); end fprintf('''%s''}\n', cfg.channel{end}); p = get(gcf, 'Position'); f = figure; set(f, 'Position', p); ft_singleplotTFR(cfg, data{:}); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION which handles hot keys in the current plot %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key_sub(handle, eventdata, varargin) incr = (max(caxis)-min(caxis)) /10; % symmetrically scale color bar down by 10 percent if strcmp(eventdata.Key,'uparrow') caxis([min(caxis)-incr max(caxis)+incr]); % symmetrically scale color bar up by 10 percent elseif strcmp(eventdata.Key,'downarrow') caxis([min(caxis)+incr max(caxis)-incr]); % resort to minmax of data for colorbar elseif strcmp(eventdata.Key,'m') caxis([varargin{1} varargin{2}]); end
github
lcnbeapp/beapp-master
avw_img_write.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/avw_img_write.m
29,911
utf_8
72118d833f0cc7cdd6ebd57754009a2f
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$ $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$]'; 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_hdr_write(avw, fileprefix, machine, verbose) % AVW_HDR_WRITE - Write Analyze header file (*.hdr) % % avw_hdr_write(avw,[fileprefix],[machine],[verbose]) % % eg, avw_hdr_write(avw,'test'); % % avw - a struct with .hdr field, which itself is a struct, % containing all fields of an Analyze header. % For details, see avw_hdr_read.m % % fileprefix - a string, the filename without the .hdr extension. % If empty, may use avw.fileprefix % % 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. % % See also, AVW_HDR_READ AVW_HDR_MAKE % AVW_IMG_READ AVW_IMG_WRITE % % $Revision$ $Date: 2009/01/14 09:24:45 $ % Licence: GNU GPL, no express or implied warranties % History: 05/2002, [email protected] % 02/2003, [email protected] % - more specific data history var sizes % - 02/2003 confirmed, Darren % % 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 ~exist('machine','var'), machine = 'ieee-le'; end if verbose, version = '[$Revision$]'; fprintf('AVW_HDR_WRITE [v%s]\n',version(12:16)); tic; end %---------------------------------------------------------------------------- % Check inputs if ~exist('avw','var'), warning('...no input avw - calling avw_hdr_make\n'); avw = avw_hdr_make; elseif isempty(avw), warning('...empty input avw - calling avw_hdr_make\n'); avw = avw_hdr_make; elseif ~isfield(avw,'hdr'), warning('...empty input avw.hdr - calling avw_hdr_make\n'); avw = avw_hdr_make; end if ~isequal(avw.hdr.hk.sizeof_hdr,348), msg = sprintf('...avw.hdr.hk.sizeof_hdr must be 348!\n'); error(msg); end quit = 0; if ~exist('fileprefix','var'), if isfield(avw,'fileprefix'), if ~isempty(avw.fileprefix), fileprefix = avw.fileprefix; else, quit = 1; end else quit = 1; end if quit, helpwin avw_hdr_write; error('...no input fileprefix - see help avw_hdr_write\n\n'); return; end end if findstr('.hdr',fileprefix), % fprintf('AVW_HDR_WRITE: Removing .hdr extension from ''%s''\n',fileprefix); fileprefix = strrep(fileprefix,'.hdr',''); end %---------------------------------------------------------------------------- % MAIN if verbose, tic; end % % force volume to 4D if necessary; conforms to AVW standard. i lifted this % % code from mri_toolbox/avw_hdr_read.m and modified it just a little bit % % (using minDim = 4; etc) % minDim = 4; % currDim = double(avw.hdr.dime.dim(1)); % if ( currDim < minDim ) % % fprintf( 'Warning %s: Forcing %d dimensions in avw.hdr.dime.dim\n', ... % % mfilename, minDim ); % avw.hdr.dime.dim(1) = int16(minDim); % avw.hdr.dime.dim(currDim+2:minDim+1) = int16(1); % avw.hdr.dime.pixdim(1) = int16(minDim); % avw.hdr.dime.pixdim(currDim+2:minDim+1) = int16(1); % end; fid = fopen(sprintf('%s.hdr',fileprefix),'w',machine); if fid < 0, msg = sprintf('Cannot write to file %s.hdr\n',fileprefix); error(msg); else if verbose, fprintf('...writing %s Analyze header.\n',machine); end write_header(fid,avw,verbose); end if verbose, t=toc; fprintf('...done (%5.2f sec).\n\n',t); end 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 %---------------------------------------------------------------------------- function write_header(fid,avw,verbose) header_key(fid,avw.hdr.hk); image_dimension(fid,avw.hdr.dime); data_history(fid,avw.hdr.hist); % check the file size is 348 bytes fbytes = ftell(fid); fclose(fid); if ~isequal(fbytes,348), msg = sprintf('...file size is not 348 bytes!\n'); warning(msg); end return %---------------------------------------------------------------------------- function header_key(fid,hk) % 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'); fwrite(fid, hk.sizeof_hdr(1), 'int32'); % must be 348! data_type = sprintf('%-10s',hk.data_type); % ensure it is 10 chars fwrite(fid, hk.data_type(1:10), 'uchar'); db_name = sprintf('%-18s',hk.db_name); % ensure it is 18 chars fwrite(fid, db_name(1:18), 'uchar'); fwrite(fid, hk.extents(1), 'int32'); fwrite(fid, hk.session_error(1),'int16'); regular = sprintf('%1s',hk.regular); % ensure it is 1 char fwrite(fid, regular(1), 'uchar'); % might be uint8 %hkey_un0 = sprintf('%1s',hk.hkey_un0); % ensure it is 1 char %fwrite(fid, hkey_un0(1), 'uchar'); fwrite(fid, hk.hkey_un0(1), 'uint8'); % >Would you set hkey_un0 as char or uint8? % Really doesn't make any difference. As far as anyone here can remember, % this was just to pad to an even byte boundary for that structure. I guess % I'd suggest setting it to a uint8 value of 0 (i.e, truly zero-valued) so % that it doesn't look like anything important! % Denny <[email protected]> return %---------------------------------------------------------------------------- function image_dimension(fid,dime) %struct image_dimension % { /* off + size */ % short int dim[8]; /* 0 + 16 */ % 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 % pixdim[2] - voxel height % pixdim[3] - interslice distance % ..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 */ fwrite(fid, dime.dim(1:8), 'int16'); fwrite(fid, dime.vox_units(1:4),'uchar'); fwrite(fid, dime.cal_units(1:8),'uchar'); fwrite(fid, dime.unused1(1), 'int16'); fwrite(fid, dime.datatype(1), 'int16'); fwrite(fid, dime.bitpix(1), 'int16'); fwrite(fid, dime.dim_un0(1), 'int16'); fwrite(fid, dime.pixdim(1:8), 'float32'); fwrite(fid, dime.vox_offset(1), 'float32'); % Ensure compatibility with SPM (according to MRIcro) if dime.roi_scale == 0, dime.roi_scale = 0.00392157; end fwrite(fid, dime.roi_scale(1), 'float32'); fwrite(fid, dime.funused1(1), 'float32'); fwrite(fid, dime.funused2(1), 'float32'); fwrite(fid, dime.cal_max(1), 'float32'); fwrite(fid, dime.cal_min(1), 'float32'); fwrite(fid, dime.compressed(1), 'int32'); fwrite(fid, dime.verified(1), 'int32'); fwrite(fid, dime.glmax(1), 'int32'); fwrite(fid, dime.glmin(1), 'int32'); return %---------------------------------------------------------------------------- function data_history(fid,hist) % 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 */ descrip = sprintf('%-80s', hist.descrip); % 80 chars aux_file = sprintf('%-24s', hist.aux_file); % 24 chars originator = sprintf('%-10s', hist.originator); % 10 chars generated = sprintf('%-10s', hist.generated); % 10 chars scannum = sprintf('%-10s', hist.scannum); % 10 chars patient_id = sprintf('%-10s', hist.patient_id); % 10 chars exp_date = sprintf('%-10s', hist.exp_date); % 10 chars exp_time = sprintf('%-10s', hist.exp_time); % 10 chars hist_un0 = sprintf( '%-3s', hist.hist_un0); % 3 chars % --- % The following should not be necessary, but I actually % found one instance where it was, so this totally anal % retentive approach became necessary, despite the % apparently elegant solution above to ensuring that variables % are the right length. if length(descrip) < 80, paddingN = 80-length(descrip); padding = char(repmat(double(' '),1,paddingN)); descrip = [descrip,padding]; end if length(aux_file) < 24, paddingN = 24-length(aux_file); padding = char(repmat(double(' '),1,paddingN)); aux_file = [aux_file,padding]; end if length(originator) < 10, paddingN = 10-length(originator); padding = char(repmat(double(' '),1,paddingN)); originator = [originator, padding]; end if length(generated) < 10, paddingN = 10-length(generated); padding = char(repmat(double(' '),1,paddingN)); generated = [generated, padding]; end if length(scannum) < 10, paddingN = 10-length(scannum); padding = char(repmat(double(' '),1,paddingN)); scannum = [scannum, padding]; end if length(patient_id) < 10, paddingN = 10-length(patient_id); padding = char(repmat(double(' '),1,paddingN)); patient_id = [patient_id, padding]; end if length(exp_date) < 10, paddingN = 10-length(exp_date); padding = char(repmat(double(' '),1,paddingN)); exp_date = [exp_date, padding]; end if length(exp_time) < 10, paddingN = 10-length(exp_time); padding = char(repmat(double(' '),1,paddingN)); exp_time = [exp_time, padding]; end if length(hist_un0) < 10, paddingN = 10-length(hist_un0); padding = char(repmat(double(' '),1,paddingN)); hist_un0 = [hist_un0, padding]; end % -- if you thought that was anal, try this; % -- lets check for unusual ASCII char values! if find(double(descrip)>128), indexStrangeChar = find(double(descrip)>128); descrip(indexStrangeChar) = ' '; end if find(double(aux_file)>128), indexStrangeChar = find(double(aux_file)>128); aux_file(indexStrangeChar) = ' '; end if find(double(originator)>128), indexStrangeChar = find(double(originator)>128); originator(indexStrangeChar) = ' '; end if find(double(generated)>128), indexStrangeChar = find(double(generated)>128); generated(indexStrangeChar) = ' '; end if find(double(scannum)>128), indexStrangeChar = find(double(scannum)>128); scannum(indexStrangeChar) = ' '; end if find(double(patient_id)>128), indexStrangeChar = find(double(patient_id)>128); patient_id(indexStrangeChar) = ' '; end if find(double(exp_date)>128), indexStrangeChar = find(double(exp_date)>128); exp_date(indexStrangeChar) = ' '; end if find(double(exp_time)>128), indexStrangeChar = find(double(exp_time)>128); exp_time(indexStrangeChar) = ' '; end if find(double(hist_un0)>128), indexStrangeChar = find(double(hist_un0)>128); hist_un0(indexStrangeChar) = ' '; end % --- finally, we write the fields fwrite(fid, descrip(1:80), 'uchar'); fwrite(fid, aux_file(1:24), 'uchar'); %orient = sprintf( '%1s', hist.orient); % 1 char %fwrite(fid, orient(1), 'uchar'); fwrite(fid, hist.orient(1), 'uint8'); % see note below on char fwrite(fid, originator(1:10), 'uchar'); fwrite(fid, generated(1:10), 'uchar'); fwrite(fid, scannum(1:10), 'uchar'); fwrite(fid, patient_id(1:10), 'uchar'); fwrite(fid, exp_date(1:10), 'uchar'); fwrite(fid, exp_time(1:10), 'uchar'); fwrite(fid, hist_un0(1:3), 'uchar'); fwrite(fid, hist.views(1), 'int32'); fwrite(fid, hist.vols_added(1), 'int32'); fwrite(fid, hist.start_field(1),'int32'); fwrite(fid, hist.field_skip(1), 'int32'); fwrite(fid, hist.omax(1), 'int32'); fwrite(fid, hist.omin(1), 'int32'); fwrite(fid, hist.smax(1), 'int32'); fwrite(fid, hist.smin(1), 'int32'); 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]> % See other notes in avw_hdr_read
github
lcnbeapp/beapp-master
triangle2connectivity.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/triangle2connectivity.m
2,477
utf_8
8a536381c1a41e258adfd603a4ccba83
function [connmat] = triangle2connectivity(tri, pos) % TRIANGLE2CONNECTIVITY computes a connectivity-matrix from a triangulation. % % Use as % [connmat] = triangle2connectivity(tri) % or % [connmat] = triangle2connectivity(tri, pos) % % The input tri is an Mx3 matrix describing a triangulated surface, % containing indices to connecting vertices. The output connmat is a sparse % logical NxN matrix, with ones, where vertices are connected, and zeros % otherwise. % % If you specify the vertex positions in the second input argument as Nx3 % matrix, the output will be a sparse matrix with the lengths of the % edges between the connected vertices. % Copyright (C) 2015, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % ensure that the vertices are indexed starting from 1 if min(tri(:))==0, tri = tri + 1; end % ensure that the vertices are indexed according to 1:number of unique vertices tri = tri_reindex(tri); % create the unique edges from the triangulation edges = [tri(:,[1 2]); tri(:,[1 3]); tri(:,[2 3])]; edges = double(unique(sort([edges; edges(:,[2 1])],2), 'rows')); % fill the connectivity matrix n = size(edges,1); if nargin<2 % create sparse binary matrix connmat = sparse([edges(:,1);edges(:,2)],[edges(:,2);edges(:,1)],true(2*n,1)); else % create sparse matrix with edge lengths dpos = sqrt(sum( (pos(edges(:,1),:) - pos(edges(:,2),:)).^2, 2)); connmat = sparse([edges(:,1);edges(:,2)],[edges(:,2);edges(:,1)],[dpos(:);dpos(:)]); end function [newtri] = tri_reindex(tri) % this subfunction reindexes tri such that they run from 1:number of unique vertices newtri = tri; [srt, indx] = sort(tri(:)); tmp = cumsum(double(diff([0;srt])>0)); newtri(indx) = tmp;
github
lcnbeapp/beapp-master
ft_platform_supports.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/ft_platform_supports.m
9,557
utf_8
eb0e55d84d57e6873cce8df6cad90d96
function tf = ft_platform_supports(what,varargin) % FT_PLATFORM_SUPPORTS returns a boolean indicating whether the current platform % supports a specific capability % % Usage: % tf = ft_platform_supports(what) % tf = ft_platform_supports('matlabversion', min_version, max_version) % % The following values are allowed for the 'what' parameter: % value means that the following is supported: % % 'which-all' which(...,'all') % 'exists-in-private-directory' exists(...) will look in the /private % subdirectory to see if a file exists % 'onCleanup' onCleanup(...) % 'alim' alim(...) % 'int32_logical_operations' bitand(a,b) with a, b of type int32 % 'graphics_objects' graphics sysem is object-oriented % 'libmx_c_interface' libmx is supported through mex in the % C-language (recent Matlab versions only % support C++) % 'stats' all statistical functions in % FieldTrip's external/stats directory % 'program_invocation_name' program_invocation_name() (GNU Octave) % 'singleCompThread' start Matlab with -singleCompThread % 'nosplash' -nosplash % 'nodisplay' -nodisplay % 'nojvm' -nojvm % 'no-gui' start GNU Octave with --no-gui % 'RandStream.setGlobalStream' RandStream.setGlobalStream(...) % 'RandStream.setDefaultStream' RandStream.setDefaultStream(...) % 'rng' rng(...) % 'rand-state' rand('state') % 'urlread-timeout' urlread(..., 'Timeout', t) % 'griddata-vector-input' griddata(...,...,...,a,b) with a and b % vectors % 'griddata-v4' griddata(...,...,...,...,...,'v4'), % that is v4 interpolation support % 'uimenu' uimenu(...) if ~ischar(what) error('first argument must be a string'); end switch what case 'matlabversion' tf = is_matlab() && matlabversion(varargin{:}); case 'exists-in-private-directory' tf = is_matlab(); case 'which-all' tf = is_matlab(); case 'onCleanup' tf = is_octave() || matlabversion(7.8, Inf); case 'alim' tf = is_matlab(); case 'int32_logical_operations' % earlier version of Matlab don't support bitand (and similar) % operations on int32 tf = is_octave() || ~matlabversion(-inf, '2012a'); case 'graphics_objects' % introduced in Matlab 2014b, graphics is handled through objects; % previous versions use numeric handles tf = is_matlab() && matlabversion('2014b', Inf); case 'libmx_c_interface' % removed after 2013b tf = matlabversion(-Inf, '2013b'); case 'stats' root_dir=fileparts(which('ft_defaults')); external_stats_dir=fullfile(root_dir,'external','stats'); % these files are only used by other functions in the external/stats % directory exclude_mfiles={'common_size.m',... 'iscomplex.m',... 'lgamma.m'}; tf = has_all_functions_in_dir(external_stats_dir,exclude_mfiles); case 'program_invocation_name' % Octave supports program_invocation_name, which returns the path % of the binary that was run to start Octave tf = is_octave(); case 'singleCompThread' tf = is_matlab() && matlabversion(7.8, inf); case {'nosplash','nodisplay','nojvm'} % Only on Matlab tf = is_matlab(); case 'no-gui' % Only on Octave tf = is_octave(); case 'RandStream.setDefaultStream' tf = is_matlab() && matlabversion('2008b', '2011b'); case 'RandStream.setGlobalStream' tf = is_matlab() && matlabversion('2012a', inf); case 'randomized_PRNG_on_startup' tf = is_octave() || ~matlabversion(-Inf,'7.3'); case 'rng' % recent Matlab versions tf = is_matlab() && matlabversion('7.12',Inf); case 'rand-state' % GNU Octave tf = is_octave(); case 'urlread-timeout' tf = is_matlab() && matlabversion('2012b',Inf); case 'griddata-vector-input' tf = is_matlab(); case 'griddata-v4' tf = is_matlab() && matlabversion('2009a',Inf); case 'uimenu' tf = is_matlab(); otherwise error('unsupported value for first argument: %s', what); end % switch end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_matlab() tf = ~is_octave(); end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = is_octave() persistent cached_tf; if isempty(cached_tf) cached_tf = logical(exist('OCTAVE_VERSION', 'builtin')); end tf = cached_tf; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function tf = has_all_functions_in_dir(in_dir, exclude_mfiles) % returns true if all functions in in_dir are already provided by the % platform m_files=dir(fullfile(in_dir,'*.m')); n=numel(m_files); for k=1:n m_filename=m_files(k).name; if isempty(which(m_filename)) && ... isempty(strmatch(m_filename,exclude_mfiles)) tf=false; return; end end tf=true; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 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(6, '7.10') % is version between 6 and 7.10? (note: '7.10', not 7.10) % matlabversion(-Inf, 7.6) % is version <= 7.6? % matlabversion('2009b') % exactly 2009b % matlabversion('2008b', '2010a') % between two versions % matlabversion('2008b', Inf) % from a version onwards % etc. % % See also VERSION, VER, VERLESSTHAN % Copyright (C) 2006, Robert Oostenveld % Copyright (C) 2010, Eelke Spaak % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % this does not change over subsequent calls, making it persistent speeds it up persistent curVer if nargin<2 max = min; end if isempty(curVer) curVer = version(); end 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 end % function 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 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 % function % 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 % function
github
lcnbeapp/beapp-master
mesh_spherify.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/mesh_spherify.m
4,920
utf_8
414c768e5ef2fdc3e19da24f00f72626
function [pnt, tri] = mesh_spherify(pnt, tri, varargin) % Takes a cortical mesh and scales it so that it fits into a % unit sphere. % % This function determines the points of the original mesh that support a % convex hull and determines the radius of those points. Subsequently the % radius of the support points is interpolated onto all vertices of the % original mesh, and the vertices of the original mesh are scaled by % dividing them by this interpolated radius. % % Use as % [pnt, tri] = mesh_spherify(pnt, tri, ...) % % Optional arguments should come as key-value pairs and may include % shift = 'no', mean', 'range' % smooth = number (default = 20) % Copyright (C) 2008, Robert Oostenveld % $Id$ % give some graphical feedback for debugging fb = false; shift = ft_getopt(varargin, 'shift'); smooth = ft_getopt(varargin, 'smooth'); % set the concentration factor if ~isempty(smooth) k = smooth; else k = 100; end % the following code is for debugging if fb figure [sphere_pnt, sphere_tri] = icosahedron162; y = vonmisesfischer(5, [0 0 1], sphere_pnt); triplot(sphere_pnt, sphere_tri, y); end % this is required by the convhulln function pnt = double(pnt); npnt = size(pnt, 1); ntri = size(tri, 1); switch shift case 'mean' pnt(:,1) = pnt(:,1) - mean(pnt(:,1)); pnt(:,2) = pnt(:,2) - mean(pnt(:,2)); pnt(:,3) = pnt(:,3) - mean(pnt(:,3)); case 'range' minx = min(pnt(:,1)); miny = min(pnt(:,2)); minz = min(pnt(:,3)); maxx = max(pnt(:,1)); maxy = max(pnt(:,2)); maxz = max(pnt(:,3)); pnt(:,1) = pnt(:,1) - mean([minx maxx]); pnt(:,2) = pnt(:,2) - mean([miny maxy]); pnt(:,3) = pnt(:,3) - mean([minz maxz]); otherwise % do nothing end % determine the convex hull, especially to determine the support points tric = convhulln(pnt); sel = unique(tric(:)); % create a triangulation for only the support points support_pnt = pnt(sel,:); support_tri = convhulln(support_pnt); if fb figure triplot(support_pnt, support_tri, [], 'faces_skin'); triplot(pnt, tri, [], 'faces_skin'); alpha 0.5 end % determine the radius and thereby scaling factor for the support points support_scale = zeros(length(sel),1); for i=1:length(sel) support_scale(i) = norm(support_pnt(i,:)); end % interpolate the scaling factor for the support points to all points scale = zeros(npnt,1); for i=1:npnt u = pnt(i,:); y = vonmisesfischer(k, u, support_pnt); y = y ./ sum(y); scale(i) = y' * support_scale; end % apply the interpolated scaling to all points pnt(:,1) = pnt(:,1) ./ scale; pnt(:,2) = pnt(:,2) ./ scale; pnt(:,3) = pnt(:,3) ./ scale; % downscale the points further to make sure that nothing sticks out n = zeros(npnt,1); for i = 1:npnt n(i) = norm(pnt(i, :)); end mscale = (1-eps) / max(n); pnt = mscale * pnt; if fb figure [sphere_pnt, sphere_tri] = icosahedron162; triplot(sphere_pnt, sphere_tri, [], 'faces_skin'); triplot(pnt, tri, [], 'faces_skin'); alpha 0.5 end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % VONMISESFISCHER probability distribution % % Use as % y = vonmisesfischer(k, u, x) % where % k = concentration parameter % u = mean direction % x = direction of the points on the sphere % % The von Mises?Fisher distribution is a probability distribution on the % (p?1) dimensional sphere in Rp. If p=2 the distribution reduces to the % von Mises distribution on the circle. The distribution belongs to the % field of directional statistics. % % This implementation is based on % http://en.wikipedia.org/wiki/Von_Mises-Fisher_distribution %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = vonmisesfischer(k, u, x) % the data describes N points in P-dimensional space [n, p] = size(x); % ensure that the direction vectors are unit length u = u ./ norm(u); for i=1:n x(i,:) = x(i,:) ./ norm(x(i,:)); end % FIXME this normalisation is wrong % but it is not yet needed, so the problem is acceptable for now % Cpk = (k^((p/2)-1)) ./ ( (2*pi)^(p/2) * besseli(p/2-1, k)); Cpk = 1; y = exp(k * u * x') ./ Cpk; y = y(:); function [val] = keyval(key, varargin) % KEYVAL returns the value that corresponds to the requested key in a % key-value pair list of variable input arguments % % Use as % [val] = keyval(key, varargin) % % See also VARARGIN % Copyright (C) 2005-2007, Robert Oostenveld if length(varargin)==1 && iscell(varargin{1}) varargin = varargin{1}; end if mod(length(varargin),2) error('optional input arguments should come in key-value pairs, i.e. there should be an even number'); end keys = varargin(1:2:end); vals = varargin(2:2:end); hit = find(strcmp(key, keys)); if length(hit)==0 % the requested key was not found val = []; elseif length(hit)==1 % the requested key was found val = vals{hit}; else error('multiple input arguments with the same name'); end
github
lcnbeapp/beapp-master
select_channel_list.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/select_channel_list.m
5,924
utf_8
94982b0a4829981930c1c446e459ca7c
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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if nargin<3 titlestr = 'Select'; end pos = get(0,'DefaultFigurePosition'); pos(3:4) = [290 300]; dlg = dialog('Name', titlestr, 'Position', pos); set(gca, 'Visible', 'off'); % explicitly turn the axis off, as it sometimes appears 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
lcnbeapp/beapp-master
artifact_viewer.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/artifact_viewer.m
7,053
utf_8
102f40eaa7a02d86d35db0d6412e07ab
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 cumulated % z-value % Copyright (C) 2004-2006, Jan-Mathijs Schoffelen & Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if ishandle(cfg) % get the input variables from the handle's guidata hx = cfg; clear cfg; tmp = guidata(hx); cfg = tmp.cfg; cfg.trl = tmp.trl; artcfg = tmp.artcfg; zval = tmp.zval; artval = tmp.artval; zindx = tmp.zindx; if ~isempty(tmp.data) inputdata = tmp.data; hdr = ft_fetch_header(inputdata); else hdr = ft_read_header(cfg.headerfile); end % make a new figure figure; else if nargin == 5 hdr = ft_read_header(cfg.headerfile); elseif nargin == 6 hdr = ft_fetch_header(inputdata); % used name inputdata iso data, because data is already used later in this function end end dat.cfg = cfg; dat.artcfg = artcfg; if exist('inputdata', 'var') dat.inputdata = inputdata; 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); dat.hdr = hdr; 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
lcnbeapp/beapp-master
estimate_fwhm2.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/estimate_fwhm2.m
3,130
utf_8
195e03d1b210e939380a0b31ddd6efb0
function [source] = estimate_fwhm2(source, maxdist) % ESTIMATE_FWHM2(SOURCE, MAXDIST) % % This function computes the Gaussian fwhm of the spatial filters, according to % least-squares Gaussian fit including data points up until MAXDIST from the % locations of interest. % % This function can only deal with scalar filters. if nargin<2, maxdist = 2.5; end % maxdist should be in units of the pos in source if isempty(maxdist), maxdist = inf; end if islogical(source.inside) inside = find(source.inside); else inside = source.inside; end ninside = numel(inside); if ~isfield(source.avg, 'filter') error('the input should contain spatial filters in'); end nchan = size(source.avg.filter{inside(1)},2); ndir = size(source.avg.filter{inside(1)},1); if ndir~=1, error('only scalar filters are allowed as input'); end %get filters and positions filter = cat(1,source.avg.filter{inside}); pos = source.pos(inside,:); %get the filter correlation matrix Cmat = filter*filter'; Cmat = abs(Cmat)./sqrt(diag(Cmat)*diag(Cmat)'); fwhm = zeros(size(source.pos,1),1); onesvec = ones(ninside,1); for k = 1:ninside d = sqrt(sum( (pos-pos(k*onesvec,:)).^2, 2)); sel = d<=maxdist; s = gaussfit(Cmat(sel,k)',d(sel)'); fwhm(inside(k)) = s; end source.fwhm = fwhm; % fwhm = zeros(size(source.pos,1),3,3); % onesvec = ones(ninside,1); % for k = 1:ninside % dpos = pos-pos(k*onesvec,:); % d = sqrt(sum(dpos.^2, 2)); % sel = d<=maxdist; % [s,~] = gaussfit3D(dpos(sel,:), Cmat(sel,k)); % fwhm(inside(k),:,:) = s; % end % source.fwhm = fwhm; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fwhm] = gaussfit(dat, design) %this function performs a least-squares gaussian fit %create independent variable ivar = design.^2; dat = log(dat+eps); beta = dat*ivar'*pinv(ivar*ivar'); sigma = sqrt(-0.5./beta(:,1)); fwhm = 2.*sqrt(2.*log(2)).*sigma; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [invsigma, R] = gaussfit3D(x, y) % function for a linear least squares fit of a Gaussian function in 3D % (with a peak of 1 at (0,0,0)). % % use as % sigma = gaussfit3D(x, y) % % x = Nx3 and y = Nx1, sigma is the covariance describing the gaussian % create design matrix based in the independent variable x design = [x(:,1).^2 x(:,2).^2 x(:,3).^2 2.*(x(:,1).*x(:,2)) 2.*(x(:,1).*x(:,3)) 2.*(x(:,2).*x(:,3))]; %design = design-repmat(mean(design,1),[size(design,1) 1]); design = cat(2, design, ones(size(design,1),1)); % log-transform the dependent variable y dat = -2.*log(y+eps); % regression beta = design\dat; % residuals res = dat - design*beta; R = 1-sum(res.^2)./sum(dat.^2); % create output invsigma = [beta(1) beta(4) beta(5);beta(4) beta(2) beta(6);beta(5) beta(6) beta(3)]; %sigma = inv(invsigma); % by construction the exponent to the gaussian looks like this % % exp( -0.5.*(-x'*invsigma*x) ) % % -x'*invsigma*x = [x1 x2 x3]*[a d e [x1 % d b f x2 % e f c] x3] = % % a*x1^2+b*x2^2+c*x3^2+2d*(x1x2)+2e*(x1x3)+2f*(x2x3) % % the variables a through f correspond with the ordered beta weights
github
lcnbeapp/beapp-master
rejectvisual_summary.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/rejectvisual_summary.m
22,693
utf_8
379ccee2d011c4f5e854a071b19084bb
function [chansel, trlsel, cfg] = rejectvisual_summary(cfg, data) % SUBFUNCTION for ft_rejectvisual % determine the initial selection of trials ntrl = length(data.trial); if isequal(cfg.trials, 'all') % support specification like 'all' cfg.trials = 1:ntrl; end trlsel = false(1, ntrl); trlsel(cfg.trials) = true; % determine the initial selection of channels nchan = length(data.label); cfg.channel = ft_channelselection(cfg.channel, data.label); % support specification like 'all' chansel = false(1, nchan); chansel(match_str(data.label, cfg.channel)) = true; % compute the sampling frequency from the first two timepoints fsample = 1/mean(diff(data.time{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 info = []; info.data = data; info.cfg = cfg; info.metric = cfg.metric; info.previousmetric = 'none'; info.level = nan(nchan, ntrl); info.ntrl = ntrl; info.nchan = nchan; info.trlsel = trlsel; info.chansel = chansel; info.fsample = fsample; info.offset = offset; info.quit = 0; h = figure(); guidata(h, info); % set up display interactive = true; % make the figure large enough to hold stuff set(h, 'Position', [50 350 800 500]); % define three axes info.axes(1) = axes('position', [0.100 0.650 0.375 0.300]); % summary 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 % instructions instructions = sprintf('Drag the mouse over the channels or trials you wish to reject'); uicontrol(h, 'Units', 'normalized', 'position', [0.520 0.520 0.400 0.050], 'Style', 'text', 'HorizontalAlignment', 'left', 'backgroundcolor', get(h, 'color'), 'string', instructions, 'FontWeight', 'bold', 'ForegroundColor', 'r'); % set up radio buttons for choosing metric bgcolor = get(h, 'color'); g = uibuttongroup('Position', [0.520 0.220 0.375 0.250 ], 'bordertype', 'none', 'backgroundcolor', bgcolor); r(1) = uicontrol('Units', 'normalized', 'parent', g, 'position', [ 0.0 8/9 0.40 0.15 ], 'Style', 'Radio', 'backgroundcolor', bgcolor, 'string', 'var', 'HandleVisibility', 'off'); r(2) = uicontrol('Units', 'normalized', 'parent', g, 'position', [ 0.0 7/9 0.40 0.15 ], 'Style', 'Radio', 'backgroundcolor', bgcolor, 'String', 'min', 'HandleVisibility', 'off'); r(3) = uicontrol('Units', 'normalized', 'parent', g, 'position', [ 0.0 6/9 0.40 0.15 ], 'Style', 'Radio', 'backgroundcolor', bgcolor, 'String', 'max', 'HandleVisibility', 'off'); r(4) = uicontrol('Units', 'normalized', 'parent', g, 'position', [ 0.0 5/9 0.40 0.15 ], 'Style', 'Radio', 'backgroundcolor', bgcolor, 'String', 'maxabs', 'HandleVisibility', 'off'); r(5) = uicontrol('Units', 'normalized', 'parent', g, 'position', [ 0.0 4/9 0.40 0.15 ], 'Style', 'Radio', 'backgroundcolor', bgcolor, 'String', 'range', 'HandleVisibility', 'off'); r(6) = uicontrol('Units', 'normalized', 'parent', g, 'position', [ 0.0 3/9 0.40 0.15 ], 'Style', 'Radio', 'backgroundcolor', bgcolor, 'String', 'kurtosis', 'HandleVisibility', 'off'); r(7) = uicontrol('Units', 'normalized', 'parent', g, 'position', [ 0.0 2/9 0.40 0.15 ], 'Style', 'Radio', 'backgroundcolor', bgcolor, 'String', '1/var', 'HandleVisibility', 'off'); r(8) = uicontrol('Units', 'normalized', 'parent', g, 'position', [ 0.0 1/9 0.40 0.15 ], 'Style', 'Radio', 'backgroundcolor', bgcolor, 'String', 'zvalue', 'HandleVisibility', 'off'); r(9) = uicontrol('Units', 'normalized', 'parent', g, 'position', [ 0.0 0/9 0.40 0.15 ], 'Style', 'Radio', 'backgroundcolor', bgcolor, 'String', 'maxzvalue', '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 toggle on or off uicontrol(h, 'Units', 'normalized', 'position', [0.630 0.470 0.14 0.05], 'Style', 'text', 'HorizontalAlignment', 'left', 'backgroundcolor', get(h, 'color'), 'string', 'Toggle trial:'); uicontrol(h, 'Units', 'normalized', 'position', [0.630 0.430 0.14 0.05], 'Style', 'edit', 'HorizontalAlignment', 'left', 'backgroundcolor', [1 1 1], 'callback', @toggle_trials); uicontrol(h, 'Units', 'normalized', 'position', [0.630 0.340 0.14 0.05], 'Style', 'text', 'HorizontalAlignment', 'left', 'backgroundcolor', get(h, 'color'), 'string', 'Toggle channel:'); uicontrol(h, 'Units', 'normalized', 'position', [0.630 0.300 0.14 0.05], 'Style', 'edit', 'HorizontalAlignment', 'left', 'backgroundcolor', [1 1 1], 'callback', @toggle_channels); % editbox for trial plotting uicontrol(h, 'Units', 'normalized', 'position', [0.630 0.210 0.14 0.05], 'Style', 'text', 'HorizontalAlignment', 'left', 'backgroundcolor', get(h, 'color'), 'string', 'Plot trial:'); info.plottrltxt = uicontrol(h, 'Units', 'normalized', 'position', [0.630 0.170 0.14 0.05], 'Style', 'edit', 'HorizontalAlignment', 'left', 'backgroundcolor', [1 1 1], 'callback', @display_trial); info.badtrllbl = uicontrol(h, 'Units', 'normalized', 'position', [0.795 0.470 0.230 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.430 0.230 0.05], 'Style', 'text', 'HorizontalAlignment', 'left', 'backgroundcolor', get(h, 'color')); info.badchanlbl = uicontrol(h, 'Units', 'normalized', 'position', [0.795 0.340 0.230 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.300 0.230 0.05], 'Style', 'text', 'HorizontalAlignment', 'left', 'backgroundcolor', get(h, 'color')); % "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); % disable trial plotting if cfg.layout not present if ~isfield(info.cfg, 'layout') set(info.plottrltxt, 'Enable', 'off'); update_log(info.output_box, sprintf('NOTE: "cfg.layout" parameter required for trial plotting!')); end % 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); tmp = info.level(info.chansel, info.trlsel); if isequal(info.metric, info.previousmetric) && all(~isnan(tmp(:))) % there is no reason to recompute the metric return end 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') || strcmp(info.metric, 'maxzvalue') % cellmean and cellstd (see ft_denoise_pca) would work instead of for-loops, but they are too memory-intensive runsum = zeros(info.nchan, 1); runss = zeros(info.nchan, 1); runnum = 0; for i=1:info.ntrl dat = preproc(info.data.trial{i}, info.data.label, offset2time(info.offset(i), info.fsample, size(info.data.trial{i}, 2)), info.cfg.preproc); % not entirely sure whether info.data.time{i} is correct, so making it on the fly runsum = runsum + sum(dat, 2); runss = runss + sum(dat.^2, 2); runnum = runnum + size(dat, 2); end mval = runsum/runnum; sd = sqrt(runss/runnum - (runsum./runnum).^2); end for i=1:info.ntrl ft_progress(i/info.ntrl, 'computing metric %d of %d\n', i, info.ntrl); dat = preproc(info.data.trial{i}, info.data.label, offset2time(info.offset(i), info.fsample, size(info.data.trial{i}, 2)), info.cfg.preproc); % not entirely sure whether info.data.time{i} is correct, so making it on the fly 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); case 'maxzvalue' level(:, i) = max( ( 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.'); info.level = level; info.previousmetric = info.metric; guidata(h, info); function redraw(h) info = guidata(h); % work with a copy of the data level = info.level; [maxperchan, maxpertrl, maxperchan_all, maxpertrl_all] = set_maxper(level, info.chansel, info.trlsel, strcmp(info.metric, 'min')); % make the three figures if gcf~=h, figure(h); end % datacursormode on; set(h, 'CurrentAxes', info.axes(1)) cla(info.axes(1)); switch info.cfg.viewmode case {'remove', 'toggle'} tmp = level; tmp(~info.chansel, :) = nan; tmp(:, ~info.trlsel) = nan; imagesc(tmp); case 'hide' imagesc(level(info.chansel==1, info.trlsel==1)); if ~all(info.trlsel) set(info.axes(1), 'Xtick', []); end if ~all(info.chansel) set(info.axes(1), 'Ytick', []); end end % switch axis ij; % colorbar; title(info.cfg.method); ylabel('channel number'); xlabel('trial number'); set(h, 'CurrentAxes', info.axes(2)) cla(info.axes(2)); switch info.cfg.viewmode case 'remove' plot(maxperchan(info.chansel==1), find(info.chansel==1), '.'); xmax = max(maxperchan); xmin = min(maxperchan); ymax = info.nchan; case 'toggle' plot(maxperchan_all(info.chansel==1), find(info.chansel==1), '.'); hold on; plot(maxperchan_all(info.chansel==0), find(info.chansel==0), 'o'); hold off; xmax = max(maxperchan_all); xmin = min(maxperchan_all); ymax = info.nchan; case 'hide' xmax = max(maxperchan); xmin = min(maxperchan); ymax = sum(info.chansel==1); plot(maxperchan(info.chansel==1), 1:ymax, '.'); if ~all(info.chansel) set(info.axes(2), 'Ytick', []); end end % switch if any(info.chansel) && any(info.trlsel) % don't try to rescale the axes if they are empty % have to use 0 as lower limit because in the single channel case ylim([1 1]) will be invalid axis([0.8*xmin 1.2*xmax 0.5 ymax+0.5]); end axis ij; 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)); switch info.cfg.viewmode case 'remove' plot(find(info.trlsel==1), maxpertrl(info.trlsel==1), '.'); xmax = info.ntrl; ymax = max(maxpertrl); ymin = min(maxpertrl); case 'toggle' plot(find(info.trlsel==1), maxpertrl_all(info.trlsel==1), '.'); hold on; plot(find(info.trlsel==0), maxpertrl_all(info.trlsel==0), 'o'); hold off; xmax = info.ntrl; ymax = max(maxpertrl_all); ymin = min(maxpertrl_all); case 'hide' xmax = sum(info.trlsel==1); ymax = max(maxpertrl); ymin = min(maxpertrl); plot(1:xmax, maxpertrl(info.trlsel==1), '.'); if ~all(info.trlsel) set(info.axes(3), 'Xtick', []); end end % switch if any(info.chansel) && any(info.trlsel) % don't try to rescale the axes if they are empty % the 0.8-1.2 is needed to deal with the single trial case % note that both ymin and ymax can be negative axis([0.5 xmax+0.5 (1-sign(ymin)*0.2)*ymin (1+sign(ymax)*0.2)*ymax]); end 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 = ''; for i=find(info.chansel==0) if ~isempty(badchantxt) badchantxt = [badchantxt ', ' info.data.label{i} '(' num2str(i) ')']; else badchantxt = [info.data.label{i} '(' num2str(i) ')']; 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 try toggle = trls; info.trlsel(toggle) = ~info.trlsel(toggle); catch update_log(info.output_box, sprintf('ERROR: Trial value too large!')); uiresume; return; end % recalculate the metric compute_metric(h) 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 [junk, junk, junk, procchans] = regexp(rawchans, '([A-Za-z]+|[0-9]{4, })'); clear junk; 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 try toggle = chans; info.chansel(toggle) = ~info.chansel(toggle); catch update_log(info.output_box, sprintf('ERROR: Channel value too large!')); uiresume; return end % recalculate the metric compute_metric(h) guidata(h, info); 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, maxperchan_all, maxpertrl_all] = set_maxper(info.level, info.chansel, info.trlsel, strcmp(info.metric, 'min')); switch gca case info.axes(1) % visual selection in the summary plot is not supported case info.axes(2) % the visual selection was made in the channels plot switch info.cfg.viewmode case 'toggle' chanlabels = 1:info.nchan; toggle = ... chanlabels >= y(1) & ... chanlabels <= y(2) & ... maxperchan_all(chanlabels)' >= x(1) & ... maxperchan_all(chanlabels)' <= x(2); info.chansel(toggle) = ~info.chansel(toggle); case 'remove' chanlabels = 1:info.nchan; toggle = ... chanlabels >= y(1) & ... chanlabels <= y(2) & ... maxperchan(chanlabels)' >= x(1) & ... maxperchan(chanlabels)' <= x(2); info.chansel(toggle) = false; case 'hide' chanlabels = 1:sum(info.chansel==1); [junk, origchanlabels] = find(info.chansel==1); toggle = ... chanlabels >= y(1) & ... chanlabels <= y(2) & ... maxperchan(origchanlabels)' >= x(1) & ... maxperchan(origchanlabels)' <= x(2); info.chansel(origchanlabels(toggle)) = false; end case info.axes(3) % the visual selection was made in the trials plot switch info.cfg.viewmode case 'toggle' trllabels = 1:info.ntrl; toggle = ... trllabels >= x(1) & ... trllabels <= x(2) & ... maxpertrl_all(trllabels) >= y(1) & ... maxpertrl_all(trllabels) <= y(2); info.trlsel(toggle) = ~info.trlsel(toggle); case 'remove' trllabels = 1:info.ntrl; toggle = ... trllabels >= x(1) & ... trllabels <= x(2) & ... maxpertrl(trllabels) >= y(1) & ... maxpertrl(trllabels) <= y(2); info.trlsel(toggle) = false; case 'hide' trllabels = 1:sum(info.trlsel==1); [junk, origtrllabels] = find(info.trlsel==1); toggle = ... trllabels >= x(1) & ... trllabels <= x(2) & ... maxpertrl(origtrllabels) >= y(1) & ... maxpertrl(origtrllabels) <= y(2); info.trlsel(origtrllabels(toggle)) = false; end end % switch gca % recalculate the metric compute_metric(h); 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, maxperchan_all, maxpertrl_all] = set_maxper(level, chansel, trlsel, minflag) if minflag % take the negative maximum, i.e. the minimum level = -1 * level; end % determine the maximum value maxperchan_all = max(level, [], 2); maxpertrl_all = max(level, [], 1); % determine the maximum value over the remaining selection level(~chansel, :) = nan; level(:, ~trlsel) = nan; maxperchan = max(level, [], 2); maxpertrl = max(level, [], 1); if minflag maxperchan = -1 * maxperchan; maxpertrl = -1 * maxpertrl; maxperchan_all = -1 * maxperchan_all; maxpertrl_all = -1 * maxpertrl_all; level = -1 * level; end function display_trial(h, eventdata) info = guidata(h); update_log(info.output_box, 'Making multiplot of individual trials ...'); rawtrls = get(h, 'string'); if isempty(rawtrls) return; else spltrls = regexp(rawtrls, '\s+', 'split'); trls = []; for n = 1:length(spltrls) trls(n) = str2num(cell2mat(spltrls(n))); end end cfg_mp = []; % disable hashing of input data (speeds up things) cfg_mp.trackcallinfo = 'no'; cfg_mp.layout = info.cfg.layout; cfg_mp.channel = info.data.label(info.chansel); currfig = gcf; for n = 1:length(trls) figure() cfg_mp.trials = trls(n); cfg_mp.interactive = 'yes'; ft_multiplotER(cfg_mp, info.data); title(sprintf('Trial %i', trls(n))); end figure(currfig); update_log(info.output_box, 'Done.'); return;
github
lcnbeapp/beapp-master
rejectvisual_channel.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/rejectvisual_channel.m
9,660
utf_8
64e84accf24c4c0d5e6d8d5dd55c5d92
function [chansel, trlsel, cfg] = rejectvisual_channel(cfg, data) % SUBFUNCTION for ft_rejectvisual % determine the initial selection of trials ntrl = length(data.trial); if isequal(cfg.trials, 'all') % support specification like 'all' cfg.trials = 1:ntrl; end trlsel = false(1,ntrl); trlsel(cfg.trials) = true; % determine the initial selection of channels nchan = length(data.label); cfg.channel = ft_channelselection(cfg.channel, data.label); % support specification like 'all' chansel = false(1,nchan); chansel(match_str(data.label, cfg.channel)) = true; % compute the sampling frequency from the first two timepoints fsample = 1/mean(diff(data.time{1})); % compute the offset from the time axes offset = zeros(ntrl,1); for i=1:ntrl offset(i) = time2offset(data.time{i}, fsample); end if (isfield(cfg, 'preproc') && ~isempty(cfg.preproc)) 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, data.time{i}, cfg.preproc); end ft_progress('close'); end % 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),'interpreter','none'); hold off
github
lcnbeapp/beapp-master
triangulate_seg.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/triangulate_seg.m
4,688
utf_8
bdeb11f09693c8be1b6139bf1dec878f
function [pnt, tri] = triangulate_seg(seg, npnt, origin) % 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 origin of the sphere. % % Use as % [pnt, tri] = triangulate_seg(seg, npnt, origin) % % Input arguments: % seg = 3D-matrix (boolean) containing segmented volume. If not boolean % seg = seg(~=0); % npnt = requested number of vertices % origin = 1x3 vector specifying the location of the origin of the sphere % in voxel indices. This argument is optional. If undefined, the % origin of the sphere will be in the centre of the volume. % % Output arguments: % pnt = Nx3 matrix of vertex locations % tri = Mx3 matrix of triangles % % Seg will be checked for holes, and filled if necessary. Also, seg will be % checked to consist of a single boolean blob. If not, only the outer surface % of the largest will be triangulated. SPM is used for both the filling and % checking for multiple blobs. % % See also KSPHERE % Copyright (C) 2005-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % impose it to be boolean seg = (seg~=0); dim = size(seg); len = ceil(sqrt(sum(dim.^2))/2); if ~any(seg(:)) error('the segmentation is empty') end % define the origin if it is not provided in the input arguments if nargin<3 origin(1) = dim(1)/2; origin(2) = dim(2)/2; origin(3) = dim(3)/2; end % ensure that the seg consists of only one filled blob. % if not filled: throw a warning and fill % if more than one blob: throw a warning and use the biggest ft_hastoolbox('SPM8', 1); % look for holes seg = volumefillholes(seg); % look for >1 blob [lab, num] = spm_bwlabel(double(seg), 26); if num>1, warning('the segmented volume consists of more than one compartment, using only the biggest one for the segmentation'); for k = 1:num n(k) = sum(lab(:)==k); end [m,ix] = max(n); seg(lab~=ix) = false; end % start with a unit sphere with evenly distributed vertices [pnt, tri] = ksphere(npnt); ishollow = false; 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) + origin(1); lin(:,2) = lin(:,2) + origin(2); lin(:,3) = lin(:,3) + origin(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 lie 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); % the value along the line is expected to be 1 at first and then drop to 0 % anything else suggests that the segmentation is hollow ishollow = any(diff(int)==1); % find the last sample along the line that is inside the segmentation sel = find(int, 1, 'last'); % this is a problem if sel is empty. If so, use the edge of the volume if ~isempty(sel) % take the last point inside and average with the first point outside pnt(i,:) = lin(sel,:); else % take the edge pnt(i,:) = lin(end,:); end end if ishollow % this should not have hapened, especially not after filling the holes warning('the segmentation is not star-shaped, please check the surface mesh'); end % undo the shift of the origin from where the projection is done % pnt(:,1) = pnt(:,1) - origin(1); % pnt(:,2) = pnt(:,2) - origin(2); % pnt(:,3) = pnt(:,3) - origin(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
lcnbeapp/beapp-master
smooth_source.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/smooth_source.m
4,790
utf_8
311f6c3b9247cab7f1c9a0dc3b5ac994
function source = smooth_source(source, varargin) %[SOURCE] = SMOOTH(SOURCE, VARARGIN) % % computes location specific 3D gaussian kernels based on a FWHM estimate % source should contain the fields % fwhm, specifying for each voxel the FWHM of the smoothing kernel in the xyz-direction % pos, allowing for the units to be correct % % key-value pairs should contain % parameter = string, field to be used for the smoothing % maxdist = scalar, maximum distance for filter kernel source = ft_datatype_source(source); parameter = ft_getopt(varargin, 'parameter', 'all'); maxdist = ft_getopt(varargin, 'maxdist', []); if ischar(parameter) && strcmp(parameter, 'all') error('not yet implemented'); elseif ischar(parameter) parameter = {parameter}; end if isempty(maxdist) maxdist = inf; end if islogical(source.inside) inside = find(source.inside); else inside = source.inside; end ninside = numel(inside); if isfield(source, 'fwhm') fwhm = source.fwhm(inside,:,:); else error('the input data should contain an ''fwhm'' field'); end dat = cell(1,numel(parameter)); for k = 1:numel(parameter) dat{k} = getsubfield(source, parameter); dat{k} = dat{k}(inside,:); end pos = source.pos(inside,:); sigma = zeros(ninside, 3, 3); if numel(fwhm)==ninside sigma(:,1,1) = (fwhm./(2.*sqrt(2.*log(2)))).^2; sigma(:,2,2) = (fwhm./(2.*sqrt(2.*log(2)))).^2; sigma(:,3,3) = (fwhm./(2.*sqrt(2.*log(2)))).^2; else % this should account for more fancy kernels error('not yet implemented'); end tmp = cell(1,numel(parameter)); for m = 1:numel(tmp) tmp{m} = zeros(size(dat{k})); end for k = 1:ninside thispos = pos(k,:); dpos = pos - thispos(ones(ninside,1),:); sel = sqrt(sum(dpos.^2,2))<=maxdist; krn = gaussian3d(squeeze(sigma(k,:,:)), dpos(sel,:)); krn = krn./sum(krn); for m = 1:numel(dat) tmp{m}(k,:) = krn'*dat{m}(sel,:); end end smoothdat = zeros(size(source.pos,1),size(tmp{1},2)); for m = 1:numel(tmp) smoothdat(inside,:) = tmp{m}; source = setsubfield(source, [parameter{m},'smooth'], smoothdat); end %--------------------------------------- function [output] = gaussian3d(C, x, y, z) % [OUTPUT] = GAUSSIAN3D(C, x, y, z) computes a 3D gaussian volume, as % specified by the covariance matrix C. x,y,z specify the x, y, and z % distance to the center of the gaussian if nargin==2 && size(x,2)==3, do3Dvol = false; elseif nargin==2 y = x; z = x; do3Dvol = true; else do3Dvol = true; end if do3Dvol lx = numel(x); ly = numel(y); lz = numel(z); x = reshape(x, [lx 1 1]); y = reshape(y, [1 ly 1]); z = reshape(z, [1 1 lz]); rx = ones(1,lx); ry = ones(1,ly); rz = ones(1,lz); xy = x(:,ry,:).*y(rx,:,:); xz = x(:,:,rz).*z(rx,:,:); yz = y(:,:,rz).*z(:,ry,:); xsq = x.^2; ysq = y.^2; zsq = z.^2; %regularize a bit if necessary ev = eig(C); if ev(3)/ev(1)>1e12, s = svd(C); C = C+eye(size(C)).*0.001.*s(1); else end detC = det(C); invC = inv(C); A = 1/((2*pi)^1.5*sqrt(detC)); c11 = -0.5.*invC(1,1).*xsq; c12 = -invC(1,2).*xy; c13 = -invC(1,3).*xz; c22 = -0.5.*invC(2,2).*ysq; c23 = -invC(2,3).*yz; c33 = -0.5.*invC(3,3).*zsq; %output = A*exp(-0.5*(repmat(c11.*x.^2, [1 ly lz]) + ... % repmat(c22.*y.^2, [lx 1 ly]) + ... % repmat(c33.*z.^2, [lx ly 1]) + ... % repmat(2.*c12.*xy, [1 1 lz]) + ... % repmat(2.*c13.*xz, [1 ly 1]) + ... % repmat(2.*c23.*yz, [lx 1 1]))); %output = A*exp(-0.5*(c11.*xsq(:,ones(1,ly),ones(1,lz)) + ... % c22.*ysq(ones(1,lx),:,ones(1,lz)) + ... % c33.*zsq(ones(1,lx),ones(1,ly),:) + ... % 2.*c12.*xy(:,:,ones(1,lz)) + ... % 2.*c13.*xz(:,ones(1,ly),:) + ... % 2.*c23.*yz(ones(1,lx),:,:))); %output = A*exp((c11(:,ry,rz) + ... % c22(rx,:,rz) + ... % c33(rx,ry,:) + ... % c12(:,:,rz) + ... % c13(:,ry,:) + ... % c23(rx,:,:))); %c12 = c12+c11(:,ry); %c23 = c23+c22(:,:,rz); %c13 = c13+c33(rx,:,:); % %output = A*exp( c12(:,:,rz) + ... % c13(:,ry,:) + ... % c23(rx,:,:)); c12 = exp(c12+c11(:,ry)); c23 = exp(c23+c22(:,:,rz)); c13 = exp(c13+c33(rx,:,:)); output = A*c12(:,:,rz).*c13(:,ry,:).*c23(rx,:,:); else % treat as a Nx3 list of x,y,z distances, and output Nx1 kernel %regularize a bit if necessary ev = eig(C); if ev(3)/ev(1)>1e12, s = svd(C); C = C+eye(size(C)).*0.001.*s(1); else end detC = det(C); invC = inv(C); A = 1/((2*pi)^1.5*sqrt(detC)); % efficiently compute x*invC*x' sandwich = x(:,1).^2.*invC(1,1)+x(:,2).^2.*invC(2,2)+x(:,3).^2.*invC(3,3)+... x(:,1).*x(:,2).*invC(1,2).*2 + ... x(:,1).*x(:,3).*invC(1,3).*2 + ... x(:,2).*x(:,3).*invC(2,3).*2; output = A.*exp(-0.5.*sandwich); end
github
lcnbeapp/beapp-master
mesh2edge.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/mesh2edge.m
3,713
utf_8
410baaa2ca114acab82443de9a844a68
function [newbnd] = mesh2edge(bnd) % MESH2EDGE finds the edge lines from a triangulated mesh or the edge % surfaces from a tetrahedral or hexahedral mesh. An edge is defined as an % element that does not border any other element. This also implies that a % closed triangulated surface has no edges. % % Use as % [edge] = mesh2edge(mesh) % % See also POLY2TRI % Copyright (C) 2013-2015, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ if isfield(bnd, 'tri') % make a list of all edges edge1 = bnd.tri(:, [1 2]); edge2 = bnd.tri(:, [2 3]); edge3 = bnd.tri(:, [3 1]); edge = cat(1, edge1, edge2, edge3); elseif isfield(bnd, 'tet') % make a list of all triangles that form the tetraheder tri1 = bnd.tet(:, [1 2 3]); tri2 = bnd.tet(:, [2 3 4]); tri3 = bnd.tet(:, [3 4 1]); tri4 = bnd.tet(:, [4 1 2]); edge = cat(1, tri1, tri2, tri3, tri4); elseif isfield(bnd, 'hex') % make a list of all "squares" that form the cube/hexaheder % FIXME should be checked, this is impossible without a drawing square1 = bnd.hex(:, [1 2 3 4]); square2 = bnd.hex(:, [5 6 7 8]); square3 = bnd.hex(:, [1 2 6 5]); square4 = bnd.hex(:, [2 3 7 6]); square5 = bnd.hex(:, [3 4 8 7]); square6 = bnd.hex(:, [4 1 5 8]); edge = cat(1, square1, square2, square3, square4, square5, square6); end % isfield(bnd) % soort all polygons in the same direction % keep the original as "edge" and the sorted one as "sedge" sedge = sort(edge, 2); % % find the edges that are not shared -> count the number of occurences % n = size(sedge,1); % occurences = ones(n,1); % for i=1:n % for j=(i+1):n % if all(sedge(i,:)==sedge(j,:)) % occurences(i) = occurences(i)+1; % occurences(j) = occurences(j)+1; % end % end % end % % % make the selection in the original, not the sorted version of the edges % % otherwise the orientation of the edges might get flipped % edge = edge(occurences==1,:); % find the edges that are not shared indx = findsingleoccurringrows(sedge); edge = edge(indx, :); % replace pnt by pos bnd = fixpos(bnd); % the naming of the output edges depends on what they represent newbnd.pos = bnd.pos; if isfield(bnd, 'tri') % these have two vertices in each edge element newbnd.line = edge; elseif isfield(bnd, 'tet') % these have three vertices in each edge element newbnd.tri = edge; elseif isfield(bnd, 'hex') % these have four vertices in each edge element newbnd.poly = edge; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION, see http://bugzilla.fcdonders.nl/show_bug.cgi?id=1833#c12 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function indx = findsingleoccurringrows(X) [X, indx] = sortrows(X); sel = any(diff([X(1,:)-1; X],1),2) & any(diff([X; X(end,:)+1],1),2); indx = indx(sel); function indx = finduniquerows(X) [X, indx] = sortrows(X); sel = any(diff([X(1,:)-1; X],1),2); indx = indx(sel);
github
lcnbeapp/beapp-master
browse_simpleFFT.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/browse_simpleFFT.m
4,727
utf_8
2800cf4a6b4a130e6fd058b508f2b513
function browse_simpleFFT(cfg, data) % BROWSE_SIMPLEFFT is a helper function for FT_DATABROWSER that shows a % simple FFT of the data. % % Included are a button to switch between log and non-log space, and a % selection button to deselect channels, for the purpose of zooming in on % bad channels. % % See also BROWSE_MOVIEPLOTER, BROWSE_TOPOPLOTER, BROWSE_MULTIPLOTER, BROWSE_TOPOPLOTVAR, BROWSE_SIMPLEFFT % Copyright (C) 2011-2014, Roemer van der Meij % call ft_freqanalysis on data cfgfreq = []; cfgfreq.method = 'mtmfft'; cfgfreq.taper = 'boxcar'; freqdata = ft_freqanalysis(cfgfreq, data); % remove zero-bin for plotting if freqdata.freq(1) == 0 freqdata.freq = freqdata.freq(2:end); freqdata.powspctrm = freqdata.powspctrm(:, 2:end); end %%% FIXME: it would be nice to use ft_singleplotER for everything below, %%% this would mean that ft_singleplotER needs to get lin/log buttons % make figure window for fft ffth = figure('name', cfg.figurename, 'numbertitle', 'off', 'units', 'normalized', 'toolbar', 'figure'); % set button button_x = uicontrol('tag', 'semilogx', 'parent', ffth, 'units', 'normalized', 'style', 'checkbox', 'string', 'log10(frequency)', 'position', [0.87, 0.75 , 0.12, 0.05], 'value', true, 'callback', {@togglex}, 'backgroundcolor', [.8 .8 .8]); button_y = uicontrol('tag', 'semilogy', 'parent', ffth, 'units', 'normalized', 'style', 'checkbox', 'string', 'log10(power)', 'position', [0.87, 0.60 , 0.12, 0.05], 'value', true, 'callback', {@toggley}, 'backgroundcolor', [.8 .8 .8]); button_chansel = uicontrol('tag', 'chansel', 'parent', ffth, 'units', 'normalized', 'style', 'pushbutton', 'string', 'select channels', 'position', [0.87, 0.45 , 0.12, 0.10], 'callback', {@selectchan_fft_cb}); % put dat in fig (sparse) fftopt = []; fftopt.freqdata = freqdata; fftopt.chancolors = cfg.chancolors; fftopt.chansel = 1:numel(data.label); fftopt.semilogx = true; fftopt.semilogy = true; setappdata(ffth, 'fftopt', fftopt); % draw fig draw_simple_fft_cb(button_chansel); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function togglex(h, eventdata) ffth = get(h, 'parent'); fftopt = getappdata(ffth, 'fftopt'); fftopt.semilogx = ~fftopt.semilogx; setappdata(ffth, 'fftopt', fftopt); draw_simple_fft_cb(h) function toggley(h, eventdata) ffth = get(h, 'parent'); fftopt = getappdata(ffth, 'fftopt'); fftopt.semilogy = ~fftopt.semilogy; setappdata(ffth, 'fftopt', fftopt); draw_simple_fft_cb(h) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function selectchan_fft_cb(h, eventdata) ffth = get(h, 'parent'); fftopt = getappdata(ffth, 'fftopt'); % open chansel dialog chansel = select_channel_list(fftopt.freqdata.label, fftopt.chansel, 'select channels for viewing power'); % output data fftopt.chansel = chansel; setappdata(ffth, 'fftopt', fftopt); draw_simple_fft_cb(h) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function draw_simple_fft_cb(h, eventdata) ffth = get(h, 'parent'); fftopt = getappdata(ffth, 'fftopt'); % clear axis (for switching) cla % toggle log10 or not if fftopt.semilogx freq = log10(fftopt.freqdata.freq); else freq = fftopt.freqdata.freq; end if fftopt.semilogy dat = log10(fftopt.freqdata.powspctrm); else dat = fftopt.freqdata.powspctrm; end % select data and chanel colors chancolors = fftopt.chancolors(fftopt.chansel, :); dat = dat(fftopt.chansel, :); % plot using specified colors set(0, 'currentFigure', ffth) for ichan = 1:size(dat, 1) color = chancolors(ichan, :); ft_plot_vector(freq, dat(ichan, :), 'box', false, 'color', color) end minx = min(freq); maxx = max(freq); miny = min(dat(:)); maxy = max(dat(:)); yrange = maxy-miny; axis([minx maxx miny-yrange*0.1 maxy+yrange*.01]) if fftopt.semilogx xlabel('log10(frequency)') else xlabel('frequency') end if fftopt.semilogy ylabel('log10(power)') else ylabel('power') end set(gca, 'Position', [0.13 0.11 0.725 0.815])
github
lcnbeapp/beapp-master
prepare_mesh_manual.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/prepare_mesh_manual.m
32,788
utf_8
7e4f36eceea55290e67695f34f02b83c
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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % FIXME: control slice's cmap referred to abs values % FIXME: clean structure slicedata % FIXME: check function assign3dpoints global obj mri = ft_checkdata(mri, 'datatype', {'volume', 'segmentation'}, 'hasunit', 'yes'); 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 % constants CONTROL_WIDTH = 0.10; CONTROL_HEIGHT = 0.075; CONTROL_HOFFSET = 0.8; CONTROL_VOFFSET = 0.6; % control buttons uicontrol('tag', 'view', 'parent', fig, 'units', 'normalized', 'style', 'radiobutton', 'string', 'View', 'value', 1, 'callback', @which_task1); ft_uilayout(fig, 'tag', 'view', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET+4*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); uicontrol('tag', 'ins', 'parent', fig, 'units', 'normalized', 'style', 'radiobutton', 'string', 'Ins', 'value', 0, 'callback', @which_task2); ft_uilayout(fig, 'tag', 'ins', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET+2.75*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); uicontrol('tag', 'del', 'parent', fig, 'units', 'normalized', 'style', 'radiobutton', 'string', 'Del', 'value', 0, 'callback', @which_task3); ft_uilayout(fig, 'tag', 'del', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET+2.75*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+CONTROL_WIDTH); uicontrol('tag', 'slice', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'slice', 'value', [], 'callback', []); ft_uilayout(fig, 'tag', 'slice', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET+1.25*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); uicontrol('tag', 'min', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', '<', 'value', [], 'callback', @cb_btn); ft_uilayout(fig, 'tag', 'min', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET+1*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); uicontrol('tag', 'max', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', '>', 'value', [], 'callback', @cb_btn); ft_uilayout(fig, 'tag', 'max', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET+1*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+CONTROL_WIDTH); uicontrol('tag', 'brightness', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'brightness', 'value', [], 'callback', []); ft_uilayout(fig, 'tag', 'brightness', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET-0.75*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); uicontrol('tag', 'plus', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', '+', 'value', [], 'callback', @cb_btn); ft_uilayout(fig, 'tag', 'plus', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-1*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); uicontrol('tag', 'minus', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', '-', 'value', [], 'callback', @cb_btn); ft_uilayout(fig, 'tag', 'minus', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-1*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+CONTROL_WIDTH); uicontrol('tag', 'toggle axes', 'parent', fig, 'units', 'normalized', 'style', 'checkbox', 'string', 'axes', 'value', 0, 'callback', @cb_redraw); ft_uilayout(fig, 'tag', 'toggle axes', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET-2.5*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); uicontrol('tag', 'plane', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'plane', 'value', [], 'callback', []); ft_uilayout(fig, 'tag', 'plane', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-3.5*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); uicontrol('tag', 'one', 'parent', fig, 'units', 'normalized', 'style', 'radiobutton', 'string', 'jk', 'value', 0, 'callback', @cb_btnp1); ft_uilayout(fig, 'tag', 'one', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-3.5*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+CONTROL_WIDTH); uicontrol('tag', 'two', 'parent', fig, 'units', 'normalized', 'style', 'radiobutton', 'string', 'ik', 'value', 0, 'callback', @cb_btnp2); ft_uilayout(fig, 'tag', 'two', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-4*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); uicontrol('tag', 'three', 'parent', fig, 'units', 'normalized', 'style', 'radiobutton', 'string', 'ij', 'value', 0, 'callback', @cb_btnp3); ft_uilayout(fig, 'tag', 'three', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-4*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+CONTROL_WIDTH); uicontrol('tag', 'mesh', 'parent', fig, 'units', 'normalized', 'style', 'text', 'string', 'mesh', 'value', [], 'callback', []); ft_uilayout(fig, 'tag', 'mesh', 'BackgroundColor', [0.8 0.8 0.8], 'width', 2*CONTROL_WIDTH, 'height', CONTROL_HEIGHT, 'vpos', CONTROL_VOFFSET-5.75*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); uicontrol('tag', 'smoothm', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'smooth', 'value', [], 'callback', @smooth_mesh); ft_uilayout(fig, 'tag', 'smoothm', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-6*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); uicontrol('tag', 'viewm', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'view', 'value', [], 'callback', @view_mesh); ft_uilayout(fig, 'tag', 'viewm', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-6*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+CONTROL_WIDTH); uicontrol('tag', 'cancel', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'cancel', 'value', [], 'callback', @cancel_mesh); ft_uilayout(fig, 'tag', 'cancel', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-6.5*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET); uicontrol('tag', 'ok', 'parent', fig, 'units', 'normalized', 'style', 'pushbutton', 'string', 'ok', 'value', [], 'callback', @cb_btn); ft_uilayout(fig, 'tag', 'ok', 'BackgroundColor', [0.8 0.8 0.8], 'width', CONTROL_WIDTH, 'height', CONTROL_HEIGHT/2, 'vpos', CONTROL_VOFFSET-6.5*CONTROL_HEIGHT, 'hpos', CONTROL_HOFFSET+CONTROL_WIDTH); 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) % % 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
lcnbeapp/beapp-master
moviefunction.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/moviefunction.m
45,773
utf_8
556b05a7a84b6579fadc1c643c5f24f9
function moviefunction(cfg, varargin) % we need cfg.plotfun to plot the data % data needs to be 3D, N x time x freq (last can be singleton) % N needs to correspond to number of vertices (channels, gridpoints, etc) % new UI artwork % % [main window] -------------------------------------\ % | [uipanel: plot] | [uipanel: colormap] | % | <80%> ^70%v | <20%> | % | [axes: mainaxes] | [axes: coloraxes] | % | [axes: subaxes] | | % | | | % | | | % | | | % | | | % | | | % | | | % | | | % | | | % | | | % | | | % | |[Checkbox: automatic]| % | |[Checkbox: symmetric]| % |--[uipanel: control] <100%>-----------------------| % | [Button:Go] [Checkbox:Rec] | % | [Slider: frequency] | % | [Slider: time] | % | [TextField: speed] | % \--------------------------------------------------/ % % Right click on mainaxes: % rotation options (+automatic), zooming options, open subplot (new subaxes added) % start, stop, record, time, freq, colorbar % Left click on subaxes: dragging it around % Right click on subaxes: close % % Consider following neat extras % new figure for zooming and and rotation timing options during playback % add an intro a la Jan-Mathijs for source, similar for normal topos % make panels foldable (like on mobile devices) % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'}); cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'funparameter'}); cfg = ft_checkconfig(cfg, 'renamed', {'parameter', 'funparameter'}); cfg = ft_checkconfig(cfg, 'renamed', {'mask', 'maskparameter'}); cfg = ft_checkconfig(cfg, 'renamed', {'framespersec', 'framerate'}); cfg = ft_checkconfig(cfg, 'deprecated', {'xparam'}); cfg = ft_checkconfig(cfg, 'forbidden', {'yparam'}); % set default cfg settings cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin'); cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin'); cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin'); cfg.xparam = ft_getopt(cfg, 'xparam', 'time'); cfg.yparam = ft_getopt(cfg, 'yparam', []); cfg.maskparameter = ft_getopt(cfg, 'maskparameter'); cfg.inputfile = ft_getopt(cfg, 'inputfile', []); cfg.moviefreq = ft_getopt(cfg, 'moviefreq', []); cfg.movietime = ft_getopt(cfg, 'movietime', []); cfg.movierpt = ft_getopt(cfg, 'movierpt', 1); for i=1:numel(varargin) if ~isempty(cfg.yparam) && ~isfield(varargin{i}, 'freq') error('data argument %i does not have a .freq field, while all former had', i); elseif isempty(cfg.yparam) && isfield(varargin{i}, 'freq') cfg.yparam = 'freq'; else cfg.yparam = []; end end % set guidata flags opt = []; opt.valx = 1; opt.valy = 1; opt.valz = 1; opt.record = ~istrue(ft_getopt(cfg, 'interactive', 'yes')); opt.framesfile = ft_getopt(cfg, 'framesfile', []); opt.samperframe = ft_getopt(cfg, 'samperframe', 1); opt.framerate = ft_getopt(cfg, 'framerate', 5); opt.fixedframesfile = ~isempty(opt.framesfile); opt.xvalues = varargin{1}.(cfg.xparam); % below consistency is checked if ~isempty(cfg.yparam) opt.yvalues = varargin{i}.(cfg.yparam); % below consistency is checked else opt.yvalues = []; end % check data options and consistency Ndata = numel(varargin); for i = 1:Ndata opt.issource(i) = ft_datatype(varargin{i}, 'source'); opt.isfreq(i) = ft_datatype(varargin{i}, 'freq'); opt.istimelock(i) = ft_datatype(varargin{i}, 'timelock'); if opt.issource(i)+opt.isfreq(i)+opt.istimelock(i) ~= 1 error('data argument %i cannot be definitely identified as frequency, timelock or source data', i); end end if Ndata>1, if all(opt.issource==1), % this is allowed maybe in the future: multiple source input arguments error('currently, not more than 1 data argument is allowed, unless one of them is a parcellation, and the other a channel level structure'); elseif all(opt.isfreq==1), % this is allowed maybe in the future: multiple freq input arguments error('currently, not more than 1 data argument is allowed, unless one of them is a parcellation, and the other a channel level structure'); elseif all(opt.istimelock==1), % this is allowed maybe in the future: multiple timelock input arguments error('currently, not more than 1 data argument is allowed, unless one of them is a parcellation, and the other a channel level structure'); elseif Ndata==2 && sum(opt.issource==1) % this may be allowed, provided the source data is a parcellation and % the other argument a parcellated data structure if ~ft_datatype(varargin{opt.issource}, 'parcellation') error('the source data structure should be a parcellation'); end end end % set the funparameter if any(opt.isfreq) opt.funparameter = ft_getopt(cfg, 'funparameter', 'powspctrm'); % use power as default elseif any(opt.istimelock) opt.funparameter = ft_getopt(cfg, 'funparameter', 'avg'); % use power as default elseif any(opt.issource) % FIXME a call to ft_checkdata wouldn't hurt here :-) opt.funparameter = ft_getopt(cfg, 'funparameter', 'avg.pow'); % use power as default end if any(opt.issource) && (any(opt.isfreq) || any(opt.istimelock)) opt.anatomy = varargin{opt.issource}; opt.ismesh = isfield(opt.anatomy, 'tri'); opt.isvolume = isfield(opt.anatomy, 'dim'); varargin = varargin(~opt.issource); opt.dat{1} = getsubfield(varargin{1}, opt.funparameter); funtok = tokenize(opt.funparameter, '.'); opt.dimord = getdimord(varargin{1}, funtok{end}); elseif any(opt.issource) opt.anatomy = varargin{opt.issource}; opt.ismesh = isfield(opt.anatomy, 'tri'); opt.isvolume = isfield(opt.anatomy, 'dim'); opt.dat{1} = getsubfield(varargin{opt.issource}, opt.funparameter); funtok = tokenize(opt.funparameter, '.'); opt.dimord = getdimord(varargin{1}, funtok{end}); else opt.layout = ft_prepare_layout(cfg); % let ft_prepare_layout do the error handling for now % ensure that the data in all inputs has the same channels, time-axis, etc. tmpcfg = keepfields(cfg, {'frequency', 'latency', 'channel'}); [varargin{:}] = ft_selectdata(tmpcfg, varargin{:}); % restore the provenance information [cfg, varargin{:}] = rollback_provenance(cfg, varargin{:}); [opt.seldat, opt.sellay] = match_str(varargin{1}.label, opt.layout.label); opt.chanx = opt.layout.pos(opt.sellay,1); opt.chany = opt.layout.pos(opt.sellay,2); for i = 1:numel(varargin) opt.dat{i} = getsubfield(varargin{i}, opt.funparameter); end opt.dimord = getdimord(varargin{1}, opt.funparameter); end dimtok = tokenize(opt.dimord, '_'); if any(strcmp(dimtok, 'rpt') | strcmp(dimtok, 'subj')) error('the input data cannot contain trials or subjects, please average first using ft_selectdata'); end opt.ydim = find(strcmp(cfg.yparam, dimtok)); opt.xdim = find(strcmp(cfg.xparam, dimtok)); opt.zdim = setdiff(1:ndims(opt.dat{1}), [opt.ydim opt.xdim]); if opt.zdim ~=1 error('input %i data does not have the correct format of N x time (x freq)', i); end % permute the data matrix for i = 1:numel(opt.dat) opt.dat{i} = permute(opt.dat{i}, [opt.zdim(:)' opt.xdim opt.ydim]); end opt.xdim = 2; if ~isempty(cfg.yparam) opt.ydim = 3; else opt.ydim = []; end % get the mask for i = 1:numel(varargin) if ~isempty(cfg.maskparameter) && ischar(cfg.maskparameter) opt.mask{i} = double(getsubfield(varargin{i}, cfg.maskparameter)~=0); else opt.mask{i} = ones(size(opt.dat{i})); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % draw the figure with the GUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% opt = createGUI(opt); if isempty(cfg.yparam) % set(opt.handles.label.yparam, 'Visible', 'off'); % set(opt.handles.slider.yparam, 'Visible', 'off'); % opt.yparam = ''; else opt.yparam = [upper(cfg.yparam(1)) lower(cfg.yparam(2:end))]; set(opt.handles.label.yparam, 'String', opt.yparam); end opt.xparam = [upper(cfg.xparam(1)) lower(cfg.xparam(2:end))]; set(opt.handles.label.xparam, 'String', opt.xparam); % set timer opt.timer = timer; set(opt.timer, 'timerfcn', {@cb_timer, opt.handles.figure}, 'period', 0.1, 'executionmode', 'fixedSpacing'); opt = plot_geometry(opt); opt = plot_other(opt); opt.speed = 1; guidata(opt.handles.figure, opt); % init first screen cb_slider(opt.handles.figure); %uicontrol(opt.handles.colorbar); if strcmp(cfg.zlim, 'maxmin') set(opt.handles.checkbox.automatic, 'Value', 1) set(opt.handles.checkbox.symmetric, 'Value', 0) cb_colorbar(opt.handles.figure); elseif strcmp(cfg.zlim, 'maxabs') set(opt.handles.checkbox.automatic, 'Value', 1) set(opt.handles.checkbox.symmetric, 'Value', 1) cb_colorbar(opt.handles.figure); else set(opt.handles.checkbox.automatic, 'Value', 0) set(opt.handles.checkbox.symmetric, 'Value', 0) cb_colorbar(opt.handles.figure, cfg.zlim); end if opt.record opt.record = false; opt.quit = true; guidata(opt.handles.figure, opt); cb_recordbutton(opt.handles.button.record); else opt.quit = false; guidata(opt.handles.figure, opt); end end %% % ************************************************************** % ********************* CREATE GUI ***************************** % ************************************************************** function opt = createGUI(opt) %% main figure opt.handles.figure = figure( ... 'Units', 'normalized', ... 'Name', 'ft_movieplot',... 'Menu', 'none', ... 'Toolbar', 'figure', ... 'NumberTitle', 'off', ... 'UserData', [], ... 'Tag', 'mainFigure', ... 'Visible', 'on', ... 'windowbuttondownfcn', @cb_getposition); %'WindowButtonUpFcn', @cb_stopDrag, ... %% panels clf % visualization panel for the geometrical information opt.handles.panel.visualization_geometry = uipanel(... 'tag', 'mainPanels1', ... % tag according to position 'parent', opt.handles.figure, ... 'units', 'normalized', ... 'title', 'Visualization_geometry', ... 'clipping', 'on', ... 'visible', 'on'); % rearrange ft_uilayout(opt.handles.figure, ... 'tag', 'mainPanels1', ... 'backgroundcolor', [.8 .8 .8], ... 'hpos', 'auto', ... 'vpos', .15, ... 'halign', 'left', ... 'width', 1, ... 'height', 0.1); % visualization panel for the non-geometrical information opt.handles.panel.visualization = uipanel(... 'tag', 'mainPanels2', ... % tag according to position 'parent', opt.handles.figure, ... 'units', 'normalized', ... 'title', 'Visualization', ... 'clipping', 'on', ... 'visible', 'on'); % rearrange ft_uilayout(opt.handles.figure, ... 'tag', 'mainPanels2', ... 'backgroundcolor', [.8 .8 .8], ... 'hpos', 'auto', ... 'vpos', .55, ... 'halign', 'left', ... 'width', 0.5, ... 'height', 0.1); % settings panel (between different views can be switched) % opt.handles.panel.view = uipanel(... % 'tag', 'sidePanels', ... % tag according to position % 'parent', opt.handles.figure,... % 'units', 'normalized', ... % 'title', 'View',... % 'clipping','on',... % 'visible', 'on'); % settings panel () opt.handles.panel.settings = uipanel(... 'tag', 'sidePanels', ... % tag according to position 'parent', opt.handles.figure, ... 'units', 'normalized', ... 'title', 'Settings', ... 'clipping', 'on', ... 'visible', 'on'); % rearrange panel ft_uilayout(opt.handles.figure, ... 'tag', 'sidePanels', ... 'backgroundcolor', [.8 .8 .8], ... 'hpos', 'auto', ... 'vpos', 0.15, ... 'halign', 'right', ... 'width', 0.15, ... 'height', 0.55); % control panel opt.handles.panel.controls = uipanel(... 'tag', 'lowerPanels', ... % tag according to position 'parent', opt.handles.figure,... 'units', 'normalized', ... 'title', 'Controls',... 'clipping','on',... 'visible', 'on'); % rearrange ft_uilayout(opt.handles.figure, ... 'tag', 'lowerPanels', ... 'backgroundcolor', [0.8 0.8 0.8], ... 'hpos', 'auto', ... 'vpos', 0, ... 'halign', 'right', ... 'width', 1, ... 'height', 0.15); ft_uilayout(opt.handles.figure, ... 'tag', 'mainPanels1', ... 'retag', 'sidePanels'); ft_uilayout(opt.handles.figure, ... 'tag', 'mainPanels2', ... 'retag', 'sidePanels'); ft_uilayout(opt.handles.figure, ... 'tag', 'sidePanels', ... 'backgroundcolor', [.8 .8 .8], ... 'hpos', 'auto', ... 'vpos', 'align', ... 'halign', 'left', ... 'valign', 'top', ... 'height', .85); % add axes % 3 axes for switching to topo viewmode % opt.handles.axes.A = axes(... % 'Parent',opt.handles.panel.view,... % 'Position',[0 0 1 .33], ... % 'Tag','topoAxes',... % 'HandleVisibility', 'on', ... % 'UserData',[]); % % opt.handles.axes.B = axes(... % 'Parent',opt.handles.panel.view,... % 'Position',[0 0.33 1 .33], ... % 'Tag','topoAxes',... % 'HandleVisibility', 'on', ... % 'UserData',[]); % % opt.handles.axes.C = axes(... % 'Parent',opt.handles.panel.view,... % 'Position',[0 0.66 1 .33], ... % 'Tag','topoAxes',... % 'HandleVisibility', 'on', ... % 'UserData',[]); % control panel uicontrols opt.handles.button.play = uicontrol(... 'parent',opt.handles.panel.controls,... 'tag', 'controlInput', ... 'string','Play',... 'units', 'normalized', ... 'style', 'pushbutton', ... 'callback',@cb_playbutton,... 'userdata', 'space'); opt.handles.button.record = uicontrol(... 'parent',opt.handles.panel.controls,... 'tag', 'controlInput', ... 'string','Record?',... 'units', 'normalized', ... 'style', 'checkbox', ... 'Callback',@cb_recordbutton,... 'userdata', 'enter'); ft_uilayout(opt.handles.panel.controls, ... 'tag', 'controlInput', ... 'width', 0.15, ... 'height', 0.25, ... 'hpos', 'auto', ... 'vpos', .75, ... 'halign', 'right', ... 'valign', 'top'); opt.handles.text.speed = uicontrol(... 'parent',opt.handles.panel.controls,... 'tag', 'speedInput', ... 'string','Speed',... 'units', 'normalized', ... 'style', 'text'); opt.handles.edit.speed = uicontrol(... 'parent',opt.handles.panel.controls,... 'tag', 'speedInput', ... 'string','1.0',... 'units', 'normalized', ... 'Callback',@cb_speed, ... 'style', 'edit'); ft_uilayout(opt.handles.panel.controls, ... 'tag', 'speedInput', ... 'width', 0.15, ... 'height', 0.25, ... 'hpos', 'auto', ... 'vpos', .25, ... 'halign', 'right', ... 'valign', 'top'); % opt.handles.button.faster = uicontrol(... % 'parent',opt.handles.panel.controls,... % 'tag', 'controlInput', ... % 'string','+',... % 'units', 'normalized', ... % 'style', 'pushbutton', ... % 'userdata', '+', ... % 'Callback',@cb_slider); % % % opt.handles.button.slower = uicontrol(... % 'parent',opt.handles.panel.controls,... % 'tag', 'controlInput', ... % 'string','-',... % 'units', 'normalized', ... % 'style', 'pushbutton', ... % 'userdata', '-', ... % 'Callback',@cb_slider); % ft_uilayout(opt.handles.panel.controls, ... % 'tag', 'controlInput', ... % 'width', 0.15, ... % 'height', 0.25, ... % 'hpos', 'auto', ... % 'vpos', .75, ... % 'valign', 'top'); % % set(opt.handles.button.slower, 'tag', 'speedButtons'); % set(opt.handles.button.faster, 'tag', 'speedButtons'); % % % ft_uilayout(opt.handles.panel.controls, ... % 'tag', 'speedButtons', ... % 'width', 0.05, ... % 'height', 0.125, ... % 'vpos', 'auto'); % % ft_uilayout(opt.handles.panel.controls, ... % 'tag', 'speedButtons', ... % 'hpos', 'align'); % % % ft_uilayout(opt.handles.panel.controls, ... % 'tag', 'speedButtons', ... % 'retag', 'controlInput'); % speed control opt.handles.slider.xparam = uicontrol(... 'Parent',opt.handles.panel.controls,... 'Units','normalized',... 'BackgroundColor',[0.9 0.9 0.9],... 'Callback',@cb_slider,... 'Position',[0.0 0.75 0.625 0.25],... 'SliderStep', [1/numel(opt.xvalues) 1/numel(opt.xvalues)],... 'String',{ 'Slider' },... 'Style','slider',... 'Tag','xparamslider'); opt.handles.label.xparam = uicontrol(... 'Parent',opt.handles.panel.controls,... 'Units','normalized',... 'Position',[0.0 0.5 0.625 0.25],... 'String','xparamLabel',... 'Style','text',... 'Tag','xparamLabel'); if ~isempty(opt.ydim) opt.handles.slider.yparam = uicontrol(... 'Parent',opt.handles.panel.controls,... 'Units','normalized',... 'BackgroundColor',[0.9 0.9 0.9],... 'Callback',@cb_slider,... 'Position',[0.0 0.25 0.625 0.25],... 'SliderStep', [1/numel(opt.yvalues) 1/numel(opt.yvalues)],... 'String',{ 'Slider' },... 'Style','slider',... 'Tag','yparamSlider'); opt.handles.label.yparam = uicontrol(... 'Parent',opt.handles.panel.controls,... 'Units','normalized',... 'Position',[0.0 0.0 0.625 0.25],... 'String','yparamLabel',... 'Style','text',... 'Tag','text3'); end opt.handles.axes.colorbar = axes(... 'Parent',opt.handles.panel.settings,... 'Units','normalized',... 'Position',[0 0 1.0 1],... 'ButtonDownFcn',@cb_color,... 'HandleVisibility', 'on', ... 'Tag','colorbarAxes', ... 'YLim', [0 1], ... 'YLimMode', 'manual', ... 'XLim', [0 1], ... 'XLimMode', 'manual'); opt.handles.colorbar = colorbar('ButtonDownFcn', []); set(opt.handles.colorbar, 'Parent', opt.handles.panel.settings); set(opt.handles.colorbar, 'Position', [0.4 0.2 0.2 0.65]); nColors = size(colormap, 1); set(opt.handles.colorbar, 'YTick', [1 nColors/4 nColors/2 3*nColors/4 nColors]); if (gcf~=opt.handles.figure) close gcf; % sometimes there is a new window that opens up end % % set lines %YLim = get(opt.handles.colorbar, 'YLim'); opt.handles.lines.upperColor = line([-1 0], [32 32], ... 'Color', 'black', ... 'LineWidth', 4, ... 'ButtonDownFcn', @cb_startDrag, ... 'Parent', opt.handles.colorbar, ... 'Visible', 'off', ... 'Tag', 'upperColor'); opt.handles.lines.lowerColor = line([1 2], [32 32], ... 'Color', 'black', ... 'LineWidth', 4, ... 'ButtonDownFcn', @cb_startDrag, ... 'Parent', opt.handles.colorbar, ... 'Visible', 'off', ... 'Tag', 'lowerColor'); opt.handles.menu.colormap = uicontrol(... 'Parent',opt.handles.panel.settings,... 'Units','normalized',... 'BackgroundColor',[1 1 1],... 'Callback',@cb_colormap,... 'Position',[0.25 0.95 0.5 0.05],... 'String',{ 'jet'; 'hot'; 'cool'; 'ikelvin'; 'ikelvinr' },... 'Style','popupmenu',... 'Value',1, ... 'Tag','colormapMenu'); opt.handles.checkbox.automatic = uicontrol(... 'Parent',opt.handles.panel.settings,... 'Units','normalized',... 'Callback',@cb_colorbar,... 'Position',[0.10 0.05 0.75 0.05],... 'String','automatic',... 'Style','checkbox',... 'Value', 1, ... % TODO make this dependet on cfg.zlim 'Tag','autoCheck'); opt.handles.checkbox.symmetric = uicontrol(... 'Parent',opt.handles.panel.settings,... 'Units','normalized',... 'Callback',@cb_colorbar,... 'Position',[0.10 0.0 0.75 0.05],... 'String','symmetric',... 'Style','checkbox',... 'Value', 0, ... % TODO make this dependet on cfg.zlim 'Tag','symCheck'); % buttons opt.handles.button.decrLowerColor = uicontrol(... 'Parent', opt.handles.panel.settings,... 'Units','normalized',... 'Enable', 'off', ... 'Callback',@cb_colorbar,... 'Position',[0.35 0.125 0.15 0.05],... 'String','-',... 'Tag','decrLowerColor'); opt.handles.button.incrLowerColor = uicontrol(... 'Parent', opt.handles.panel.settings,... 'Units','normalized',... 'Enable', 'off', ... 'Callback',@cb_colorbar,... 'Position',[0.5 0.125 0.15 0.05],... 'String','+',... 'Tag','incrLowerColor'); opt.handles.button.decrUpperColor = uicontrol(... 'Parent', opt.handles.panel.settings,... 'Units','normalized',... 'Enable', 'off', ... 'Callback',@cb_colorbar,... 'Position',[0.35 0.875 0.15 0.05],... 'String','-',... 'Tag','decrUpperColor'); opt.handles.button.incrUpperColor = uicontrol(... 'Parent', opt.handles.panel.settings,... 'Units','normalized',... 'Enable', 'off', ... 'Callback',@cb_colorbar,... 'Position',[0.5 0.875 0.15 0.05],... 'String','+',... 'Tag','incrUpperColor'); % Handle to the axes that will contain the geometry opt.handles.axes.movie = axes(... 'Parent', opt.handles.panel.visualization_geometry,... 'Position', [0 0 1 1], ... 'CameraPosition', [0.5 0.5 9.16025403784439], ... 'CameraPositionMode', get(0,'defaultaxesCameraPositionMode'),... 'CLim', get(0,'defaultaxesCLim'), ... 'CLimMode', 'manual', ... 'Color', [0.9 0.9 0.94], ... 'ColorOrder', get(0,'defaultaxesColorOrder'),... 'XColor', get(0,'defaultaxesXColor'), ... 'YColor', get(0,'defaultaxesYColor'), ... 'ZColor', get(0,'defaultaxesZColor'), ... 'HandleVisibility', 'on', ... 'ButtonDownFcn', @cb_view, ... 'Tag', 'geometry'); % Handle to the axes that will contain the non-geometry opt.handles.axes.other = axes(... 'Parent', opt.handles.panel.visualization,... 'Position', [0 0 1 1], ... 'CameraPosition', [0.5 0.5 9.16025403784439], ... 'CameraPositionMode', get(0,'defaultaxesCameraPositionMode'),... 'CLim', get(0,'defaultaxesCLim'), ... 'CLimMode', 'manual', ... 'Color', [0.9 0.9 0.94], ... 'ColorOrder', get(0,'defaultaxesColorOrder'),... 'XColor', get(0,'defaultaxesXColor'), ... 'YColor', get(0,'defaultaxesYColor'), ... 'ZColor', get(0,'defaultaxesZColor'), ... 'HandleVisibility', 'on', ... 'ButtonDownFcn', @cb_view, ... 'Tag', 'other'); % Disable axis labels axis(opt.handles.axes.movie, 'equal'); axis(opt.handles.axes.colorbar, 'equal'); % axis(opt.handles.axes.A, 'equal'); % axis(opt.handles.axes.B, 'equal'); % axis(opt.handles.axes.C, 'equal'); % axis(opt.handles.axes.movie, 'off'); axis(opt.handles.axes.colorbar, 'off'); % axis(opt.handles.axes.A, 'off'); % axis(opt.handles.axes.B, 'off'); % axis(opt.handles.axes.C, 'off'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function update_panels(opt) for i=1:numel(opt.dat) if ~any(opt.issource) set(opt.handles.grid{i}, 'cdata', griddata(opt.chanx{i}, opt.chany{i}, opt.mask{i}(:,opt.valx,opt.valy).*opt.dat{i}(:,opt.valx,opt.valy), opt.xdata{i}, opt.nanmask{i}.*opt.ydata{i}, 'v4')); else set(opt.handles.mesh{i}, 'FaceVertexCData', squeeze(opt.dat{i}(:,opt.valx,opt.valy))); set(opt.handles.mesh{i}, 'FaceVertexAlphaData', squeeze(opt.mask{i}(:,opt.valx,opt.valy))); end end if opt.doplot opt.valz set(get(opt.handles.axes.other,'children'), 'ydata', opt.dat{1}(opt.valz,:)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_speed(h, eventdata) if ~ishandle(h) return end opt = guidata(h); val = get(h, 'String'); % val = get(opt.handles.slider.speed, 'value'); % val = exp(log(opt.MAX_SPEED) * (val-.5)./0.5); % % % make sure we can easily get back to normal speed % if abs(val-opt.AVG_SPEED) < 0.08 % val = opt.AVG_SPEED; % set(opt.handles.slider.speed, 'value', 0.5); % end speed = str2num(val); if isempty(speed) speed = opt.speed; end opt.speed = speed; set(h, 'String', opt.speed) % if val >=100 % set(opt.handles.label.speed, 'String', ['Speed ' num2str(opt.speed, '%.1f'), 'x']) % elseif val >= 10 % set(opt.handles.label.speed, 'String', ['Speed ' num2str(opt.speed, '%.2f'), 'x']) % else % set(opt.handles.label.speed, 'String', ['Speed ' num2str(opt.speed, '%.3f'), 'x']) % end guidata(h, opt); uiresume; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_timer(obj, info, h) if ~ishandle(h) return end opt = guidata(h); delta = opt.speed/numel(opt.xvalues); val = get(opt.handles.slider.xparam, 'value'); val = val + delta; if opt.record if val>1 % stop recording stop(opt.timer); % reset again val = 0; set(opt.handles.slider.xparam, 'value', val); cb_slider(h); cb_recordbutton(opt.handles.button.record); % TODO FIXME add some message here guidata(h, opt); return; end end while val>1 val = val-1; end set(opt.handles.slider.xparam, 'value', val); cb_slider(h); if opt.record pause(.1); drawnow; vs = version('-release'); vs = vs(1:4); % get starting position via parameter panel currFrame = getframe(opt.handles.figure); for i=1:opt.samperframe if vs<2010 opt.vidObj = addframe(opt.vidObj, currFrame); else writeVideo(opt.vidObj, currFrame); end end guidata(h, opt); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_slider(h, eventdata) opt = guidata(h); valx = get(opt.handles.slider.xparam, 'value'); valx = round(valx*(numel(opt.xvalues)-1))+1; valx = min(valx, numel(opt.xvalues)); valx = max(valx, 1); set(opt.handles.label.xparam, 'String', [opt.xparam ' ' num2str(opt.xvalues(valx), '%.2f') 's']); if ~isempty(opt.yvalues) valy = get(opt.handles.slider.yparam, 'value'); valy = round(valy*(numel(opt.yvalues)-1))+1; valy = min(valy, numel(opt.yvalues)); valy = max(valy, 1); if valy ~= opt.valy cb_colorbar(h); end set(opt.handles.label.yparam, 'String', [opt.yparam ' ' num2str(opt.yvalues(valy), '%.2f') 'Hz']); else valy = 1; end opt.valx = valx; opt.valy = valy; guidata(h, opt); update_panels(opt); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_playbutton(h, eventdata) if ~ishandle(h) return end opt = guidata(h); switch get(h, 'string') case 'Play' set(h, 'string', 'Stop'); start(opt.timer); case 'Stop' set(h, 'string', 'Play'); stop(opt.timer); end uiresume; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_recordbutton(h, eventdata) if ~ishandle(h) return end opt = guidata(h); opt.record = ~opt.record; % switch state guidata(h, opt); if opt.record if ~opt.fixedframesfile % open a save-file dialog [FileName,PathName,FilterIndex] = uiputfile('*.avi', 'Save AVI-file' , 'ft_movie'); if (FileName == 0 & PathName == 0) % aborted cb_recordbutton(h); return; end opt.framesfile = fullfile(PathName, FileName); if (FilterIndex==1) % remove .avi again (4 chars) opt.framesfile = opt.framesfile(1:end-4); end end % FIXME open new window to play in there, so that frame getting works vs = version('-release'); vs = vs(1:4); if vs<2010 opt.vidObj = avifile(opt.framesfile, 'FPS', opt.framerate); else opt.vidObj = VideoWriter(opt.framesfile, 'Uncompressed AVI'); opt.vidObj.FrameRate = opt.framerate; open(opt.vidObj); end %set(opt.handles.figure,'renderer','opengl') %opengl software; set(opt.handles.figure,'renderer','zbuffer'); %opt.vidObj = avifile(opt.framesfile, 'fps', opt.framerate, 'quality', 75); set(h, 'string', 'Stop'); guidata(h, opt); start(opt.timer); else % FIXME set handle back to old window stop(opt.timer); if ~isempty(opt.framesfile) vs = version('-release'); vs = vs(1:4); if vs<2010 opt.vidObj = close(opt.vidObj); else close(opt.vidObj); end end set(h, 'string', 'Record'); guidata(h, opt); if (opt.quit) close(opt.handles.figure); end end % % % This function should open a new window, plot in there, extract every % % frame, store the movie in opt and return again % % % this is not needed, no new window is needed % %scrsz = get(0, 'ScreenSize'); % %f = figure('Position',[1 1 scrsz(3) scrsz(4)]); % % % FIXME disable buttons (apart from RECORD) when recording % % if record is pressed, stop recording and immediately return % % % adapted from ft_movieplotTFR % % % frequency/time selection % if ~isempty(opt.yvalues) && any(~isnan(yvalues)) % if ~isempty(cfg.movietime) % indx = cfg.movietime; % for iFrame = 1:floor(size(opt.dat, opt.xdim)/cfg.samperframe) % indy = ((iFrame-1)*cfg.samperframe+1):iFrame*cfg.samperframe; % updateMovie(opt, indx, indy); % F(iFrame) = getframe; % end % elseif ~isempty(cfg.moviefreq) % indy = cfg.moviefreq; % for iFrame = 1:floor(size(opt.dat, opt.ydim)/cfg.samperframe) % indx = ((iFrame-1)*cfg.samperframe+1):iFrame*cfg.samperframe; % updateMovie(opt, indx, indy); % F(iFrame) = getframe; % end % else % error('Either moviefreq or movietime should contain a bin number') % end % else % for iFrame = 1:floor(size(opt.dat, opt.xdim)/cfg.samperframe) % indx = ((iFrame-1)*cfg.samperframe+1):iFrame*cfg.samperframe; % updateMovie(opt, indx, 1); % F(iFrame) = getframe; % end % end % % % save movie % if ~isempty(cfg.framesfile) % save(cfg.framesfile, 'F'); % end % % play movie % movie(F, cfg.movierpt, cfg.framespersec); % uiresume; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_colormap(h, eventdata) maps = get(h, 'String'); val = get(h, 'Value'); while ~strcmp(get(h, 'Tag'), 'mainFigure') h = get(h, 'Parent'); end opt = guidata(h); cmap = feval(maps{val}, size(colormap, 1)); % if strcmp(maps{val}, 'ikelvin') % cmap = ikelvin(size(colormap, 1)); % elseif strcmp(maps{val}, 'kelvin') % cmap = kelvin(size(colormap, 1)); % else % cmap = colormap(opt.handles.axes.movie, maps{val}); % end if get(opt.handles.checkbox.automatic, 'Value') colormap(opt.handles.axes.movie_subplot{1}, cmap); end adjust_colorbar(opt); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_colorbar(h, eventdata) if strcmp(get(h, 'Tag'), 'mainFigure') % this is the init call incr = false; decr = false; else incr = strcmp(get(h, 'String'), '+'); decr = strcmp(get(h, 'String'), '-'); lower = strfind(get(h, 'Tag'), 'Lower')>0; while ~strcmp(get(h, 'Tag'), 'mainFigure') h = get(h, 'Parent'); end end opt = guidata(h); if (~incr&&~decr&&exist('eventdata', 'var')&&~isempty(eventdata)) % init call caxis(opt.handles.axes.movie, eventdata); end zmin = inf; zmax = -inf; for i=1:numel(opt.dat) [tmpmin tmpmax] = caxis(opt.handles.axes.movie_subplot{i}); zmin = min(tmpmin, zmin); zmax = max(tmpmax, zmax); end yLim = get(opt.handles.colorbar, 'YLim'); if incr yTick = linspace(zmin, zmax, yLim(end)); if get(opt.handles.checkbox.symmetric, 'Value') zmin = zmin - mean(diff(yTick)); zmax = zmax + mean(diff(yTick)); elseif (lower) zmin = zmin + mean(diff(yTick)); else zmax = zmax + mean(diff(yTick)); end elseif decr yTick = linspace(zmin, zmax, yLim(end)); if get(opt.handles.checkbox.symmetric, 'Value') zmin = zmin + mean(diff(yTick)); zmax = zmax - mean(diff(yTick)); elseif (lower) zmin = zmin - mean(diff(yTick)); else zmax = zmax - mean(diff(yTick)); end elseif get(opt.handles.checkbox.automatic, 'Value') % if automatic set(opt.handles.lines.upperColor, 'Visible', 'off'); set(opt.handles.lines.lowerColor, 'Visible', 'off'); set(opt.handles.lines.upperColor, 'YData', [yLim(end)/2 yLim(end)/2]); set(opt.handles.lines.lowerColor, 'YData', [yLim(end)/2 yLim(end)/2]); set(opt.handles.button.incrLowerColor, 'Enable', 'off'); set(opt.handles.button.decrUpperColor, 'Enable', 'off'); set(opt.handles.button.incrUpperColor, 'Enable', 'off'); set(opt.handles.button.decrLowerColor, 'Enable', 'off'); if get(opt.handles.checkbox.symmetric, 'Value') % maxabs zmax = -inf; for i=1:numel(opt.dat) tmpmax = max(max(abs(opt.dat{i}(:,:,opt.valy)))); zmax = max(tmpmax, zmax); end zmin = -zmax; else % maxmin zmax = -inf; zmin = inf; for i=1:numel(opt.dat) tmpmin = min(min(opt.dat{i}(:,:,opt.valy))); tmpmax = max(max(opt.dat{i}(:,:,opt.valy))); zmax = max(tmpmax, zmax); zmin = min(tmpmin, zmin); end end else set(opt.handles.lines.upperColor, 'Visible', 'on'); set(opt.handles.lines.lowerColor, 'Visible', 'on') if get(opt.handles.checkbox.symmetric, 'Value') % maxabs set(opt.handles.button.incrLowerColor, 'Enable', 'off'); set(opt.handles.button.decrUpperColor, 'Enable', 'off'); set(opt.handles.button.incrUpperColor, 'Enable', 'on'); set(opt.handles.button.decrLowerColor, 'Enable', 'on'); for i=1:numel(opt.dat) [tmpmin tmpmax] = caxis(opt.handles.axes.movie_subplot{i}); zmax = max(tmpmax, zmax); end zmin = -zmax; else set(opt.handles.button.incrLowerColor, 'Enable', 'on'); set(opt.handles.button.decrUpperColor, 'Enable', 'on'); set(opt.handles.button.incrUpperColor, 'Enable', 'on'); set(opt.handles.button.decrLowerColor, 'Enable', 'on'); for i=1:numel(opt.dat) [tmpmin tmpmax] = caxis(opt.handles.axes.movie_subplot{i}); zmin = min(tmpmin, zmin); zmax = max(tmpmax, zmax); end end end % incr, decr, automatic, else maps = get(opt.handles.menu.colormap, 'String'); cmap = feval(maps{get(opt.handles.menu.colormap, 'Value')}, size(colormap, 1)); for i=1:numel(opt.dat) colormap(opt.handles.axes.movie_subplot{i}, cmap); end adjust_colorbar(opt); if (gcf~=opt.handles.figure) close gcf; % sometimes there is a new window that opens up end for i=1:numel(opt.dat) caxis(opt.handles.axes.movie_subplot{i}, [zmin zmax]); end nColors = size(colormap, 1); %yTick = (zmax-zmin)*(get(opt.handles.colorbar, 'YTick')/nColors)+zmin yTick = (zmax-zmin)*[0 .25 .5 .75 1]+zmin; %yTick = linspace(zmin, zmax, yLim(end)); % truncate intelligently/-ish %yTick = get(opt.handles.colorbar, 'YTick')/nColors; yTick = num2str(yTick', 5); set(opt.handles.colorbar, 'YTickLabel', yTick, 'FontSize', 8); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_startDrag(h, eventdata) f = get(h, 'Parent'); while ~strcmp(get(f, 'Tag'), 'mainFigure') f = get(f, 'Parent'); end opt = guidata(f); opt.handles.current.line = h; if strfind(get(h, 'Tag'), 'Color')>0 opt.handles.current.axes = opt.handles.colorbar; opt.handles.current.color = true; else disp('Figure out if it works for xparam and yparam'); keyboard end set(f, 'WindowButtonMotionFcn', @cb_dragLine); guidata(h, opt); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_getposition(h, eventdata) h = findobj(h, 'tag', 'mainFigure'); opt = guidata(h); pos = get(get(h, 'currentaxes'), 'currentpoint'); switch get(get(h, 'currentaxes'), 'tag'), case 'geometry' if opt.ismesh % get the intersection with the mesh [ipos, d] = intersect_line(opt.anatomy.pos, opt.anatomy.tri, pos(1,:), pos(2,:)); [md, ix] = min(abs(d)); dpos = opt.anatomy.pos - ipos(ix*ones(size(opt.anatomy.pos,1),1),:); opt.valz = nearest(sum(dpos.^2,2),0); elseif opt.isvolume else end case 'other' otherwise end % if strcmp(get(get(h, 'currentaxes'), 'tag'), 'timecourse') % % get the current point % pos = get(opt.hy, 'currentpoint'); % set(opt.sliderx, 'value', nearest(opt.xparam, pos(1,1))./numel(opt.xparam)); % if isfield(opt, 'hline') % set(opt.slidery, 'value', nearest(opt.yparam, pos(1,2))./numel(opt.yparam)); % end % elseif strcmp(get(get(h, 'currentaxes'), 'tag'), 'mesh') % % get the current point, which is defined as the intersection through the % % axis-box (in 3D) % pos = get(opt.hx, 'currentpoint'); % % % get the intersection with the mesh % [ipos, d] = intersect_line(opt.pos, opt.tri, pos(1,:), pos(2,:)); % [md, ix] = min(abs(d)); % % dpos = opt.pos - ipos(ix*ones(size(opt.pos,1),1),:); % opt.vindx = nearest(sum(dpos.^2,2),0); % % if isfield(opt, 'parcellation') % opt.pindx = find(opt.parcellation(opt.vindx,:)); % disp(opt.pindx); % end % elseif strcmp(get(get(h, 'currentaxes'), 'tag'), 'mesh2') % % get the current point, which is defined as the intersection through the % % axis-box (in 3D) % pos = get(opt.hz, 'currentpoint'); % % % get the intersection with the mesh % [ipos, d] = intersect_line(opt.pos, opt.tri, pos(1,:), pos(2,:)); % [md, ix] = min(abs(d)); % % dpos = opt.pos - ipos(ix*ones(size(opt.pos,1),1),:); % opt.vindx = nearest(sum(dpos.^2,2),0); % % if isfield(opt, 'parcellation') % opt.pindx2 = find(opt.parcellation(opt.vindx,:)); % disp(opt.pindx2); % end % % end guidata(h, opt); cb_slider(h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_dragLine(h, eventdata) opt = guidata(h); pt = get(opt.handles.current.axes, 'CurrentPoint'); yLim = get(opt.handles.colorbar, 'YLim'); % upper (lower) bar must not below (above) lower (upper) bar if ~(opt.handles.current.line == opt.handles.lines.upperColor && ... (any(pt(3)*[1 1]<get(opt.handles.lines.lowerColor, 'YData')) || ... yLim(end) <= pt(3))) ... && ~(opt.handles.current.line == opt.handles.lines.lowerColor && ... (any(pt(3)*[1 1]>get(opt.handles.lines.upperColor, 'YData')) || ... yLim(1) >= pt(3))) set(opt.handles.current.line, 'YData', pt(3)*[1 1]); end adjust_colorbar(opt); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_stopDrag(h, eventdata) while ~strcmp(get(h, 'Tag'), 'mainFigure') h = get(h, 'Parent'); end set(h, 'WindowButtonMotionFcn', ''); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function adjust_colorbar(opt) % adjust colorbar upper = get(opt.handles.lines.upperColor, 'YData'); lower = get(opt.handles.lines.lowerColor, 'YData'); if any(round(upper)==0) || any(round(lower)==0) return; end maps = get(opt.handles.menu.colormap, 'String'); cmap = feval(maps{get(opt.handles.menu.colormap, 'Value')}, size(colormap, 1)); cmap(round(lower(1)):round(upper(1)), :) = repmat(cmap(round(lower(1)), :), 1+round(upper(1))-round(lower(1)), 1); for i=1:numel(opt.dat) colormap(opt.handles.axes.movie_subplot{i}, cmap); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function opt = plot_geometry(opt) numArgs = numel(opt.dat); numRows = floor(sqrt(numArgs)); numCols = ceil(sqrt(numArgs)); for i=1:numArgs axes(opt.handles.axes.movie); opt.handles.axes.movie_subplot{i} = gca; if isfield(opt, 'anatomy') && opt.ismesh if isfield(opt.anatomy, 'sulc') && ~isempty(opt.anatomy.sulc) vdat = opt.anatomy.sulc; vdat(vdat>0.5) = 0.5; vdat(vdat<-0.5)= -0.5; vdat = vdat-min(vdat); vdat = 0.35.*(vdat./max(vdat))+0.3; vdat = repmat(vdat,[1 3]); mesh = ft_plot_mesh(opt.anatomy, 'edgecolor', 'none', 'vertexcolor', vdat); else mesh = ft_plot_mesh(opt.anatomy, 'edgecolor', 'none', 'facecolor', [0.5 0.5 0.5]); end lighting gouraud % set(mesh, 'Parent', opt.handles.axes.movie); % mesh = ft_plot_mesh(source, 'edgecolor', 'none', 'vertexcolor', 0*opt.dat(:,1,1), 'facealpha', 0*opt.mask(:,1,1)); opt.handles.mesh{i} = ft_plot_mesh(opt.anatomy, 'edgecolor', 'none', 'vertexcolor', opt.dat{i}(:,1,1)); set(opt.handles.mesh{i}, 'AlphaDataMapping', 'scaled'); set(opt.handles.mesh{i}, 'FaceVertexAlphaData', opt.mask{i}(:,opt.valx,opt.valy)); % TODO FIXME below does not work %set(opt.handles.mesh, 'FaceAlpha', 'flat'); %set(opt.handles.mesh, 'EdgeAlpha', 'flat'); lighting gouraud cam1 = camlight('left'); % set(cam1, 'Parent', opt.handles.axes.movie); cam2 = camlight('right'); % set(cam2, 'Parent', opt.handles.axes.movie); % set(opt.handles.mesh, 'Parent', opt.handles.axes.movie); % cameratoolbar(opt.handles.figure, 'Show'); else axes(opt.handles.axes.movie) [dum, opt.handles.grid{i}] = ft_plot_topo(opt.layout{i}.pos(opt.sellay,1), opt.layout{i}.pos(opt.sellay,2), zeros(numel(opt.sellay{i}),1), 'mask', opt.layout{i}.mask, 'outline', opt.layout{i}.outline, 'interpmethod', 'v4', 'interplim', 'mask', 'parent', opt.handles.axes.movie); %[dum, opt.handles.grid] = ft_plot_topo(layout.pos(sellay,1), layout.pos(sellay,2), zeros(numel(sellay),1), 'mask',layout.mask, 'outline', layout.outline, 'interpmethod', 'v4', 'interplim', 'mask', 'parent', opt.handles.axes.movie); % set(opt.handles.grid, 'Parent', opt.handles.axes.movie); opt.xdata{i} = get(opt.handles.grid{i}, 'xdata'); opt.ydata{i} = get(opt.handles.grid{i}, 'ydata'); opt.nanmask{i} = 1-get(opt.handles.grid{i}, 'cdata'); if (gcf~=opt.handles.figure) close gcf; % sometimes there is a new window that opens up end end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function opt = plot_other(opt) dimord = opt.dimord; switch dimord case {'pos_time' 'pos_freq' 'chan_time' 'chan_freq'} opt.doplot = true; opt.doimagesc = false; case {'pos_freq_time' 'chan_freq_time' 'chan_chan_freq' 'chan_chan_time' 'pos_pos_freq' 'pos_pos_time'} opt.doplot = false; opt.doimagesc = false; otherwise end if opt.doplot plot(opt.handles.axes.other, opt.xvalues, nanmean(opt.dat{1}(opt.valz,:),1)); elseif opt.doimagesc end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function c = ikelvin(m) % pos hue sat value cu = [ 0.0 1/2 0 1.0 0.125 1/2 0.6 0.95 0.375 2/3 1.0 0.8 0.5 2/3 1.0 0.3 ]; cl = cu; cl(:, 3:4) = cl(end:-1:1, 3:4); cl(:, 2) = cl(:, 2) - 0.5; cu(:,1) = cu(:,1)+.5; x = linspace(0, 1, m)'; l = (x < 0.5); u = ~l; for i = 1:3 h(l, i) = interp1(cl(:, 1), cl(:, i+1), x(l)); h(u, i) = interp1(cu(:, 1), cu(:, i+1), x(u)); end c = hsv2rgb(h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function c = ikelvinr(m) % pos hue sat value cu = [ 0.0 1/2 0 1.0 0.125 1/2 0.6 0.95 0.375 2/3 1.0 0.8 0.5 2/3 1.0 0.3 ]; cl = cu; cl(:, 3:4) = cl(end:-1:1, 3:4); cl(:, 2) = cl(:, 2) - 0.5; cu(:,1) = cu(:,1)+.5; x = linspace(0, 1, m)'; l = (x < 0.5); u = ~l; for i = 1:3 h(l, i) = interp1(cl(:, 1), cl(:, i+1), x(l)); h(u, i) = interp1(cu(:, 1), cu(:, i+1), x(u)); end c = hsv2rgb(h); c = flipud(c); end
github
lcnbeapp/beapp-master
bsscca.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/bsscca.m
7,428
utf_8
d64d6dd63efc92dff2aabe9e03c7dbb1
function [w,rho] = bsscca(X, delay) % BSSCCA computes the unmixing matrix based on the canonical correlation between a signal and its lagged-one copy. It implements the algorithm described in [1] % % DeClercq et al 2006, IEEE Biomed Eng 2583. if nargin<2, delay = 1; end % hmmmm we need to observe the epochs' boundaries to not create rubbish % support cell array input if isa(X, 'cell') delay = setdiff(delay(:)', 0); n = size(X{1},1); mX = cellmean(X,2); X = cellvecadd(X, -mX); C = cellcovshift(X,[0 delay],2,0); m = size(C,1)-n; XY = C(1:n, (n+1):end); % cross terms XY XX = C(1:n, 1:n); % auto terms X; YY = C((n+1):end, (n+1):end); % auto terms Y YX = C((n+1):end, 1:n); %A(1:n,1:n) = 0; %A((n+1):end,(n+1):end) = 0; %B(1:n,(n+1):end) = 0; %B((n+1):end,1:n) = 0; else % input is a single data matrix assumed to be a continuous stretch [n,m] = size(X); % get the means %m = ones(1,m-1); %mX = mean(X(:,2:end),2); % lag zero %mX2 = mean(X(:,1:end-1),2); % lag one % use Borga's (2001) formulation from 'a unified approach to PCA, PLS, MLR % and CCA' A = zeros(2*n); B = zeros(2*n); if numel(delay)==1 Xlag = X(:,1:(m-delay)); else end XY = X(:,delay+(1:(m-delay)))*Xlag'; XX = X(:,delay+(1:(m-delay)))*X(:,delay+(1:(m-delay)))'; YY = Xlag*Xlag'; %XY = (X(:,2:end)-mX*m)*(X(:,1:end-1)-mX2*m)'; A(1:n,(n+1):end) = XY; A((n+1):end,1:n) = XY'; B(1:n,1:n) = XX; B((n+1):end,(n+1):end) = YY; %B(1:n,1:n) = (X(:,2:end)-mX*m)*(X(:,2:end)-mX*m)'; %B((n+1):end,(n+1):end) = (X(:,1:end-1)-mX2*m)*(X(:,1:end-1)-mX2*m)'; end %if cond(B)>1e8 % s = svd(B); % [w,rho] = eig((B+eye(size(B,1))*s(1)*0.00000001)\A); %else % [w,rho] = eig(B\A); %end if cond(XX)>1e8 s = svd(XX); XX = XX+eye(size(XX,1))*s(1)*0.00000001; end if cond(YY)>1e8 s = svd(YY); YY = YY+eye(size(YY,1))*s(1)*0.00000001; end [wx,rho] = eig((XX\XY)*(YY\YX)); rho = sqrt(real(diag(rho))); [dummy,ix] = sort(rho, 'descend'); rho = rho(ix); wx = wx(:,ix); w = wx'; %[dummy,ix] = sort(diag(abs(rho).^2),'descend'); %w = w(1:n,ix(2:2:end))'; %w = w(1:n,1:n); %rho = abs(rho(ix(2:2:2*n),ix(2:2:2*n))).^2; % normalise to unit norm %for k= 1:size(w,1) % w(k,:) = w(k,:)./norm(w(k,:)); %end function [m] = cellmean(x, dim) % [M] = CELLMEAN(X, DIM) computes the mean, across all cells in x along % the dimension dim. % % X should be an linear cell-array of matrices for which the size in at % least one of the dimensions should be the same for all cells nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellmean'); end if nargin==1, scx1 = cellfun('size', x, 1); scx2 = cellfun('size', x, 2); if all(scx2==scx2(1)), dim = 2; %let second dimension prevail elseif all(scx1==scx1(1)), dim = 1; else error('no dimension to compute mean for'); end end nx = max(nx); nsmp = cellfun('size', x, dim); ssmp = cellfun(@sum, x, repmat({dim},1,nx), 'UniformOutput', 0); m = sum(cell2mat(ssmp), dim)./sum(nsmp); function [y] = cellvecadd(x, v) % [Y]= CELLVECADD(X, V) - add vector to all rows or columns of each matrix % in cell-array X % check once and for all to save time persistent bsxfun_exists; if isempty(bsxfun_exists); bsxfun_exists=(exist('bsxfun')==5); if ~bsxfun_exists; error('bsxfun not found.'); end end nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellmean'); end if ~iscell(v), v = repmat({v}, nx); end sx1 = cellfun('size', x, 1); sx2 = cellfun('size', x, 2); sv1 = cellfun('size', v, 1); sv2 = cellfun('size', v, 2); if all(sx1==sv1) && all(sv2==1), dim = mat2cell([ones(length(sx2),1) sx2(:)]', repmat(2,nx(1),1), repmat(1,nx(2),1)); elseif all(sx2==sv2) && all(sv1==1), dim = mat2cell([sx1(:) ones(length(sx1),1)]', repmat(2,nx(1),1), repmat(1,nx(2),1)); elseif all(sv1==1) && all(sv2==1), dim = mat2cell([sx1(:) sx2(:)]'', nx(1), nx(2)); else error('inconsistent input'); end y = cellfun(@bsxfun, repmat({@plus}, nx), x, v, 'UniformOutput', 0); %y = cellfun(@vplus, x, v, dim, 'UniformOutput', 0); function [c] = cellcov(x, y, dim, flag) % [C] = CELLCOV(X, DIM) computes the covariance, across all cells in x along % the dimension dim. When there are three inputs, covariance is computed between % all cells in x and y % % X (and Y) should be linear cell-array(s) of matrices for which the size in at % least one of the dimensions should be the same for all cells if nargin<4 && iscell(y) flag = 1; elseif nargin<4 && isnumeric(y) flag = dim; end if nargin<3 && iscell(y) scx1 = cellfun('size', x, 1); scx2 = cellfun('size', x, 2); if all(scx2==scx2(1)), dim = 2; %let second dimension prevail elseif all(scx1==scx1(1)), dim = 1; else error('no dimension to compute covariance for'); end elseif nargin<=3 && isnumeric(y) dim = y; end if isnumeric(y), y = []; end nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellmean'); end if flag, mx = cellmean(x, 2); x = cellvecadd(x, -mx); if ~isempty(y), my = cellmean(y, 2); y = cellvecadd(y, -my); end end nx = max(nx); nsmp = cellfun('size', x, dim); if isempty(y), csmp = cellfun(@covc, x, repmat({dim},1,nx), 'UniformOutput', 0); else csmp = cellfun(@covc, x, y, repmat({dim},1,nx), 'UniformOutput', 0); end nc = size(csmp{1}); c = sum(reshape(cell2mat(csmp), [nc(1) nc(2) nx]), 3)./sum(nsmp); function [c] = covc(x, y, dim) if nargin==2, dim = y; y = x; end if dim==1, c = x'*y; elseif dim==2, c = x*y'; end function [c] = cellcovshift(x, shift, dim, flag) % [C] = CELLCOVSHIFT(X, SHIFT, DIM) computes the covariance, across all cells % in x along the dimension dim. % % X should be linear cell-array(s) of matrices for which the size in at % least one of the dimensions is be the same for all cells if nargin<4, flag = 1; end if nargin<3, dim = find(size(x{1})>1, 1, 'first'); end nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1) || ndims(x{1})>2, error('incorrect input for cellcovshift'); end % shift the time axis y = cellshift(x, shift, dim); % compute covariance c = cellcov(y, dim, flag); function [x] = cellshift(x, shift, dim, maxshift) % CELLSHIFT(X, SHIFT, DIM) if numel(shift)>1 x = x(:)'; y = cell(numel(shift),numel(x)); for k = 1:numel(shift) y(k,:) = cellshift(x, shift(k), dim, max(abs(shift))); end for k = 1:size(y,2) y{1,k} = cell2mat(y(:,k)); for m = 2:size(y,1) y{m,k} = nan; end end x = y(1,:); return; end if nargin<4 maxshift = max(abs(shift)); end if any(abs(shift))>abs(maxshift) error('the value for maxshift should be >= shift'); end if nargin<3 dim = find(size(x{1})>1, 1, 'first'); end maxshift = abs(maxshift); if numel(maxshift)==1, maxshift = maxshift([1 1]); end nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellshift'); end n = numel(x); nsmp = cellfun('size', x, dim); beg1 = ones(1,n) + shift + maxshift(1); end1 = nsmp + shift - maxshift(2); switch dim case 1 for k = 1:n x{k} = x{k}(beg1(k):end1(k),:); end case 2 for k = 1:n x{k} = x{k}(:,beg1(k):end1(k)); end otherwise error('dimensionality of >2 is not supported'); end
github
lcnbeapp/beapp-master
inside_contour.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/inside_contour.m
1,105
utf_8
6554af9f8bc2dc7512e8ca962a63688b
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
lcnbeapp/beapp-master
smudge.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/smudge.m
1,949
utf_8
a793adc32ad1bfa0f193bd20c3ca7764
function [datout, S] = smudge(datin, tri, niter, threshold) % 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 || isempty(niter), niter = 1; end if nargin<4 threshold = 0; end for k = 1:niter [tmp, Stmp] = do_smudge(datin, tri, threshold); if k==1, S = Stmp; else S = Stmp*S; end datout = tmp; datin = tmp; end function [datout, S] = do_smudge(datin, tri, threshold) % number of points npnt = numel(datin); % non-zero points nz = find(datin>threshold); % triangles containing 1 or 2 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 % matrices that define edges which has one of the members 0 % sorted according to the left or the right column respectively vecx = sortrows([vec1 vec2]); % having the non-zero vertex upfront, sorted accordingly vecy = sortrows([vec2 vec1]); % having the zero vertex upfront, sorted accordingly clear vec1 vec2; % in a closed surface the edges occur in doubles vecx = vecx(1:2:end,:); vecy = vecy(1:2:end,:); % vecx now has in the first column the column indices for matrix S % vecx now has in the second column the row indices for matrix S % reconstruct the value that has to be put into the matrix [uval,i1,i2] = unique(vecy(:,1)); tmp = diff([0;vecy(:,1)])>0; nix = diff(find([tmp;1]==1)); nix(end+1:numel(uval)) = 1; [dummy,i1,i2] = unique(vecx(:,2)); val = 1./nix(i2); S = sparse(vecx(:,2),vecx(:,1),val,npnt,npnt); S = S + spdiags(datin(:)>threshold, 0, npnt, npnt); datout = S*datin(:);
github
lcnbeapp/beapp-master
getdimsiz.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/getdimsiz.m
2,235
utf_8
340d495a654f2f6752aa1af7ac915390
function dimsiz = getdimsiz(data, field) % GETDIMSIZ % % Use as % dimsiz = getdimsiz(data, field) % % If the length of the vector that is returned is smaller than the % number of dimensions that you would expect from GETDIMORD, you % should assume that it has trailing singleton dimensions. % % Example use % dimord = getdimord(datastructure, fieldname); % dimtok = tokenize(dimord, '_'); % dimsiz = getdimsiz(datastructure, fieldname); % dimsiz(end+1:length(dimtok)) = 1; % there can be additional trailing singleton dimensions % % See also GETDIMORD, GETDATFIELD if ~isfield(data, field) && isfield(data, 'avg') && isfield(data.avg, field) field = ['avg.' field]; elseif ~isfield(data, field) && isfield(data, 'trial') && isfield(data.trial, field) field = ['trial.' field]; elseif ~isfield(data, field) error('field "%s" not present in data', field); end if strncmp(field, 'avg.', 4) prefix = []; field = field(5:end); % strip the avg data.(field) = data.avg.(field); % move the avg into the main structure data = rmfield(data, 'avg'); elseif strncmp(field, 'trial.', 6) prefix = numel(data.trial); field = field(7:end); % strip the trial data.(field) = data.trial(1).(field); % move the first trial into the main structure data = rmfield(data, 'trial'); else prefix = []; end dimsiz = cellmatsize(data.(field)); % add nrpt in case of source.trial dimsiz = [prefix dimsiz]; end % main function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to determine the size of data representations like {pos}_ori_time % FIXME this will fail for {xxx_yyy}_zzz %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function siz = cellmatsize(x) if iscell(x) if isempty(x) siz = 0; return % nothing else to do elseif isvector(x) cellsize = numel(x); % the number of elements in the cell-array else cellsize = size(x); x = x(:); % convert to vector for further size detection end [dum, indx] = max(cellfun(@numel, x)); matsize = size(x{indx}); % the size of the content of the cell-array siz = [cellsize matsize]; % concatenate the two else siz = size(x); end end % function cellmatsize
github
lcnbeapp/beapp-master
convert_event.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/convert_event.m
7,782
utf_8
f31a7a3358af889e95dc1c8178c68bbf
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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % 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 = ft_getopt(varargin, 'endsample'); typenames = ft_getopt(varargin, 'typenames'); % 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) if ~isempty(obj{i}) obj{i} = obj{i}(:,1:3); end 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
lcnbeapp/beapp-master
project_elec.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/project_elec.m
3,791
utf_8
61bc3f095e4ced1311048c06823bb037
function [el, prj] = project_elec(elc, pnt, tri) % PROJECT_ELEC projects electrodes on a triangulated surface % and returns triangle index, la/mu parameters and distance % % Use as % [el, prj] = project_elec(elc, pnt, tri) % which returns % el = Nx4 matrix with [tri, la, mu, dist] for each electrode % prj = Nx3 matrix with the projected electrode position % % See also TRANSFER_ELEC % Copyright (C) 1999-2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ Nelc = size(elc,1); el = zeros(Nelc, 4); % this is a work-around for http://bugzilla.fcdonders.nl/show_bug.cgi?id=2369 elc = double(elc); pnt = double(pnt); tri = double(tri); for i=1:Nelc [proj,dist] = ptriprojn(pnt(tri(:,1),:), pnt(tri(:,2),:), pnt(tri(:,3),:), elc(i,:), 1); [mindist, minindx] = min(abs(dist)); [la, mu] = lmoutr(pnt(tri(minindx,1),:), pnt(tri(minindx,2),:), pnt(tri(minindx,3),:), proj(minindx,:)); smallest_dist = dist(minindx); smallest_tri = minindx; smallest_la = la; smallest_mu = mu; % the following can be done faster, because the smallest_dist can be % directly selected % Ntri = size(tri,1); % for j=1:Ntri % %[proj, dist] = ptriproj(pnt(tri(j,1),:), pnt(tri(j,2),:), pnt(tri(j,3),:), elc(i,:), 1); % if dist(j)<smallest_dist % % remember the triangle index, distance and la/mu % [la, mu] = lmoutr(pnt(tri(j,1),:), pnt(tri(j,2),:), pnt(tri(j,3),:), proj(j,:)); % smallest_dist = dist(j); % smallest_tri = j; % smallest_la = la; % smallest_mu = mu; % end % end % store the projection for this electrode el(i,:) = [smallest_tri smallest_la smallest_mu smallest_dist]; end if nargout>1 prj = zeros(size(elc)); for i=1:Nelc v1 = pnt(tri(el(i,1),1),:); v2 = pnt(tri(el(i,1),2),:); v3 = pnt(tri(el(i,1),3),:); la = el(i,2); mu = el(i,3); prj(i,:) = routlm(v1, v2, v3, la, mu); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION this is an alternative implementation that will also work for % polygons %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function prj = polyproj(elc,pnt) % projects a point on a plane, e.g. an electrode on a polygon % pnt is a Nx3 matrix with multiple vertices that span the plane % these vertices can be slightly off the plane center = mean(pnt,1); % shift the vertices to have zero mean pnt(:,1) = pnt(:,1) - center(1); pnt(:,2) = pnt(:,2) - center(2); pnt(:,3) = pnt(:,3) - center(3); elc(:,1) = elc(:,1) - center(1); elc(:,2) = elc(:,2) - center(2); elc(:,3) = elc(:,3) - center(3); pnt = pnt'; elc = elc'; [u, s, v] = svd(pnt); % The vertices are assumed to ly in plane, at least reasonably. That means % that from the three eigenvectors there is one which is very small, i.e. % the one orthogonal to the plane. Project the electrodes along that % direction. u(:,3) = 0; prj = u * u' * elc; prj = prj'; prj(:,1) = prj(:,1) + center(1); prj(:,2) = prj(:,2) + center(2); prj(:,3) = prj(:,3) + center(3);
github
lcnbeapp/beapp-master
fdr.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/fdr.m
2,138
utf_8
fd32f61564bb6c0088f02c6a3fcec3a2
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. % % There are two types of FDR correction (Benjamini-Hochberg & Benjamini-Yekutieli), of % which the second is currently implemented. % Copyright (C) 2005-2015, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % 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); if any(ps<=pi) h = ps<=(max(ps(ps<=pi))); else h = false(size(ps)); end % 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
lcnbeapp/beapp-master
prepare_mesh_hexahedral.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/prepare_mesh_hexahedral.m
17,670
utf_8
6191dbd9342d65e59d705e95b3e70aeb
function mesh = prepare_mesh_hexahedral(cfg, mri) % PREPARE_MESH_HEXAHEDRAL % % Configuration options for generating a regular 3-D grid % cfg.tissue = cell with the names of the compartments that should be meshed % cfg.resolution = desired resolution of the mesh (default = 1) % cfg.shift % cfg.background % % See also PREPARE_MESH_SEGMENTATION, PREPARE_MESH_MANUAL, PREPARE_MESH_HEADSHAPE % Copyrights (C) 2012-2013, Johannes Vorwerk % % $Id$ % ensure that the input is consistent with what this function expects mri = ft_checkdata(mri, 'datatype', {'volume', 'segmentation'}, 'hasunit', 'yes'); % get the default options cfg.tissue = ft_getopt(cfg, 'tissue'); cfg.resolution = ft_getopt(cfg, 'resolution', 1); % this is in mm cfg.shift = ft_getopt(cfg, 'shift'); cfg.background = ft_getopt(cfg, 'background', 0); if isempty(cfg.tissue) mri = ft_datatype_segmentation(mri, 'segmentationstyle', 'indexed'); fn = fieldnames(mri); for i = 1:numel(fn), if (numel(mri.(fn{i})) == prod(mri.dim)) && (~strcmp(fn{i}, 'inside')) segfield = fn{i}; end end cfg.tissue = setdiff(unique(mri.(segfield)(:)), 0); end if ischar(cfg.tissue) % it should either be something like {'brain', 'skull', 'scalp'}, or something like [1 2 3] cfg.tissue = {cfg.tissue}; end if iscell(cfg.tissue) % the code below assumes that it is a probabilistic representation if any(strcmp(cfg.tissue, 'brain')) mri = ft_datatype_segmentation(mri, 'segmentationstyle', 'probabilistic', 'hasbrain', 'yes'); else mri = ft_datatype_segmentation(mri, 'segmentationstyle', 'probabilistic'); end else % the code below assumes that it is an indexed representation mri = ft_datatype_segmentation(mri, 'segmentationstyle', 'indexed'); end if isempty(cfg.shift) warning('No node-shift selected') cfg.shift = 0; elseif cfg.shift > 0.3 warning('Node-shift should not be larger than 0.3') cfg.shift = 0.3; end % do the mesh extraction % this has to be adjusted for FEM!!! if iscell(cfg.tissue) % this assumes that it is a probabilistic representation % for example {'brain', 'skull', scalp'} try temp = zeros(size(mri.(cfg.tissue{1})(:))); for i = 1:numel(cfg.tissue) temp = [temp, mri.(cfg.tissue{i})(:)]; end [val, seg] = max(temp, [], 2); seg = seg - 1; seg = reshape(seg, mri.dim); catch error('Please specify cfg.tissue to correspond to tissue types in the segmented MRI') end tissue = cfg.tissue; else % this assumes that it is an indexed representation % for example [3 2 1] seg = zeros(mri.dim); tissue = {}; for i = 1:numel(cfg.tissue) seg = seg + i*(mri.seg == cfg.tissue(i)); if isfield(mri, 'seglabel') try tissue{i} = mri.seglabel{cfg.tissue(i)}; catch error('Please specify cfg.tissue to correspond to (the name or number of) tissue types in the segmented MRI') end else tissue{i} = sprintf('tissue %d', i); end end end % reslice to desired resolution if (cfg.resolution ~= 1) % this should be done like this: split seg into probabilistic, reslice single compartments, take maximum values seg_array = []; seg_indices = unique(seg); for i = 1:(length(unique(seg))) seg_reslice.anatomy = double(seg == (i-1)); seg_reslice.dim = mri.dim; seg_reslice.transform = eye(4); seg_reslice.transform(1:3, 4) = -ceil(mri.dim/2); cfg_reslice = []; cfg_reslice.resolution = cfg.resolution; cfg_reslice.dim = ceil(mri.dim/cfg.resolution); seg_build = ft_volumereslice(cfg_reslice, seg_reslice); seg_array = [seg_array, seg_build.anatomy(:)]; clear seg_reslice; end [max_seg seg_build.seg] = max(seg_array, [], 2); clear max_seg seg_array; seg_build.seg = reshape(seg_build.seg, seg_build.dim); seg_build.seg = seg_indices(seg_build.seg); seg_build.transform = mri.transform; clear seg_build.anatomy; else seg_build.seg = seg; seg_build.dim = mri.dim; clear seg; end % ensure that the segmentation is binary and that there is a single contiguous region % FIXME is this still needed when it is already binary? %seg = volumethreshold(seg, 0.5, tissue); ft_hastoolbox('simbio', 1); % build the mesh mesh = build_mesh_hexahedral(cfg, seg_build); % converting position of meshpoints to the head coordinate system if (cfg.resolution ~= 1) mesh.pnt = cfg.resolution * mesh.pnt; end mesh.pnt = ft_warp_apply(mri.transform, mesh.pnt, 'homogeneous'); labels = mesh.labels; clear mesh.labels; mesh.tissue = zeros(size(labels)); numlabels = size(unique(labels), 1); mesh.tissuelabel = {}; ulabel = sort(unique(labels)); for i = 1:numlabels mesh.tissue(labels == ulabel(i)) = i; mesh.tissuelabel{i} = tissue{i}; end end % function %% subfunctions %% function mesh = build_mesh_hexahedral(cfg, mri) background = cfg.background; shift = cfg.shift; % extract number of voxels in each direction % x_dim = mri.dim(1); % y_dim = mri.dim(2); % z_dim = mri.dim(3); %labels = mri.seg; fprintf('Dimensions of the segmentation before restriction to bounding-box: %i %i %i\n', mri.dim(1), mri.dim(2), mri.dim(3)); [bb_x, bb_y, bb_z] = ind2sub(size(mri.seg), find(mri.seg)); shift_coord = [min(bb_x) - 2, min(bb_y) - 2, min(bb_z) - 2]; bb_x = [min(bb_x), max(bb_x)]; bb_y = [min(bb_y), max(bb_y)]; bb_z = [min(bb_z), max(bb_z)]; x_dim = size(bb_x(1)-1:bb_x(2)+1, 2); y_dim = size(bb_y(1)-1:bb_y(2)+1, 2); z_dim = size(bb_z(1)-1:bb_z(2)+1, 2); labels = zeros(x_dim, y_dim, z_dim); labels(2:(x_dim-1), 2:(y_dim-1), 2:(z_dim-1)) = mri.seg(bb_x(1):bb_x(2), bb_y(1):bb_y(2), bb_z(1):bb_z(2)); fprintf('Dimensions of the segmentation after restriction to bounding-box: %i %i %i\n', x_dim, y_dim, z_dim); % create elements mesh.hex = create_elements(x_dim, y_dim, z_dim); fprintf('Created elements...\n' ) % create nodes mesh.pnt = create_nodes(x_dim, y_dim, z_dim); fprintf('Created nodes...\n' ) if(shift < 0 | shift > 0.3) error('Please choose a shift parameter between 0 and 0.3!'); elseif(shift > 0) mesh.pnt = shift_nodes(mesh.pnt, mesh.hex, labels, shift, x_dim, y_dim, z_dim); end %background = 1; % delete background voxels(if desired) if(background == 0) mesh.hex = mesh.hex(labels ~= 0, :); mesh.labels = labels(labels ~= 0); else mesh.labels = labels(:); end % delete unused nodes [C, ia, ic] = unique(mesh.hex(:)); mesh.pnt = mesh.pnt(C, :, :, :); mesh.pnt = mesh.pnt + repmat(shift_coord, size(mesh.pnt, 1), 1); mesh.hex(:) = ic; end % subfunction % function creating elements from a MRI-Image with the dimensions x_dim, % y_dim, z_dim. Each voxel of the MRI-Image corresponds to one element in % the hexahedral mesh. The numbering of the elements is as follows: % the first x-y-plane(z == 1) is numbered by incrementing in x-direction % first until x_dim is reached. This is done for each row in y-direction % until y_dim is reached. Using the resulting x_dim-by-y_dim numbering as % an overlay and adding (i-1)*(x_dim*y_dim) to the overlay while i is % iterating through the z-dimension(until i == z_dim) we obtain a numbering % for all the elements. % The node-numbering is done accordingly: the bottom left node in element i % has number i in the node-numbering. All the remaining nodes are numbered % in the same manner as described above for the element numbering(note the % different dimensionalities: x_dim+1 instead of x_dim etc.). function elements = create_elements(x_dim, y_dim, z_dim) elements = zeros(x_dim*y_dim*z_dim, 8); % create an offset vector for the bottom-left nodes in each element b = 1:((x_dim+1)*(y_dim)); % delete the entries where the node does not correspond to an element's % bottom-left node(i.e. where the x-component of the node is equal to % x_dim+1) b = b(mod(b, (x_dim+1)) ~= 0); % repeat offset to make it fit the number of elements b = repmat(b, 1, (z_dim)); % create vector accounting for the offset of the nodes in z-direction c = fix([0:((x_dim)*(y_dim)*(z_dim)-1)]/((x_dim)*(y_dim))) * (x_dim+1)*(y_dim+1); % create the elements by assigning the nodes to them. entries 1 through 4 % describe the bottom square of the hexahedron, entries 5 through 8 the top % square. elements(:, 1) = b + c; elements(:, 2) = b + c + 1; elements(:, 3) = b + c + (x_dim+1) + 1; elements(:, 4) = b + c + (x_dim+1); elements(:, 5) = b + c + (x_dim + 1)*(y_dim+1); elements(:, 6) = b + c + (x_dim + 1)*(y_dim+1) + 1; elements(:, 7) = b + c + (x_dim + 1)*(y_dim+1) + (x_dim+1) + 1; elements(:, 8) = b + c + (x_dim + 1)*(y_dim+1) + (x_dim+1); clear b; clear c; end %subfunction % function creating the nodes and assigning coordinates in the % [0, x_dim]x[0, y_dim]x[0, z_dim] box. for details on the node-numbering see % comments for create_elements. function nodes = create_nodes(x_dim, y_dim, z_dim) nodes = zeros(((x_dim+1)*(y_dim+1)*(z_dim + 1)), 3); % offset vector for node coordinates b = [0:((x_dim+1)*(y_dim+1)*(z_dim+1)-1)]; % assign coordinates within the box nodes(:, 1) = mod(b, (x_dim+1)); nodes(:, 2) = mod(fix(b/(x_dim+1)), (y_dim+1)); nodes(:, 3) = fix(b/((x_dim + 1)*(y_dim+1))); clear b; end % function shifting the nodes function nodes = shift_nodes(points, hex, labels, sh, x_dim, y_dim, z_dim) cfg = []; fprintf('Applying shift %f\n', sh); nodes = points; % helper vector for indexing the nodes b = 1:(x_dim+1)*(y_dim+1)*(z_dim+1); % vector which gives the corresponding element to a node(in the sense % of how the node-numbering was done, see comment for create_elements). % note that this vector still contains values for nodes which do not have a % corresponding element. this will be manually omitted in the finding % of the surrounding elements(see below). offset = (b - nodes(b, 2)' - (nodes(b, 3))'*(y_dim+1+x_dim))'; offset(offset <= 0) = size(labels, 1)+1; offset(offset > size(hex, 1)) = size(labels, 1)+1; % create array containing the surrounding elements for each node %surrounding = zeros((x_dim+1)*(y_dim+1)*(z_dim+1), 8); % find out the surrounding of each node(if there is any) % find element to which the node is bottom left front %surrounding((nodes(b, 1) < x_dim) & (nodes(b, 3) < z_dim), 1) = offset((nodes(b, 1) < x_dim) & (nodes(b, 3) < z_dim)); % bottom right front %surrounding(nodes(b, 1) > 0, 2) = offset(nodes(b, 1) > 0, 1) -1; % bottom left back %surrounding(nodes(b, 2) > 0, 3) = offset(nodes(b, 2) > 0, 1) - x_dim; % bottom right back %surrounding((nodes(b, 2) > 0) & (nodes(b, 1) > 0), 4) = offset((nodes(b, 2) > 0) & (nodes(b, 1) > 0), 1) - (x_dim) - 1; % top left front %surrounding(nodes(b, 3) > 0, 5) = offset(nodes(b, 3) > 0, 1) - (x_dim)*(y_dim); % top right front %surrounding(nodes(b, 3) > 0, 6) = offset(nodes(b, 3) > 0, 1) - (x_dim)*(y_dim) - 1; % top left back %surrounding(nodes(b, 3) > 0, 7) = offset(nodes(b, 3) > 0, 1) - (x_dim)*(y_dim) - x_dim; % top right back %surrounding((nodes(b, 3) > 0) & (nodes(b, 2) > 0), 8) = offset((nodes(b, 3) > 0) & (nodes(b, 2) > 0), 1) - (x_dim)*(y_dim) - (x_dim) -1; %clear offset; %clear b; % those entries in the surrounding matrix which point to non-existing % elements(> size(hex, 1) or <= 0) we overwrite with a % dummy element %surrounding(surrounding <= 0) = size(labels, 1) + 1; %surrounding(surrounding > size(hex, 1)) = size(labels, 1)+1; % set the label of the dummy element to be zero(background) labels(size(labels, 1)+1) = 0; % matrixs holding the label of each surrounding element %surroundinglabels = labels(surrounding); surroundinglabels = zeros((x_dim+1)*(y_dim+1)*(z_dim+1), 8); surroundinglabels((nodes(b, 1) < x_dim) & (nodes(b, 3) < z_dim), 1) = labels(offset((nodes(b, 1) < x_dim) & (nodes(b, 3) < z_dim))); surroundinglabels(nodes(b, 1) > 0, 2) = labels(offset(nodes(b, 1) > 0, 1) -1); surroundinglabels(nodes(b, 2) > 0, 3) = labels(offset(nodes(b, 2) > 0, 1) - x_dim); offsetnow = offset((nodes(b, 2) > 0) & (nodes(b, 1) > 0), 1) - (x_dim) - 1; offsetnow(offsetnow <= 0) = size(labels, 1)+1; surroundinglabels((nodes(b, 2) > 0) & (nodes(b, 1) > 0), 4) = labels(offsetnow); offsetnow = offset(nodes(b, 3) > 0, 1) - (x_dim)*(y_dim); offsetnow(offsetnow <= 0) = size(labels, 1)+1; surroundinglabels(nodes(b, 3) > 0, 5) = labels(offsetnow); offsetnow = offset(nodes(b, 3) > 0, 1) - (x_dim)*(y_dim) - 1; offsetnow(offsetnow <= 0) = size(labels, 1)+1; surroundinglabels(nodes(b, 3) > 0, 6) = labels(offsetnow); offsetnow = offset(nodes(b, 3) > 0, 1) - (x_dim)*(y_dim) - x_dim; offsetnow(offsetnow <= 0) = size(labels, 1)+1; surroundinglabels(nodes(b, 3) > 0, 7) = labels(offsetnow); offsetnow = offset((nodes(b, 3) > 0) & (nodes(b, 2) > 0), 1) - (x_dim)*(y_dim) - (x_dim) -1; offsetnow(offsetnow <= 0) = size(labels, 1)+1; surroundinglabels((nodes(b, 3) > 0) & (nodes(b, 2) > 0), 8) = labels(offsetnow); % matrix showing how many types of each label are around a given node distribution = zeros(size(nodes, 1), size(unique(labels), 1)); % the following assumes that the labels are 1, 2, ... for l = 1:size(unique(labels), 1) for k = 1:8 distribution(:, l) = distribution(:, l) + (surroundinglabels(:, k) == l); end end % fill up the last column with the amount of background labels distribution(:, (size(unique(labels), 1))) = 8 - sum(distribution(:, 1:size(unique(labels), 1))'); % how many different labels are there around each node distsum = sum(distribution>0, 2); % set zeros to Inf in order to make the finding of a minimum % meaningful distribution(distribution == 0) = Inf; % find out which is the minority label [mins, minpos] = min(distribution, [], 2); clear distribution; % calculate the centroid for each element centroids = zeros(size(hex, 1), 3); for l = 1:3 centroids(:, l) = sum(reshape(nodes(hex(:, :), l), size(hex, 1), 8)')'/8; end % set a dummy centroid centroids(size(centroids, 1) +1, :) = 0; tbc = zeros(size(surroundinglabels)); % helper matrix, c(i, j, k) is one when surroundinglabels(i, j) == k for i = 1:size(unique(labels), 1)+1 c = zeros(size(surroundinglabels, 2), size(unique(labels), 1)+1); if (i == size(unique(labels), 1)+1) c = surroundinglabels == 0; else c = surroundinglabels == i; end tbc(ismember(minpos, i) == 1, :) = c(ismember(minpos, i) == 1, :); end % % matrix that shows which elements are to be considered as minority % % around a given node % clear surroundinglabels; % % helper matrix, c(i, j, k) is one when surroundinglabels(i, j) == k % c = zeros(size(surroundinglabels, 1), size(surroundinglabels, 2), size(unique(labels), 1)+1); % for i = 1:size(unique(labels), 1) % c(:, :, i) = surroundinglabels == i; % end % c(:, :, size(unique(labels), 1)+1) = surroundinglabels == 0; % % % % matrix that shows which elements are to be considered as minority % % around a given node % tbc = zeros(size(surroundinglabels)); % clear surroundinglabels; % for i = 1:size(unique(labels), 1)+1 % tbc(ismember(minpos, i) == 1, :) = c(ismember(minpos, i) == 1, :, i); % end clear c; % delete cases in which we don't have a real minimum tbcsum = sum(tbc, 2); tbc(tbcsum == 8, :) = 0; tbc(tbcsum == 4, :) = 0; tbcsum((distsum>2) & (mins > 1), :) = 0; tbcsum(tbcsum == 8) = 0; tbcsum(tbcsum == 4) = 0; tbcsum((distsum>2) & (mins > 1)) = 0; %surroundingconsidered = surrounding.*tbc; surroundingconsidered = zeros(size(tbc)); surroundingconsidered((nodes(b, 1) < x_dim) & (nodes(b, 3) < z_dim), 1) = offset((nodes(b, 1) < x_dim) & (nodes(b, 3) < z_dim)).*tbc((nodes(b, 1) < x_dim) & (nodes(b, 3) < z_dim), 1); surroundingconsidered(nodes(b, 1) > 0, 2) = (offset(nodes(b, 1) > 0, 1) -1).*(tbc(nodes(b, 1) > 0, 2)); surroundingconsidered(nodes(b, 2) > 0, 3) = (offset(nodes(b, 2) > 0, 1) - x_dim).*tbc(nodes(b, 2) > 0, 3); surroundingconsidered((nodes(b, 2) > 0) & (nodes(b, 1) > 0), 4) = (offset((nodes(b, 2) > 0) & (nodes(b, 1) > 0), 1) - (x_dim) - 1).*tbc((nodes(b, 2) > 0) & (nodes(b, 1) > 0), 4).*tbc((nodes(b, 2) > 0) & (nodes(b, 1) > 0), 4); surroundingconsidered(nodes(b, 3) > 0, 5) = (offset(nodes(b, 3) > 0, 1) - (x_dim)*(y_dim)).*tbc(nodes(b, 3) > 0, 5); surroundingconsidered(nodes(b, 3) > 0, 6) = (offset(nodes(b, 3) > 0, 1) - (x_dim)*(y_dim) - 1).*tbc(nodes(b, 3) > 0, 6); surroundingconsidered(nodes(b, 3) > 0, 7) = (offset(nodes(b, 3) > 0, 1) - (x_dim)*(y_dim) - x_dim).*tbc(nodes(b, 3) > 0, 7); surroundingconsidered((nodes(b, 3) > 0) & (nodes(b, 2) > 0), 8) = (offset((nodes(b, 3) > 0) & (nodes(b, 2) > 0), 1) - (x_dim)*(y_dim) - (x_dim) -1).*tbc((nodes(b, 3) > 0) & (nodes(b, 2) > 0), 8); %clear surrounding; clear tbc; tbcsum(tbcsum == 8) = 0; tbcsum(tbcsum == 4) = 0; tbcsum((distsum>2) & (mins > 1)) = 0; clear distsum; % get the surrounding elements which are to be considered for the shift % use the dummy centroid to make computations easier surroundingconsidered(surroundingconsidered == 0) = size(centroids, 1); % calculate the combination of the centroids which are to be considered % for the shift centroidcomb = zeros(size(nodes)); centroidcomb(:, 1) = sum(reshape(centroids(surroundingconsidered, 1), [], 8), 2); centroidcomb(:, 2) = sum(reshape(centroids(surroundingconsidered, 2), [], 8), 2); centroidcomb(:, 3) = sum(reshape(centroids(surroundingconsidered, 3), [], 8), 2); clear surroundingconsidered; centroidcomb(tbcsum ~= 0, 1) = centroidcomb(tbcsum ~= 0, 1)./tbcsum(tbcsum ~= 0); centroidcomb(tbcsum ~= 0, 2) = centroidcomb(tbcsum ~= 0, 2)./tbcsum(tbcsum ~= 0); centroidcomb(tbcsum ~= 0, 3) = centroidcomb(tbcsum ~= 0, 3)./tbcsum(tbcsum ~= 0); % finally apply the shift nodes(tbcsum == 0, :) = points(tbcsum == 0, :); nodes(tbcsum ~= 0, :) = (1-sh)*nodes(tbcsum ~= 0, :) + sh*centroidcomb(tbcsum ~= 0, :); end %subfunction
github
lcnbeapp/beapp-master
read_labview_dtlg.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/read_labview_dtlg.m
5,089
utf_8
dc63845970397d9529684d354d5ce39b
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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ 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
lcnbeapp/beapp-master
sphericalSplineInterpolate.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/private/sphericalSplineInterpolate.m
5,226
utf_8
27ce6fd83adee8c3957c477f73dad771
function [W,Gss,Gds,Hds]=sphericalSplineInterpolate(src,dest,lambda,order,type,tol) %interpolate matrix for spherical interpolation % % W = sphericalSplineInterpolate(src,dest,lambda,order,type,tol) % % Inputs: % src - [3 x N] old electrode positions % dest - [3 x M] new electrode positions % lambda - [float] regularisation parameter for smoothing the estimates (1e-5) % order - [float] order of the polynomial interplotation to use (4) % type - [str] one of; ('spline') % 'spline' - spherical Spline % 'slap' - surface Laplician (aka. CSD) % tol - [float] tolerance for the legendre poly approx (1e-7) % Outputs: % W - [M x N] linear mapping matrix between old and new co-ords % % Based upon the paper: Perrin89 % Copyright 2009- by Jason D.R. Farquhar ([email protected]) % Permission is granted for anyone to copy, use, or modify this % software and accompanying documents, provided this copyright % notice is retained, and note is made of any changes that have been % made. This software and documents are distributed without any % warranty, express or implied. if ( nargin < 3 || isempty(lambda) ) lambda=1e-5; end; if ( nargin < 4 || isempty(order) ) order=4; end; if ( nargin < 5 || isempty(type)) type='spline'; end; if ( nargin < 6 || isempty(tol) ) tol=eps; end; % map the positions onto the sphere (not using repop, by JMH) src = src ./repmat(sqrt(sum(src.^2)), size(src, 1), 1); % src = repop(src,'./',sqrt(sum(src.^2))); dest = dest./repmat(sqrt(sum(dest.^2)), size(dest, 1), 1); % dest = repop(dest,'./',sqrt(sum(dest.^2))); %calculate the cosine of the angle between the new and old electrodes. If %the vectors are on top of each other, the result is 1, if they are %pointing the other way, the result is -1 cosSS = src'*src; % angles between source positions cosDS = dest'*src; % angles between destination positions % Compute the interpolation matrix to tolerance tol [Gss] = interpMx(cosSS,order,tol); % [nSrc x nSrc] [Gds Hds] = interpMx(cosDS,order,tol); % [nDest x nSrc] % Include the regularisation if ( lambda>0 ) Gss = Gss+lambda*eye(size(Gss)); end; % Compute the mapping to the polynomial coefficients space % [nSrc+1 x nSrc+1] % N.B. this can be numerically unstable so use the PINV to solve.. muGss=1;%median(diag(Gss)); % used to improve condition number when inverting. Probably uncessary %C = [ Gss muGss*ones(size(Gss,1),1)]; C = [ Gss muGss*ones(size(Gss,1),1);... muGss*ones(1,size(Gss,2)) 0]; iC = pinv(C); % Compute the mapping from source measurements and positions to destination positions if ( strcmp(lower(type),'spline') ) W = [Gds ones(size(Gds,1),1).*muGss]*iC(:,1:end-1); % [nDest x nSrc] elseif (strcmp(lower(type),'slap')) W = Hds*iC(1:end-1,1:end-1);%(:,1:end-1); % [nDest x nSrc] end return; %-------------------------------------------------------------------------- function [G,H]=interpMx(cosEE,order,tol) % compute the interpolation matrix for this set of point pairs if ( nargin < 3 || isempty(tol) ) tol=1e-10; end; G=zeros(size(cosEE)); H=zeros(size(cosEE)); for i=1:numel(cosEE); x = cosEE(i); n=1; Pns1=1; Pn=x; % seeds for the legendre ploy recurence tmp = ( (2*n+1) * Pn ) / ((n*n+n).^order); G(i) = tmp ; % 1st element in the sum H(i) = (n*n+n)*tmp; % 1st element in the sum oGi=inf; dG=abs(G(i)); oHi=inf; dH=abs(H(i)); for n=2:500; % do the sum Pns2=Pns1; Pns1=Pn; Pn=((2*n-1)*x*Pns1 - (n-1)*Pns2)./n; % legendre poly recurance oGi=G(i); oHi=H(i); tmp = ((2*n+1) * Pn) / ((n*n+n).^order) ; G(i) = G(i) + tmp; % update function estimate, spline interp H(i) = H(i) + (n*n+n)*tmp; % update function estimate, SLAP dG = (abs(oGi-G(i))+dG)/2; dH=(abs(oHi-H(i))+dH)/2; % moving ave gradient est for convergence %fprintf('%d) dG =%g \t dH = %g\n',n,dG,dH);%abs(oGi-G(i)),abs(oHi-H(i))); if ( dG<tol && dH<tol ) break; end; % stop when tol reached end end G= G./(4*pi); H= H./(4*pi); return; %-------------------------------------------------------------------------- function testCase() src=randn(3,100); src(3,:)=abs(src(3,:)); src=repop(src,'./',sqrt(sum(src.^2))); % source points on sphere dest=rand(3,30); dest(3,:)=abs(dest(3,:)); dest=repop(dest,'./',sqrt(sum(dest.^2))); % dest points on sphere clf;scatPlot(src,'b.'); W=sphericalSplineInterpolate(src,dest); W=sphericalSplineInterpolate(src(:,1:70),src); clf;imagesc(W); clf;jplot(src(1:2,1:70),W(70:75,:)'); z=jf_load('eeg/vgrid/nips2007/1-rect230ms','jh','flip_rc_sep'); z=jf_retain(z,'dim','ch','idx',[z.di(1).extra.iseeg]); lambda=0; order=4; chPos=[z.di(1).extra.pos3d]; incIdx=1:size(dest,2)-3; exIdx=setdiff(1:size(dest,2),incIdx); % included + excluded channels W=sphericalSplineInterpolate(chPos(:,incIdx),chPos,lambda,order); % estimate the removed channels clf;imagesc(W); clf;jplot(chPos(:,incIdx),W(exIdx,:)'); % compare estimated with true X=z.X(:,:,2); Xest=W*z.X(incIdx,:,2); clf;mcplot([X(exIdx(1),:);Xest(exIdx(1),:)]') clf;subplot(211);mcplot(X');subplot(212);mcplot(Xest');
github
lcnbeapp/beapp-master
ft_write_cifti.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/ft_write_cifti.m
31,321
utf_8
b43578a0120b4ea370bcde78c9bb3034
function ft_write_cifti(filename, source, varargin) % FT_WRITE_CIFTI writes functional data or functional connectivity to a cifti-2 % file. The geometrical description of the brainordinates can consist of % triangulated surfaces or voxels in a regular 3-D volumetric grid. The functional % data can consist of a dense or a parcellated representation. Furthermore, it % writes the geometrical description of the surfaces to one or multiple gifti % files. % % Use as % ft_write_cifti(filename, data, ...) % where the filename is a string and the data according to the description below. % % If the input data describes a dense representation of functional data, the data % structure should conform to the FT_DATATYPE_SOURCE or FT_DATATYPE_VOLUME % definition. % % If the input data describes a parcellated representation of functional data, the % data structure should conform to the FT_DATATYPE_TIMELOCK or FT_DATATYPE_FREQ % definition. In addition, the description of the geometry should be specified in % the data.brainordinate field, which should conform to the FT_DATATYPE_SOURCE or % FT_DATATYPE_VOLUME definition. % % Any optional input arguments should come in key-value pairs and may include % 'parameter' = string, fieldname that contains the functional data % 'brainstructure' = string, fieldname that describes the brain structures (default = 'brainstructure') % 'parcellation' = string, fieldname that describes the parcellation (default = 'parcellation') % 'precision' = string, can be 'single', 'double', 'int32', etc. (default ='single') % 'writesurface' = boolean, can be false or true (default = true) % 'debug' = boolean, write a debug.xml file (default = false) % % The brainstructure refers to the global anatomical structure, such as CortexLeft, Thalamus, etc. % The parcellation refers to the the detailled parcellation, such as BA1, BA2, BA3, etc. % % See also FT_READ_CIFTI, FT_READ_MRI, FT_WRITE_MRI % Copyright (C) 2013-2015, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ parameter = ft_getopt(varargin, 'parameter'); brainstructure = ft_getopt(varargin, 'brainstructure'); % the default is determined further down parcellation = ft_getopt(varargin, 'parcellation'); % the default is determined further down precision = ft_getopt(varargin, 'precision', 'single'); writesurface = ft_getopt(varargin, 'writesurface', true); debug = ft_getopt(varargin, 'debug', false); if isfield(source, 'brainordinate') % this applies to a parcellated data representation % copy the geometrical description over in to the main structure source = copyfields(source.brainordinate, source, fieldnames(source.brainordinate)); source = rmfield(source, 'brainordinate'); end if isempty(brainstructure) && isfield(source, 'brainstructure') && isfield(source, 'brainstructurelabel') % these fields are asumed to be present from ft_read_cifti brainstructure = 'brainstructure'; end if isempty(parcellation) && isfield(source, 'parcellation') && isfield(source, 'parcellationlabel') % these fields are asumed to be present from ft_read_cifti parcellation = 'parcellation'; end if isfield(source, 'inside') && islogical(source.inside) % convert into an indexed representation source.inside = find(source.inside(:)); end if isfield(source, 'dim') && ~isfield(source, 'transform') % ensure that the volumetric description contains both dim and transform source.transform = pos2transform(source.pos); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% dat = source.(parameter); dimord = getdimord(source, parameter); switch dimord case {'pos' 'pos_scalar'} % NIFTI_INTENT_CONNECTIVITY_DENSE_SCALARS extension = '.dscalar.nii'; intent_code = 3006; intent_name = 'ConnDenseScalar'; dat = transpose(dat); dimord = 'scalar_pos'; case 'pos_pos' % NIFTI_INTENT_CONNECTIVITY_DENSE extension = '.dconn.nii'; intent_code = 3001; intent_name = 'ConnDense'; case 'pos_time' % NIFTI_INTENT_CONNECTIVITY_DENSE_SERIES extension = '.dtseries.nii'; intent_code = 3002; intent_name = 'ConnDenseSeries'; dat = transpose(dat); dimord = 'time_pos'; case 'pos_freq' % NIFTI_INTENT_CONNECTIVITY_DENSE_SERIES extension = '.dtseries.nii'; intent_code = 3002; intent_name = 'ConnDenseSeries'; dat = transpose(dat); dimord = 'freq_pos'; case {'chan' 'chan_scalar'} % NIFTI_INTENT_CONNECTIVITY_PARCELLATED_SCALARS extension = '.pscalar.nii'; intent_code = 3006; intent_name = 'ConnParcelScalr'; % due to length constraints of the NIfTI header field, the last "a" is removed dat = transpose(dat); dimord = 'scalar_chan'; case 'chan_chan' % NIFTI_INTENT_CONNECTIVITY_PARCELLATED extension = '.pconn.nii'; intent_code = 3003; intent_name = 'ConnParcels'; case 'chan_time' % NIFTI_INTENT_CONNECTIVITY_PARCELLATED_SERIES extension = '.ptseries.nii'; intent_code = 3004; intent_name = 'ConnParcelSries'; % due to length constraints of the NIfTI header field, the first "e" is removed dat = transpose(dat); dimord = 'time_chan'; case 'chan_freq' % NIFTI_INTENT_CONNECTIVITY_PARCELLATED_SERIES extension = '.ptseries.nii'; intent_code = 3004; intent_name = 'ConnParcelSries'; % due to length constraints of the NIfTI header field, the first "e" is removed dat = transpose(dat); dimord = 'freq_chan'; case {'chan_chan_time' 'chan_chan_freq'} % NIFTI_INTENT_CONNECTIVITY_PARCELLATED_PARCELLATED_SERIES extension = '.pconnseries.nii'; intent_code = 3011; intent_name = 'ConnPPSr'; case {'pos_pos_time' 'pos_pos_freq'} % this is not part of the Cifti v2 specification, but would have been NIFTI_INTENT_CONNECTIVITY_DENSE_DENSE_SERIES extension = '.dconnseries.nii'; % user's choise intent_code = 3000; intent_name = 'ConnUnknown'; otherwise error('unsupported dimord "%s"', dimord); end % switch % determine each of the dimensions dimtok = tokenize(dimord, '_'); [p, f, x] = fileparts(filename); if isequal(x, '.nii') filename = fullfile(p, f); % strip the extension end [p, f, x] = fileparts(filename); if any(isequal(x, {'.dtseries', '.ptseries', '.dconn', '.pconn', '.dscalar', '.pscalar'})) filename = fullfile(p, f); % strip the extension end % add the full cifti extension to the filename [p, f, x] = fileparts(filename); filename = fullfile(p, [f x extension]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get the description of the geometry %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ModelType = zeros(size(source.pos,1), 1); ModelTypelabel = {'SURFACE', 'VOXEL'}; if isfield(source, 'transform') tolerance = 0.01; % in milimeter ijk = ft_warp_apply(inv(source.transform), source.pos); % convert from xyz to ijk sel = sqrt(sum((ijk - round(ijk)).^2,2))<tolerance; % note that some surface points might be marked as voxel if they happen to fall on a grid point ModelType(~sel) = 1; % surface ModelType( sel) = 2; % voxel else ModelType(:) = 1; % surface end if isfield(source, brainstructure) BrainStructure = source.( brainstructure ); BrainStructurelabel = source.([brainstructure 'label']); elseif isfield(source, 'pos') BrainStructure = ones(size(source.pos,1),1); BrainStructurelabel = {'INVALID'}; end if isfield(source, parcellation) Parcellation = source.( parcellation ); Parcellationlabel = source.([parcellation 'label']); elseif isfield(source, 'pos') Parcellation = ones(size(source.pos,1),1); Parcellationlabel = {'INVALID'}; end % ensure that these are column vectors try, BrainStructure = BrainStructure(:); end try, Parcellation = Parcellation(:); end list1 = { 'CIFTI_STRUCTURE_CORTEX_LEFT' 'CIFTI_STRUCTURE_CORTEX_RIGHT' 'CIFTI_STRUCTURE_CEREBELLUM' 'CIFTI_STRUCTURE_ACCUMBENS_LEFT' 'CIFTI_STRUCTURE_ACCUMBENS_RIGHT' 'CIFTI_STRUCTURE_ALL_GREY_MATTER' 'CIFTI_STRUCTURE_ALL_WHITE_MATTER' 'CIFTI_STRUCTURE_AMYGDALA_LEFT' 'CIFTI_STRUCTURE_AMYGDALA_RIGHT' 'CIFTI_STRUCTURE_BRAIN_STEM' 'CIFTI_STRUCTURE_CAUDATE_LEFT' 'CIFTI_STRUCTURE_CAUDATE_RIGHT' 'CIFTI_STRUCTURE_CEREBELLAR_WHITE_MATTER_LEFT' 'CIFTI_STRUCTURE_CEREBELLAR_WHITE_MATTER_RIGHT' 'CIFTI_STRUCTURE_CEREBELLUM_LEFT' 'CIFTI_STRUCTURE_CEREBELLUM_RIGHT' 'CIFTI_STRUCTURE_CEREBRAL_WHITE_MATTER_LEFT' 'CIFTI_STRUCTURE_CEREBRAL_WHITE_MATTER_RIGHT' 'CIFTI_STRUCTURE_CORTEX' 'CIFTI_STRUCTURE_DIENCEPHALON_VENTRAL_LEFT' 'CIFTI_STRUCTURE_DIENCEPHALON_VENTRAL_RIGHT' 'CIFTI_STRUCTURE_HIPPOCAMPUS_LEFT' 'CIFTI_STRUCTURE_HIPPOCAMPUS_RIGHT' 'CIFTI_STRUCTURE_INVALID' 'CIFTI_STRUCTURE_OTHER' 'CIFTI_STRUCTURE_OTHER_GREY_MATTER' 'CIFTI_STRUCTURE_OTHER_WHITE_MATTER' 'CIFTI_STRUCTURE_PALLIDUM_LEFT' 'CIFTI_STRUCTURE_PALLIDUM_RIGHT' 'CIFTI_STRUCTURE_PUTAMEN_LEFT' 'CIFTI_STRUCTURE_PUTAMEN_RIGHT' 'CIFTI_STRUCTURE_THALAMUS_LEFT' 'CIFTI_STRUCTURE_THALAMUS_RIGHT' }; list2 = { 'CORTEX_LEFT' 'CORTEX_RIGHT' 'CEREBELLUM' 'ACCUMBENS_LEFT' 'ACCUMBENS_RIGHT' 'ALL_GREY_MATTER' 'ALL_WHITE_MATTER' 'AMYGDALA_LEFT' 'AMYGDALA_RIGHT' 'BRAIN_STEM' 'CAUDATE_LEFT' 'CAUDATE_RIGHT' 'CEREBELLAR_WHITE_MATTER_LEFT' 'CEREBELLAR_WHITE_MATTER_RIGHT' 'CEREBELLUM_LEFT' 'CEREBELLUM_RIGHT' 'CEREBRAL_WHITE_MATTER_LEFT' 'CEREBRAL_WHITE_MATTER_RIGHT' 'CORTEX' 'DIENCEPHALON_VENTRAL_LEFT' 'DIENCEPHALON_VENTRAL_RIGHT' 'HIPPOCAMPUS_LEFT' 'HIPPOCAMPUS_RIGHT' 'INVALID' 'OTHER' 'OTHER_GREY_MATTER' 'OTHER_WHITE_MATTER' 'PALLIDUM_LEFT' 'PALLIDUM_RIGHT' 'PUTAMEN_LEFT' 'PUTAMEN_RIGHT' 'THALAMUS_LEFT' 'THALAMUS_RIGHT' }; % replace the short name with the long name, i.e add 'CIFTI_STRUCTURE_' where applicable [dum, indx1, indx2] = intersect(BrainStructurelabel, list2); BrainStructurelabel(indx1) = list1(indx2); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % construct the XML object describing the geometry %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ensure that the external toolbox is present, this adds gifti/@xmltree ft_hastoolbox('gifti', 1); tree = xmltree; tree = set(tree, 1, 'name', 'CIFTI'); tree = attributes(tree, 'add', find(tree, 'CIFTI'), 'Version', '2'); tree = add(tree, find(tree, 'CIFTI'), 'element', 'Matrix'); % The cifti file contains one Matrix, which contains one or multiple MatrixIndicesMap, each containing % CIFTI_INDEX_TYPE_BRAIN_MODELS The dimension represents one or more brain models. % CIFTI_INDEX_TYPE_PARCELS The dimension represents a parcellation scheme. % CIFTI_INDEX_TYPE_SERIES The dimension represents a series of regular samples. % CIFTI_INDEX_TYPE_SCALARS The dimension represents named scalar maps. % CIFTI_INDEX_TYPE_LABELS The dimension represents named label maps. if any(strcmp(dimtok, 'time')) % construct the MatrixIndicesMap for the time axis in the data % NumberOfSeriesPoints="2" SeriesExponent="0" SeriesStart="0.0000000000" SeriesStep="1.0000000000" SeriesUnit="SECOND" tree = add(tree, find(tree, 'CIFTI/Matrix'), 'element', 'MatrixIndicesMap'); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap'); branch = branch(end); if length(source.time)>1 SeriesStep = median(diff(source.time)); % this assumes evenly spaced samples else SeriesStep = 0; end tree = attributes(tree, 'add', branch, 'AppliesToMatrixDimension', printwithcomma(find(strcmp(dimtok, 'time'))-1)); tree = attributes(tree, 'add', branch, 'IndicesMapToDataType', 'CIFTI_INDEX_TYPE_SERIES'); tree = attributes(tree, 'add', branch, 'NumberOfSeriesPoints', num2str(length(source.time))); tree = attributes(tree, 'add', branch, 'SeriesExponent', num2str(0)); tree = attributes(tree, 'add', branch, 'SeriesStart', num2str(source.time(1))); tree = attributes(tree, 'add', branch, 'SeriesStep', num2str(SeriesStep)); tree = attributes(tree, 'add', branch, 'SeriesUnit', 'SECOND'); end % if time if any(strcmp(dimtok, 'freq')) % construct the MatrixIndicesMap for the frequency axis in the data % NumberOfSeriesPoints="2" SeriesExponent="0" SeriesStart="0.0000000000" SeriesStep="1.0000000000" SeriesUnit="HZ" tree = add(tree, find(tree, 'CIFTI/Matrix'), 'element', 'MatrixIndicesMap'); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap'); branch = branch(end); if length(source.freq)>1 SeriesStep = median(diff(source.freq)); % this assumes evenly spaced samples else SeriesStep = 0; end tree = attributes(tree, 'add', branch, 'AppliesToMatrixDimension', printwithcomma(find(strcmp(dimtok, 'freq'))-1)); tree = attributes(tree, 'add', branch, 'IndicesMapToDataType', 'CIFTI_INDEX_TYPE_SCALARS'); tree = attributes(tree, 'add', branch, 'NumberOfSeriesPoints', num2str(length(source.freq))); tree = attributes(tree, 'add', branch, 'SeriesExponent', num2str(0)); tree = attributes(tree, 'add', branch, 'SeriesStart', num2str(source.freq(1))); tree = attributes(tree, 'add', branch, 'SeriesStep', num2str(SeriesStep)); tree = attributes(tree, 'add', branch, 'SeriesUnit', 'HZ'); end % if freq if any(strcmp(dimtok, 'scalar')) tree = add(tree, find(tree, 'CIFTI/Matrix'), 'element', 'MatrixIndicesMap'); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap'); branch = branch(end); tree = attributes(tree, 'add', branch, 'AppliesToMatrixDimension', printwithcomma(find(strcmp(dimtok, 'scalar'))-1)); tree = attributes(tree, 'add', branch, 'IndicesMapToDataType', 'CIFTI_INDEX_TYPE_SCALARS'); tree = add(tree, branch, 'element', 'NamedMap'); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/NamedMap'); branch = branch(end); [tree, uid] = add(tree, branch, 'element', 'MapName'); tree = add(tree, uid, 'chardata', parameter); end % if not freq and time if any(strcmp(dimtok, 'pos')) % construct the MatrixIndicesMap for the geometry tree = add(tree, find(tree, 'CIFTI/Matrix'), 'element', 'MatrixIndicesMap'); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap'); branch = branch(end); tree = attributes(tree, 'add', branch, 'AppliesToMatrixDimension', printwithcomma(find(strcmp(dimtok, 'pos'))-1)); tree = attributes(tree, 'add', branch, 'IndicesMapToDataType', 'CIFTI_INDEX_TYPE_BRAIN_MODELS'); if isfield(source, 'dim') switch source.unit case 'mm' MeterExponent = -3; case 'cm' MeterExponent = -2; case 'dm' MeterExponent = -1; case 'm' MeterExponent = 0; otherwise error('unsupported source.unit') end % case [tree, uid] = add(tree, branch, 'element', 'Volume'); tree = attributes(tree, 'add', uid, 'VolumeDimensions', printwithcomma(source.dim)); [tree, uid] = add(tree, uid, 'element', 'TransformationMatrixVoxelIndicesIJKtoXYZ'); tree = attributes(tree, 'add', uid, 'MeterExponent', num2str(MeterExponent)); tree = add(tree, uid, 'chardata', printwithspace(source.transform')); % it needs to be transposed end for i=1:length(BrainStructurelabel) % write one brainstructure for each group of vertices if isempty(regexp(BrainStructurelabel{i}, '^CIFTI_STRUCTURE_', 'once')) BrainStructurelabel{i} = ['CIFTI_STRUCTURE_' BrainStructurelabel{i}]; end sel = (BrainStructure==i); IndexCount = sum(sel); IndexOffset = find(sel, 1, 'first') - 1; % zero offset branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap'); branch = branch(end); tree = add(tree, branch, 'element', 'BrainModel'); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/BrainModel'); branch = branch(end); if all(ModelType(sel)==find(strcmp(ModelTypelabel, 'VOXEL'))) tree = attributes(tree, 'add', branch, 'IndexOffset', printwithspace(IndexOffset)); tree = attributes(tree, 'add', branch, 'IndexCount', printwithspace(IndexCount)); tree = attributes(tree, 'add', branch, 'ModelType', 'CIFTI_MODEL_TYPE_VOXELS'); tree = attributes(tree, 'add', branch, 'BrainStructure', BrainStructurelabel{i}); tree = add(tree, branch, 'element', 'VoxelIndicesIJK'); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/BrainModel/VoxelIndicesIJK'); branch = branch(end); tmp = source.pos(sel,:); tmp = ft_warp_apply(inv(source.transform), tmp); tmp = round(tmp)' - 1; % transpose, zero offset tree = add(tree, branch, 'chardata', printwithspace(tmp)); else tmp = find(sel)-IndexOffset-1; % zero offset tree = attributes(tree, 'add', branch, 'IndexOffset', printwithspace(IndexOffset)); tree = attributes(tree, 'add', branch, 'IndexCount', printwithspace(IndexCount)); tree = attributes(tree, 'add', branch, 'ModelType', 'CIFTI_MODEL_TYPE_SURFACE'); tree = attributes(tree, 'add', branch, 'BrainStructure', BrainStructurelabel{i}); tree = attributes(tree, 'add', branch, 'SurfaceNumberOfVertices', printwithspace(IndexCount)); tree = add(tree, branch, 'element', 'VertexIndices'); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/BrainModel/VertexIndices'); branch = branch(end); tree = add(tree, branch, 'chardata', printwithspace(tmp)); end end % for each BrainStructurelabel end % if pos if any(strcmp(dimtok, 'chan')) tree = add(tree, find(tree, 'CIFTI/Matrix'), 'element', 'MatrixIndicesMap'); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap'); branch = branch(end); tree = attributes(tree, 'add', branch, 'AppliesToMatrixDimension', printwithcomma(find(strcmp(dimtok, 'chan'))-1)); tree = attributes(tree, 'add', branch, 'IndicesMapToDataType', 'CIFTI_INDEX_TYPE_PARCELS'); if isfield(source, 'dim') switch source.unit case 'mm' MeterExponent = -3; case 'cm' MeterExponent = -2; case 'dm' MeterExponent = -1; case 'm' MeterExponent = 0; otherwise error('unsupported source.unit') end % case [tree, uid] = add(tree, branch, 'element', 'Volume'); tree = attributes(tree, 'add', uid, 'VolumeDimensions', printwithcomma(source.dim)); [tree, uid] = add(tree, uid, 'element', 'TransformationMatrixVoxelIndicesIJKtoXYZ'); tree = attributes(tree, 'add', uid, 'MeterExponent', num2str(MeterExponent)); tree = add(tree, uid, 'chardata', printwithspace(source.transform')); % it needs to be transposed end % surfaces are described with vertex positions (pos/pnt) and triangles (tri) if isfield(source, 'pos') && isfield(source, 'tri') % there is a surface description for i=1:length(BrainStructurelabel) sel = find(BrainStructure~=i); [mesh.pnt, mesh.tri] = remove_vertices(source.pos, source.tri, sel); mesh.unit = source.unit; if isempty(mesh.pnt) || isempty(mesh.tri) % the brainordinate positions in this brain structure are not connected with triangles, i.e. in the case of voxels continue; end [tree, uid] = add(tree, branch, 'element', 'Surface'); tree = attributes(tree, 'add', uid, 'BrainStructure', BrainStructurelabel{i}); tree = attributes(tree, 'add', uid, 'SurfaceNumberOfVertices', printwithspace(size(mesh.pnt,1))); end end % if tri parcel = source.label; % channels are used to represent parcels for i=1:numel(parcel) indx = find(strcmp(Parcellationlabel, parcel{i})); if isempty(indx) continue end selParcel = (Parcellation==indx); structure = BrainStructurelabel(unique(BrainStructure(selParcel))); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap'); branch = branch(end); tree = add(tree, branch, 'element', 'Parcel'); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/Parcel'); branch = branch(end); tree = attributes(tree, 'add', branch, 'Name', parcel{i}); % this is for pretty printing maxparcellen = max(cellfun(@length, parcel)); for j=1:length(structure) selStructure = (BrainStructure==find(strcmp(BrainStructurelabel, structure{j}))); indx = find(selParcel & selStructure); offset = find(selStructure, 1, 'first') - 1; fprintf('parcel %s contains %5d vertices in %s\n', stringpad(parcel{i}, maxparcellen), length(indx), structure{j}); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/Parcel'); branch = branch(end); if all(ModelType(selStructure)==find(strcmp(ModelTypelabel, 'VOXEL'))) tree = add(tree, branch, 'element', 'VoxelIndicesIJK'); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/Parcel/VoxelIndicesIJK'); branch = branch(end); tmp = ft_warp_apply(inv(source.transform), source.pos(indx,:)); tmp = round(tmp)' - 1; % transpose, zero offset tree = add(tree, branch, 'chardata', printwithspace(tmp)); else tree = add(tree, branch, 'element', 'Vertices'); branch = find(tree, 'CIFTI/Matrix/MatrixIndicesMap/Parcel/Vertices'); branch = branch(end); tree = attributes(tree, 'add', branch, 'BrainStructure', structure{j}); tmp = indx - offset - 1; tree = add(tree, branch, 'chardata', printwithspace(tmp)); end end % for each structure contained in this parcel end % for each parcel end % if chan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % write everything to file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 4 bytes with the size of the header, 384 for nifti-1 or 540 for nifti-2 % 540 bytes with the nifti-2 header % 4 bytes that indicate the presence of a header extension [1 0 0 0] % 4 bytes with the size of the header extension in big endian? % 4 bytes with the header extension code NIFTI_ECODE_CIFTI [0 0 0 32] % variable number of bytes with the xml section, at the end there might be some empty "junk" % 8 bytes, presumaby with the size and type? % variable number of bytes with the voxel data xmlfile = [tempname '.xml']; % this will contain the cifti XML structure save(tree, xmlfile); % write the XMLTREE object to disk xmlfid = fopen(xmlfile, 'rb'); xmldat = fread(xmlfid, [1, inf], 'char'); fclose(xmlfid); % we do not want the content of the XML elements to be nicely formatted, as it might create confusion when reading % therefore detect and remove whitespace immediately following a ">" and preceding a "<" whitespace = false(size(xmldat)); gt = int8('>'); lt = int8('<'); ws = int8(sprintf(' \t\r\n')); b = find(xmldat==gt); e = find(xmldat==lt); b = b(1:end-1); % the XML section ends with ">", this is not of relevance e = e(2:end); % the XML section starts with "<", this is not of relevance b = b+1; e = e-1; for i=1:length(b) for j=b(i):1:e(i) if any(ws==xmldat(j)) whitespace(j) = true; else break end end end for i=1:length(b) for j=e(i):-1:b(i) if any(ws==xmldat(j)) whitespace(j) = true; else break end end end % keep it if there is _only_ whitespace between the ">" and "<" for i=1:length(b) if all(whitespace(b(i):e(i))) whitespace(b(i):e(i)) = false; end end % remove the padding whitespace xmldat = xmldat(~whitespace); % the header extension needs to be aligned xmlsize = length(xmldat); xmlpad = ceil((xmlsize+8)/16)*16 - (xmlsize+8); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % construct the NIFTI-2 header %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% hdr.magic = [110 43 50 0 13 10 26 10]; % see http://nifti.nimh.nih.gov/nifti-1/documentation/nifti1fields/nifti1fields_pages/datatype.html switch precision case 'uint8' hdr.datatype = 2; case 'int16' hdr.datatype = 4; case 'int32' hdr.datatype = 8; case 'single' hdr.datatype = 16; case 'double' hdr.datatype = 64; case 'int8' hdr.datatype = 256; case 'uint16' hdr.datatype = 512; case 'uint32' hdr.datatype = 768; case 'uint64' hdr.datatype = 1280; case 'int64' hdr.datatype = 1024; otherwise error('unsupported precision "%s"', precision); end switch precision case {'uint8' 'int8'} hdr.bitpix = 1*8; case {'uint16' 'int16'} hdr.bitpix = 2*8; case {'uint32' 'int32'} hdr.bitpix = 4*8; case {'uint64' 'int64'} hdr.bitpix = 8*8; case 'single' hdr.bitpix = 4*8; case 'double' hdr.bitpix = 8*8; otherwise error('unsupported precision "%s"', precision); end % dim(1) represents the number of dimensions % for a normal nifti file, dim(2:4) are x, y, z, dim(5) is time % cifti makes use of dim(6:8), which are free to choose hdr.dim = [4+length(dimtok) 1 1 1 1 1 1 1]; % the nifti specification does not allow for more than 7 dimensions to be specified assert(hdr.dim(1)<8); for i=1:length(dimtok) switch dimtok{i} case 'pos' hdr.dim(5+i) = size(source.pos,1); case 'chan' hdr.dim(5+i) = numel(source.label); case 'time' hdr.dim(5+i) = numel(source.time); case 'freq' hdr.dim(5+i) = numel(source.freq); case 'scalar' hdr.dim(5+i) = 1; otherwise error('unsupported dimord "%s"', dimord) end end hdr.intent_p1 = 0; hdr.intent_p2 = 0; hdr.intent_p3 = 0; hdr.pixdim = [0 1 1 1 1 1 1 1]; hdr.vox_offset = 4+540+8+xmlsize+xmlpad; hdr.scl_slope = 1; % WorkBench sets scl_slope/scl_inter to 1 and 0, although 0 and 0 would also be fine - both mean the same thing according to the nifti spec hdr.scl_inter = 0; hdr.cal_max = 0; hdr.cal_min = 0; hdr.slice_duration = 0; hdr.toffset = 0; hdr.slice_start = 0; hdr.slice_end = 0; hdr.descrip = char(zeros(1,80)); hdr.aux_file = char(zeros(1,24)); hdr.qform_code = 0; hdr.sform_code = 0; hdr.quatern_b = 0; hdr.quatern_c = 0; hdr.quatern_d = 0; hdr.qoffset_x = 0; hdr.qoffset_y = 0; hdr.qOffset_z = 0; hdr.srow_x = [0 0 0 0]; hdr.srow_y = [0 0 0 0]; hdr.srow_z = [0 0 0 0]; hdr.slice_code = 0; hdr.xyzt_units = 0; hdr.intent_code = intent_code; hdr.intent_name = cat(2, intent_name, zeros(1, 16-length(intent_name))); % zero-pad up to 16 characters hdr.dim_info = 0; hdr.unused_str = char(zeros(1,15)); % open the file fid = fopen(filename, 'wb'); % write the header, this is 4+540 bytes write_nifti2_hdr(fid, hdr); if debug try % write the xml section to a temporary file for debugging xmlfile = 'debug.xml'; tmp = fopen(xmlfile, 'w'); fwrite(tmp, xmldat, 'char'); fclose(tmp); end end % write the cifti header extension fwrite(fid, [1 0 0 0], 'uint8'); fwrite(fid, 8+xmlsize+xmlpad, 'int32'); % esize fwrite(fid, 32, 'int32'); % etype fwrite(fid, xmldat, 'char'); % write the ascii XML section fwrite(fid, zeros(1,xmlpad), 'uint8'); % zero-pad to the next 16 byte boundary % write the actual data fwrite(fid, dat, precision); fclose(fid); % write the surfaces as gifti files if writesurface && isfield(source, 'pos') && isfield(source, 'tri') if isfield(source, brainstructure) % it contains information about anatomical structures, including cortical surfaces for i=1:length(BrainStructurelabel) sel = find(BrainStructure~=i); [mesh.pnt, mesh.tri] = remove_vertices(source.pos, source.tri, sel); mesh.unit = source.unit; if isempty(mesh.pnt) || isempty(mesh.tri) % the brainordinate positions in this brain structure are not connected with triangles, i.e. in the case of voxels continue; end if ~isempty(regexp(BrainStructurelabel{i}, '^CIFTI_STRUCTURE_', 'once')) BrainStructurelabel{i} = BrainStructurelabel{i}(17:end); end [p, f, x] = fileparts(filename); filetok = tokenize(f, '.'); surffile = fullfile(p, [filetok{1} '.' BrainStructurelabel{i} '.surf.gii']); fprintf('writing %s surface to %s\n', BrainStructurelabel{i}, surffile); ft_write_headshape(surffile, mesh, 'format', 'gifti'); end else mesh.pnt = source.pos; mesh.tri = source.tri; mesh.unit = source.unit; [p, f, x] = fileparts(filename); filetok = tokenize(f, '.'); surffile = fullfile(p, [filetok{1} '.surf.gii']); ft_write_headshape(surffile, mesh, 'format', 'gifti'); end end % if writesurface and isfield tri %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to print lists of numbers with appropriate whitespace %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function s = printwithspace(x) x = x(:)'; % convert to vector if all(round(x)==x) % print as integer value s = sprintf('%d ', x); else % print as floating point value s = sprintf('%f ', x); end s = s(1:end-1); function s = printwithcomma(x) x = x(:)'; % convert to vector if all(round(x)==x) % print as integer value s = sprintf('%d,', x); else % print as floating point value s = sprintf('%f,', x); end s = s(1:end-1); function s = stringpad(s, n) while length(s)<n s = [' ' s]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION from roboos/matlab/triangle %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [pntR, triR] = remove_vertices(pnt, tri, removepnt) npnt = size(pnt,1); ntri = size(tri,1); if all(removepnt==0 | removepnt==1) removepnt = find(removepnt); end % remove the vertices and determine the new numbering (indices) in numb keeppnt = setdiff(1:npnt, removepnt); numb = zeros(1,npnt); numb(keeppnt) = 1:length(keeppnt); % look for triangles referring to removed vertices removetri = false(ntri,1); removetri(ismember(tri(:,1), removepnt)) = true; removetri(ismember(tri(:,2), removepnt)) = true; removetri(ismember(tri(:,3), removepnt)) = true; % remove the vertices and triangles pntR = pnt(keeppnt, :); triR = tri(~removetri,:); % renumber the vertex indices for the triangles triR = numb(triR);
github
lcnbeapp/beapp-master
ft_chantype.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/ft_chantype.m
28,384
utf_8
522cd6f4bd6d33431a8b221f56de3b4c
function chantype = ft_chantype(input, desired) % FT_CHANTYPE determines for each individual channel what chantype of data it % represents, e.g. a planar gradiometer, axial gradiometer, magnetometer, % trigger channel, etc. If you want to know what the acquisition system is % (e.g. ctf151 or neuromag306), you should not use this function but % FT_SENSTYPE instead. % % Use as % type = ft_chantype(hdr) % type = ft_chantype(sens) % type = ft_chantype(label) % or as % type = ft_chantype(hdr, desired) % type = ft_chantype(sens, desired) % type = ft_chantype(label, desired) % % If the desired unit is not specified as second input argument, this % function returns a Nchan*1 cell-array with a string describing the type % of each channel. % % If the desired unit is specified as second input argument, this function % returns a Nchan*1 boolean vector with "true" for the channels of the % desired type and "false" for the ones that do not match. % % The specification of the channel types depends on the acquisition system, % for example the ctf275 system includes the following tyoe of channels: % meggrad, refmag, refgrad, adc, trigger, eeg, headloc, headloc_gof. % % See also FT_READ_HEADER, FT_SENSTYPE, FT_CHANUNIT % Copyright (C) 2008-2015, Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are for remembering the type on subsequent calls with the same input arguments persistent previous_argin previous_argout % this is to avoid a recursion loop persistent recursion if isempty(recursion) recursion = false; end if nargin<2 desired = []; end % determine the type of input, this is handled similarly as in FT_CHANUNIT isheader = isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'Fs'); isdata = isa(input, 'struct') && ~isheader && (isfield(input, 'hdr') || isfield(input, 'grad') || isfield(input, 'elec') || isfield(input, 'opto')); isgrad = isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'pnt') && isfield(input, 'ori'); % old style iselec = isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'pnt') && ~isfield(input, 'ori'); % old style isgrad = (isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'coilpos')) || isgrad; % new style iselec = (isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'elecpos')) || iselec; % new style isopto = isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'transceiver'); islabel = isa(input, 'cell') && ~isempty(input) && isa(input{1}, 'char'); if isheader % this speeds up the caching in real-time applications input.nSamples = 0; end current_argin = {input, desired}; if isequal(current_argin, previous_argin) % don't do the chantype detection again, but return the previous output from cache chantype = previous_argout{1}; return end if isdata % the hdr, grad, elec or opto structure might have a different set of channels origlabel = input.label; if isfield(input, 'hdr') input = input.hdr; isheader = true; elseif isfield(input, 'grad') input = input.grad; isgrad = true; elseif isfield(input, 'elec') input = input.elec; iselec = true; elseif isfield(input, 'opto') input = input.opto; isopto = true; else % at least it contains channel labels islabel = true; end end if isheader label = input.label; numchan = length(label); elseif isgrad label = input.label; numchan = length(label); elseif iselec label = input.label; numchan = length(label); elseif islabel label = input; numchan = length(label); elseif isfield(input, 'label') % this is a last resort: I don't know what it is, but perhaps the labels are informative label = input.label; numchan = length(label); else error('the input that was provided to this function cannot be deciphered'); end if isfield(input, 'chantype') % start with the provided channel types chantype = input.chantype(:); else % start with unknown chantype for all channels chantype = repmat({'unknown'}, numchan, 1); end if ft_senstype(input, 'unknown') % don't bother doing all subsequent checks to determine the chantype of sensor array elseif isheader && (ft_senstype(input, 'neuromag') || ft_senstype(input, 'babysquid74')) % channames-KI is the channel kind, 1=meg, 202=eog, 2=eeg, 3=trigger (I am not sure, but have inferred this from a single test file) % chaninfo-TY is the Coil chantype (0=magnetometer, 1=planar gradiometer) if isfield(input, 'orig') && isfield(input.orig, 'channames') for sel=find(input.orig.channames.KI(:)==202)' chantype{sel} = 'eog'; end for sel=find(input.orig.channames.KI(:)==2)' chantype{sel} = 'eeg'; end for sel=find(input.orig.channames.KI(:)==3)' chantype{sel} = 'digital trigger'; end % determine the MEG channel subtype selmeg=find(input.orig.channames.KI(:)==1)'; for i=1:length(selmeg) if input.orig.chaninfo.TY(i)==0 chantype{selmeg(i)} = 'megmag'; elseif input.orig.chaninfo.TY(i)==1 % FIXME this might also be a axial gradiometer in case the BabySQUID data is read with the old reading routines chantype{selmeg(i)} = 'megplanar'; end end elseif isfield(input, 'orig') && isfield(input.orig, 'chs') && isfield(input.orig.chs, 'coil_type') % all the chs.kinds and chs.coil_types are obtained from the MNE manual, p.210-211 for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==2)' % planar gradiometers chantype(sel) = {'megplanar'}; %Neuromag-122 planar gradiometer end for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==3012)' %planar gradiometers chantype(sel) = {'megplanar'}; %Type T1 planar grad end for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==3013)' %planar gradiometers chantype(sel) = {'megplanar'}; %Type T2 planar grad end for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==3014)' %planar gradiometers chantype(sel) = {'megplanar'}; %Type T3 planar grad end for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==3022)' %magnetometers chantype(sel) = {'megmag'}; %Type T1 magenetometer end for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==3023)' %magnetometers chantype(sel) = {'megmag'}; %Type T2 magenetometer end for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==3024)' %magnetometers chantype(sel) = {'megmag'}; %Type T3 magenetometer end for sel=find([input.orig.chs.kind]==1 & [input.orig.chs.coil_type]==7001)' %axial gradiometer chantype(sel) = {'megaxial'}; end for sel=find([input.orig.chs.kind]==301)' %MEG reference channel, located far from head chantype(sel) = {'ref'}; end for sel=find([input.orig.chs.kind]==2)' %EEG channels chantype(sel) = {'eeg'}; end for sel=find([input.orig.chs.kind]==201)' %MCG channels chantype(sel) = {'mcg'}; end for sel=find([input.orig.chs.kind]==3)' %Stim channels if any([input.orig.chs(sel).logno] == 101) %new systems: 101 (and 102, if enabled) are digital; low numbers are 'pseudo-analog' (if enabled) chantype(sel([input.orig.chs(sel).logno] == 101)) = {'digital trigger'}; chantype(sel([input.orig.chs(sel).logno] == 102)) = {'digital trigger'}; chantype(sel([input.orig.chs(sel).logno] <= 32)) = {'analog trigger'}; others = [input.orig.chs(sel).logno] > 32 & [input.orig.chs(sel).logno] ~= 101 & ... [input.orig.chs(sel).logno] ~= 102; chantype(sel(others)) = {'other trigger'}; elseif any([input.orig.chs(sel).logno] == 14) %older systems: STI 014/015/016 are digital; lower numbers 'pseudo-analog'(if enabled) chantype(sel([input.orig.chs(sel).logno] == 14)) = {'digital trigger'}; chantype(sel([input.orig.chs(sel).logno] == 15)) = {'digital trigger'}; chantype(sel([input.orig.chs(sel).logno] == 16)) = {'digital trigger'}; chantype(sel([input.orig.chs(sel).logno] <= 13)) = {'analog trigger'}; others = [input.orig.chs(sel).logno] > 16; chantype(sel(others)) = {'other trigger'}; else warning('There does not seem to be a suitable trigger channel.'); chantype(sel) = {'other trigger'}; end end for sel=find([input.orig.chs.kind]==202)' %EOG chantype(sel) = {'eog'}; end for sel=find([input.orig.chs.kind]==302)' %EMG chantype(sel) = {'emg'}; end for sel=find([input.orig.chs.kind]==402)' %ECG chantype(sel) = {'ecg'}; end for sel=find([input.orig.chs.kind]==502)' %MISC chantype(sel) = {'misc'}; end for sel=find([input.orig.chs.kind]==602)' %Resp chantype(sel) = {'respiration'}; end end elseif ft_senstype(input, 'babysquid74') % the name can be something like "MEG 001" or "MEG001" or "MEG 0113" or "MEG0113" % i.e. with two or three digits and with or without a space sel = myregexp('^MEG', label); chantype(sel) = {'megaxial'}; elseif ft_senstype(input, 'neuromag122') % the name can be something like "MEG 001" or "MEG001" or "MEG 0113" or "MEG0113" % i.e. with two or three digits and with or without a space sel = myregexp('^MEG', label); chantype(sel) = {'megplanar'}; elseif ft_senstype(input, 'neuromag306') && isgrad % there should be 204 planar gradiometers and 102 axial magnetometers if isfield(input, 'tra') tmp = sum(abs(input.tra),2); sel = (tmp==median(tmp)); chantype(sel) = {'megplanar'}; sel = (tmp~=median(tmp)); chantype(sel) = {'megmag'}; end elseif ft_senstype(input, 'neuromag306') && islabel sel = myregexp('^MEG.*1$', label); chantype(sel) = {'megmag'}; sel = myregexp('^MEG.*2$', label); chantype(sel) = {'megplanar'}; sel = myregexp('^MEG.*3$', label); chantype(sel) = {'megplanar'}; elseif ft_senstype(input, 'neuromag306_combined') && islabel % the magnetometers are detected, the combined channels remain unknown sel = myregexp('^MEG.*1$', label); chantype(sel) = {'megmag'}; elseif ft_senstype(input, 'ctf') && isheader % According to one source of information meg channels are 5, refmag 0, % refgrad 1, adcs 18, trigger 11, eeg 9. % % According to another source of information it is as follows % refMagnetometers: 0 % refGradiometers: 1 % meg_sens: 5 % eeg_sens: 9 % adc: 10 % stim_ref: 11 % video_time: 12 % sam: 15 % virtual_channels: 16 % sclk_ref: 17 % start with an empty one origSensType = []; if isfield(input, 'orig') if isfield(input.orig, 'sensType') && isfield(input.orig, 'Chan') % the header was read using the open-source MATLAB code that originates from CTF and that was modified by the FCDC origSensType = input.orig.sensType; elseif isfield(input.orig, 'res4') && isfield(input.orig.res4, 'senres') % the header was read using the CTF p-files, i.e. readCTFds origSensType = [input.orig.res4.senres.sensorTypeIndex]; elseif isfield(input.orig, 'sensor') && isfield(input.orig.sensor, 'info') % the header was read using the CTF importer from the NIH and Daren Weber origSensType = [input.orig.sensor.info.index]; end end if isempty(origSensType) warning('could not determine channel chantype from the CTF header'); end for sel=find(origSensType(:)==5)' chantype{sel} = 'meggrad'; end for sel=find(origSensType(:)==0)' chantype{sel} = 'refmag'; end for sel=find(origSensType(:)==1)' chantype{sel} = 'refgrad'; end for sel=find(origSensType(:)==18)' chantype{sel} = 'adc'; end for sel=find(origSensType(:)==11)' chantype{sel} = 'trigger'; end for sel=find(origSensType(:)==17)' chantype{sel} = 'clock'; end for sel=find(origSensType(:)==9)' chantype{sel} = 'eeg'; end for sel=find(origSensType(:)==29)' chantype{sel} = 'reserved'; % these are "reserved for future use", but relate to head localization end for sel=find(origSensType(:)==13)' chantype{sel} = 'headloc'; % these represent the x, y, z position of the head coils end for sel=find(origSensType(:)==28)' chantype{sel} = 'headloc_gof'; % these represent the goodness of fit for the head coils end % for sel=find(origSensType(:)==23)' % chantype{sel} = 'SPLxxxx'; % I have no idea what these are % end elseif ft_senstype(input, 'ctf') && isgrad % in principle it is possible to look at the number of coils, but here the channels are identified based on their name sel = myregexp('^M[ZLR][A-Z][0-9][0-9]$', input.label); chantype(sel) = {'meggrad'}; % normal gradiometer channels sel = myregexp('^S[LR][0-9][0-9]$', input.label); chantype(sel) = {'meggrad'}; % normal gradiometer channels in the 64 channel CTF system sel = myregexp('^B[GPQR][0-9]$', input.label); chantype(sel) = {'refmag'}; % reference magnetometers sel = myregexp('^[GPQR][0-9][0-9]$', input.label); chantype(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); chantype(sel) = {'meggrad'}; % normal gradiometer channels sel = myregexp('^S[LR][0-9][0-9]$', label); chantype(sel) = {'meggrad'}; % normal gradiometer channels in the 64 channel CTF system sel = myregexp('^B[GPR][0-9]$', label); chantype(sel) = {'refmag'}; % reference magnetometers sel = myregexp('^[GPQR][0-9][0-9]$', label); chantype(sel) = {'refgrad'}; % reference gradiometers elseif ft_senstype(input, 'bti') if isfield(input, 'orig') && isfield(input.orig, 'config') configname = {input.orig.config.channel_data.name}; configtype = [input.orig.config.channel_data.type]; if ~isequal(configname(:), input.label(:)) % reorder the channels according to the order in input.label [sel1, sel2] = match_str(input.label, configname); configname = configname(sel2); configtype = configtype(sel2); configdata = input.orig.config.channel_data(sel2); end numloops = zeros(size(configdata)); for i=1:length(configdata) if isfield(configdata(i).device_data, 'total_loops') numloops(i) = configdata(i).device_data.total_loops; end end % these are taken from bti2grad chantype(configtype==1 & numloops==1) = {'megmag'}; chantype(configtype==1 & numloops==2) = {'meggrad'}; chantype(configtype==2) = {'eeg'}; chantype(configtype==3) = {'ref'}; % not known if mag or grad chantype(configtype==4) = {'aux'}; chantype(configtype==5) = {'trigger'}; % refine the distinction between refmag and refgrad to make the types % in grad and header consistent sel = myregexp('^M[CLR][xyz][aA]*$', label); chantype(sel) = {'refmag'}; sel = myregexp('^G[xyz][xyz]A$', label); chantype(sel) = {'refgrad'}; else % determine the chantype on the basis of the channel labels % all 4D-BTi MEG channels start with "A" followed by a number % all 4D-BTi reference channels start with M or G % all 4D-BTi EEG channels start with E, except for the 248-MEG/32-EEG system in Warsaw where they end with -1 sel = myregexp('^A[0-9]+$', label); chantype(sel) = {'meg'}; sel = myregexp('^M[CLR][xyz][aA]*$', label); chantype(sel) = {'refmag'}; sel = myregexp('^G[xyz][xyz]A$', label); chantype(sel) = {'refgrad'}; if isgrad && isfield(input, 'tra') gradtype = repmat({'unknown'}, size(input.label)); gradtype(strncmp('A', input.label, 1)) = {'meg'}; gradtype(strncmp('M', input.label, 1)) = {'refmag'}; gradtype(strncmp('G', input.label, 1)) = {'refgrad'}; % look at the number of coils of the meg channels selchan = find(strcmp('meg', gradtype)); for k = 1:length(selchan) ncoils = length(find(input.tra(selchan(k),:)==1)); if ncoils==1, gradtype{selchan(k)} = 'megmag'; elseif ncoils==2, gradtype{selchan(k)} = 'meggrad'; end end [selchan, selgrad] = match_str(label, input.label); chantype(selchan) = gradtype(selgrad); end % deal with additional channel types based on the names if isheader && issubfield(input, 'orig.channel_data.chan_label') tmplabel = {input.orig.channel_data.chan_label}; tmplabel = tmplabel(:); else tmplabel = label; % might work end sel = find(strcmp('unknown', chantype)); if ~isempty(sel) chantype(sel) = ft_chantype(tmplabel(sel)); sel = find(strcmp('unknown', chantype)); if ~isempty(sel) % channels that start with E are assumed to be EEG % channels that end with -1 are also assumed to be EEG, see http://bugzilla.fcdonders.nl/show_bug.cgi?id=2389 chantype(sel(cellfun(@(x) strcmp(x(end-1:end),'-1') || strcmp(x(1),'E'), label(sel)))) = {'eeg'}; end end end elseif ft_senstype(input, 'itab') && isheader origtype = [input.orig.ch.type]; chantype(origtype==0) = {'unknown'}; chantype(origtype==1) = {'ele'}; chantype(origtype==2) = {'mag'}; % might be magnetometer or gradiometer, look at the number of coils chantype(origtype==4) = {'ele ref'}; chantype(origtype==8) = {'mag ref'}; chantype(origtype==16) = {'aux'}; chantype(origtype==32) = {'param'}; chantype(origtype==64) = {'digit'}; chantype(origtype==128) = {'flag'}; % these are the channels that are visible to fieldtrip chansel = 1:input.orig.nchan; chantype = chantype(chansel); elseif ft_senstype(input, 'yokogawa') && isheader % This is to recognize Yokogawa channel types from the original header % This is from the original documentation NullChannel = 0; MagnetoMeter = 1; AxialGradioMeter = 2; PlannerGradioMeter = 3; RefferenceChannelMark = hex2dec('0100'); RefferenceMagnetoMeter = bitor( RefferenceChannelMark, MagnetoMeter ); RefferenceAxialGradioMeter = bitor( RefferenceChannelMark, AxialGradioMeter ); RefferencePlannerGradioMeter = bitor( RefferenceChannelMark, PlannerGradioMeter); TriggerChannel = -1; EegChannel = -2; EcgChannel = -3; EtcChannel = -4; if ft_hastoolbox('yokogawa_meg_reader') % shorten names ch_info = input.orig.channel_info.channel; type_orig = [ch_info.type]; sel = (type_orig == NullChannel); chantype(sel) = {'null'}; sel = (type_orig == MagnetoMeter); chantype(sel) = {'megmag'}; sel = (type_orig == AxialGradioMeter); chantype(sel) = {'meggrad'}; sel = (type_orig == PlannerGradioMeter); chantype(sel) = {'megplanar'}; sel = (type_orig == RefferenceMagnetoMeter); chantype(sel) = {'refmag'}; sel = (type_orig == RefferenceAxialGradioMeter); chantype(sel) = {'refgrad'}; sel = (type_orig == RefferencePlannerGradioMeter); chantype(sel) = {'refplanar'}; sel = (type_orig == TriggerChannel); chantype(sel) = {'trigger'}; sel = (type_orig == EegChannel); chantype(sel) = {'eeg'}; sel = (type_orig == EcgChannel); chantype(sel) = {'ecg'}; sel = (type_orig == EtcChannel); chantype(sel) = {'etc'}; elseif ft_hastoolbox('yokogawa') sel = (input.orig.channel_info(:, 2) == NullChannel); chantype(sel) = {'null'}; sel = (input.orig.channel_info(:, 2) == MagnetoMeter); chantype(sel) = {'megmag'}; sel = (input.orig.channel_info(:, 2) == AxialGradioMeter); chantype(sel) = {'meggrad'}; sel = (input.orig.channel_info(:, 2) == PlannerGradioMeter); chantype(sel) = {'megplanar'}; sel = (input.orig.channel_info(:, 2) == RefferenceMagnetoMeter); chantype(sel) = {'refmag'}; sel = (input.orig.channel_info(:, 2) == RefferenceAxialGradioMeter); chantype(sel) = {'refgrad'}; sel = (input.orig.channel_info(:, 2) == RefferencePlannerGradioMeter); chantype(sel) = {'refplanar'}; sel = (input.orig.channel_info(:, 2) == TriggerChannel); chantype(sel) = {'trigger'}; sel = (input.orig.channel_info(:, 2) == EegChannel); chantype(sel) = {'eeg'}; sel = (input.orig.channel_info(:, 2) == EcgChannel); chantype(sel) = {'ecg'}; sel = (input.orig.channel_info(:, 2) == EtcChannel); chantype(sel) = {'etc'}; end elseif ft_senstype(input, 'yokogawa') && isgrad % all channels in the gradiometer definition are meg % chantype(1:end) = {'meg'}; % channels are identified based on their name: only magnetic as isgrad==1 sel = myregexp('^M[0-9][0-9][0-9]$', input.label); chantype(sel) = {'megmag'}; sel = myregexp('^AG[0-9][0-9][0-9]$', input.label); chantype(sel) = {'meggrad'}; sel = myregexp('^PG[0-9][0-9][0-9]$', input.label); chantype(sel) = {'megplanar'}; sel = myregexp('^RM[0-9][0-9][0-9]$', input.label); chantype(sel) = {'refmag'}; sel = myregexp('^RAG[0-9][0-9][0-9]$', input.label); chantype(sel) = {'refgrad'}; sel = myregexp('^RPG[0-9][0-9][0-9]$', input.label); chantype(sel) = {'refplanar'}; elseif ft_senstype(input, 'yokogawa') && islabel % the yokogawa channel labels are a mess, so autodetection is not possible % chantype(1:end) = {'meg'}; sel = myregexp('[0-9][0-9][0-9]$', label); chantype(sel) = {'null'}; sel = myregexp('^M[0-9][0-9][0-9]$', label); chantype(sel) = {'megmag'}; sel = myregexp('^AG[0-9][0-9][0-9]$', label); chantype(sel) = {'meggrad'}; sel = myregexp('^PG[0-9][0-9][0-9]$', label); chantype(sel) = {'megplanar'}; sel = myregexp('^RM[0-9][0-9][0-9]$', label); chantype(sel) = {'refmag'}; sel = myregexp('^RAG[0-9][0-9][0-9]$', label); chantype(sel) = {'refgrad'}; sel = myregexp('^RPG[0-9][0-9][0-9]$', label); chantype(sel) = {'refplanar'}; sel = myregexp('^TRIG[0-9][0-9][0-9]$', label); chantype(sel) = {'trigger'}; sel = myregexp('^EEG[0-9][0-9][0-9]$', label); chantype(sel) = {'eeg'}; sel = myregexp('^ECG[0-9][0-9][0-9]$', label); chantype(sel) = {'ecg'}; sel = myregexp('^ETC[0-9][0-9][0-9]$', label); chantype(sel) = {'etc'}; elseif ft_senstype(input, 'itab') && isheader sel = ([input.orig.ch.type]==0); chantype(sel) = {'unknown'}; sel = ([input.orig.ch.type]==1); chantype(sel) = {'unknown'}; sel = ([input.orig.ch.type]==2); chantype(sel) = {'megmag'}; sel = ([input.orig.ch.type]==8); chantype(sel) = {'megref'}; sel = ([input.orig.ch.type]==16); chantype(sel) = {'aux'}; sel = ([input.orig.ch.type]==64); chantype(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 chantype = chantype(input.orig.chansel); elseif ft_senstype(input, 'itab') && isgrad % the channels have to be identified based on their name alone sel = myregexp('^MAG_[0-9][0-9][0-9]$', label); chantype(sel) = {'megmag'}; sel = myregexp('^MAG_[0-9][0-9]$', label); % for the itab28 system chantype(sel) = {'megmag'}; sel = myregexp('^MAG_[0-9]$', label); % for the itab28 system chantype(sel) = {'megmag'}; sel = myregexp('^REF_[0-9][0-9][0-9]$', label); chantype(sel) = {'megref'}; sel = myregexp('^AUX.*$', label); chantype(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); chantype(sel) = {'megmag'}; sel = myregexp('^REF_[0-9][0-9][0-9]$', label); chantype(sel) = {'megref'}; sel = myregexp('^AUX.*$', label); chantype(sel) = {'aux'}; elseif ft_senstype(input, 'eeg') && islabel % use an external helper function to define the list with EEG channel names chantype(match_str(label, ft_senslabel('eeg1005'))) = {'eeg'}; % this includes all channels from the 1010 and 1020 arrangement chantype(match_str(label, ft_senslabel(ft_senstype(input)))) = {'eeg'}; % this will work for biosemi, egi and other detected channel arrangements elseif ft_senstype(input, 'eeg') && iselec % all channels in an electrode definition must be eeg channels chantype(:) = {'eeg'}; elseif ft_senstype(input, 'eeg') && isheader % use an external helper function to define the list with EEG channel names chantype(match_str(input.label, ft_senslabel(ft_senstype(input)))) = {'eeg'}; elseif ft_senstype(input, 'plexon') && isheader % this is a complete header that was read from a Plexon *.nex file using read_plexon_nex for i=1:numchan switch input.orig.VarHeader(i).Type case 0 chantype{i} = 'spike'; case 1 chantype{i} = 'event'; case 2 chantype{i} = 'interval'; % Interval variables? case 3 chantype{i} = 'waveform'; case 4 chantype{i} = 'population'; % Population variables ? case 5 chantype{i} = 'analog'; otherwise % keep the default 'unknown' chantype end end end % ft_senstype % if possible, set additional types based on channel labels label2type = { {'ecg', 'ekg'}; {'emg'}; {'eog', 'heog', 'veog'}; {'lfp'}; {'eeg'}; {'trigger', 'trig', 'dtrig'}; }; for i = 1:numel(label2type) for j = 1:numel(label2type{i}) chantype(intersect(strmatch(label2type{i}{j}, lower(label)), find(strcmp(chantype, 'unknown')))) = label2type{i}(1); end end if isdata % the input was replaced by one of hdr, grad, elec, opto [sel1, sel2] = match_str(origlabel, input.label); origtype = repmat({'unknown'}, size(sel1)); origtype(sel1) = chantype(sel2); % the hdr, grad, elec or opto structure might have a different set of channels chantype = origtype; end if all(strcmp(chantype, 'unknown')) && ~recursion % try whether only lowercase channel labels makes a difference if islabel recursion = true; chantype = ft_chantype(lower(input)); recursion = false; elseif isfield(input, 'label') input.label = lower(input.label); recursion = true; chantype = ft_chantype(input); recursion = false; end end if all(strcmp(chantype, 'unknown')) && ~recursion % try whether only uppercase channel labels makes a difference if islabel recursion = true; chantype = ft_chantype(upper(input)); recursion = false; elseif isfield(input, 'label') input.label = upper(input.label); recursion = true; chantype = ft_chantype(input); recursion = false; end end if nargin>1 % return a boolean vector if isequal(desired, 'meg') || isequal(desired, 'ref') % only compare the first three characters, i.e. meggrad or megmag should match chantype = strncmp(desired, chantype, 3); else chantype = strcmp(desired, chantype); end end % remember the current input and output arguments, so that they can be % reused on a subsequent call in case the same input argument is given current_argout = {chantype}; previous_argin = current_argin; previous_argout = current_argout; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function match = myregexp(pat, list) match = false(size(list)); for i=1:numel(list) match(i) = ~isempty(regexp(list{i}, pat, 'once')); end
github
lcnbeapp/beapp-master
ft_read_header.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/ft_read_header.m
94,063
utf_8
b72ee43e5846a045b221a03afde784b7
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 = []) % 'checkmaxfilter' = boolean, whether to check that maxfilter has been correctly applied (default = true) % 'chanindx' = list with channel indices in case of different sampling frequencies (only for EDF) % 'coordsys' = string, 'head' or 'dewar' (default = 'head') % 'coilaccuracy' = can be empty or a number (0, 1 or 2) to specify the accuracy (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 Nx1 cell-array with the label of each channel % hdr.chantype Nx1 cell-array with the channel type, see FT_CHANTYPE % hdr.chanunit Nx1 cell-array with the physical units, see FT_CHANUNIT % % For some data formats that are recorded on animal electrophysiology % systems (e.g. Neuralynx, Plexon), the following optional fields are % returned, which allows for relating the timing of spike and LFP data % hdr.FirstTimeStamp number, represented as 32 bit or 64 bit unsigned integer % hdr.TimeStampPerSample number, represented in double precision % % For continuously recorded 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) % NetMEG (*.nc) % ITAB - Chieti (*.mhd) % Tristan Babysquid (*.fif) % % The following EEG dataformats are supported % ANT - Advanced Neuro Technology, EEProbe (*.avr, *.eeg, *.cnt) % BCI2000 (*.dat) % Biosemi (*.bdf) % BrainVision (*.eeg, *.seg, *.dat, *.vhdr, *.vmrk) % CED - Cambridge Electronic Design (*.smr) % EGI - Electrical Geodesics, Inc. (*.egis, *.ave, *.gave, *.ses, *.raw, *.sbin, *.mff) % GTec (*.mat) % Generic data formats (*.edf, *.gdf) % Megis/BESA (*.avr, *.swf, *.besa) % NeuroScan (*.eeg, *.cnt, *.avg) % Nexstim (*.nxe) % TMSi (*.Poly5) % Mega Neurone (directory) % Natus/Nicolet/Nervus (.e files) % Nihon Kohden (*.m00) % % The following spike and LFP dataformats are supported % Neuralynx (*.ncs, *.nse, *.nts, *.nev, *.nrd, *.dma, *.log) % Plextor (*.nex, *.plx, *.ddt) % CED - Cambridge Electronic Design (*.smr) % MPI - Max Planck Institute (*.dap) % Neurosim (neurosim_spikes, neurosim_signals, neurosim_ds) % Windaq (*.wdq) % % The following NIRS dataformats are supported % BUCN - Birkbeck college, London (*.txt) % % The following Eyetracker dataformats are supported % EyeLink - SR Research (*.asc) % Tobii - (*.tsv) % SensoMotoric Instruments - (*.txt) % % See also FT_READ_DATA, FT_READ_EVENT, FT_WRITE_DATA, FT_WRITE_EVENT, % FT_CHANTYPE, FT_CHANUNIT % Copyright (C) 2003-2016 Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % TODO channel renaming should be made a general option (see bham_bdf) persistent cacheheader % for caching the full header persistent cachechunk % for caching the res4 chunk when doing realtime analysis on the CTF scanner persistent db_blob % for fcdc_mysql if isempty(db_blob) db_blob = false; end if iscell(filename) % use recursion to read events from multiple files ft_warning(sprintf('concatenating header from %d files', numel(filename))); hdr = cell(size(filename)); for i=1:numel(filename) hdr{i} = ft_read_header(filename{i}, varargin{:}); end ntrl = nan(size(filename)); nsmp = nan(size(filename)); for i=1:numel(filename) assert(isequal(hdr{i}.label, hdr{1}.label)); assert(isequal(hdr{i}.Fs, hdr{1}.Fs)); ntrl(i) = hdr{i}.nTrials; nsmp(i) = hdr{i}.nSamples; end combined = hdr{1}; combined.orig = hdr; % store the original header details of each file if all(ntrl==1) % each file is a continuous recording combined.nTrials = ntrl(1); combined.nSamples = sum(nsmp); elseif all(nsmp==nsmp(1)) % each file holds segments of the same length combined.nTrials = sum(ntrl); combined.nSamples = nsmp(1); else error('cannot concatenate files'); end % return the header of the concatenated datafiles hdr = combined; return end % get the options headerformat = ft_getopt(varargin, 'headerformat'); retry = ft_getopt(varargin, 'retry', false); % the default is not to retry reading the header chanindx = ft_getopt(varargin, 'chanindx'); % this is used for EDF with different sampling rates coordsys = ft_getopt(varargin, 'coordsys', 'head'); % this is used for ctf and neuromag_mne, it can be head or dewar coilaccuracy = ft_getopt(varargin, 'coilaccuracy'); % empty, or a number between 0-2 % optionally get the data from the URL and make a temporary local copy filename = fetch_url(filename); if isempty(headerformat) % only do the autodetection if the format was not specified headerformat = ft_filetype(filename); end if iscell(headerformat) % this happens for datasets specified as cell-array for concatenation headerformat = headerformat{1}; end if strcmp(headerformat, 'compressed') % the file is compressed, unzip on the fly inflated = true; filename = inflate_file(filename); headerformat = ft_filetype(filename); else inflated = false; end realtime = any(strcmp(headerformat, {'fcdc_buffer', 'ctf_shm', 'fcdc_mysql'})); % The checkUniqueLabels flag is used for the realtime buffer in case % it contains fMRI data. It prevents 1000000 voxel names to be checked % for uniqueness. fMRI users will probably never use channel names % for anything. if realtime % skip the rest of the initial checks to increase the speed for realtime operation checkUniqueLabels = false; % the cache and fallback option should always be false for realtime processing cache = false; fallback = false; else % check whether the file or directory exists if ~exist(filename, 'file') error('FILEIO:InvalidFileName', 'file or directory ''%s'' does not exist', filename); end checkUniqueLabels = true; % get the rest of the options, this is skipped for realtime operation cache = ft_getopt(varargin, 'cache'); fallback = ft_getopt(varargin, 'fallback'); checkmaxfilter = ft_getopt(varargin, 'checkmaxfilter', true); if isempty(cache) if any(strcmp(headerformat, {'bci2000_dat', 'eyelink_asc', 'gtec_mat', 'mega_neurone', 'smi_txt', 'biosig'})) cache = true; else cache = false; end end % ensure that the headerfile and datafile are defined, which are sometimes different than the name of the dataset [filename, headerfile, datafile] = dataset2files(filename, headerformat); if ~strcmp(filename, headerfile) && ~ft_filetype(filename, 'ctf_ds') && ~ft_filetype(filename, 'fcdc_buffer_offline') && ~ft_filetype(filename, 'fcdc_matbin') filename = headerfile; % this function should read the headerfile, not the dataset headerformat = ft_filetype(filename); % update the filetype end end % if skip initial check % implement the caching in a data-format independent way if cache && exist(headerfile, 'file') && ~isempty(cacheheader) % try to get the header from cache details = dir(headerfile); if isequal(details, cacheheader.details) % the header file has not been updated, fetch it from the cache % fprintf('got header from cache\n'); hdr = rmfield(cacheheader, 'details'); switch ft_filetype(datafile) case {'ctf_ds' 'ctf_meg4' 'ctf_old' 'read_ctf_res4'} % for realtime analysis end-of-file-chasing the res4 does not correctly % estimate the number of samples, so we compute it on the fly sz = 0; files = dir([filename '/*.*meg4']); for j=1:numel(files) sz = sz + files(j).bytes; end hdr.nTrials = floor((sz - 8) / (hdr.nChans*4) / hdr.nSamples); end return end % if the details correspond end % if cache % the support for head/dewar coordinates is still limited if strcmp(coordsys, 'dewar') && ~any(strcmp(headerformat, {'fcdc_buffer', 'ctf_ds', 'ctf_meg4', 'ctf_res4', 'neuromag_fif', 'neuromag_mne'})) error('dewar coordinates are not supported for %s', headerformat); end % start with an empty header hdr = []; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the data with the low-level reading function % please maintain this list in alphabetical order %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 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, elec] = bti2grad(orig); if ~isempty(elec), hdr.elec = elec; end % remember original header details hdr.orig = orig; case {'4d_pdf', '4d_m4d', '4d_xyz'} orig = read_bti_m4d(filename); hdr.Fs = orig.SampleFrequency; hdr.nChans = orig.TotalChannels; hdr.nSamples = orig.SlicesPerEpoch; hdr.nSamplesPre = round(orig.FirstLatency*orig.SampleFrequency); hdr.nTrials = orig.TotalEpochs; hdr.label = orig.ChannelOrder(:); [hdr.grad, elec] = bti2grad(orig); if ~isempty(elec), hdr.elec = elec; end % remember original header details hdr.orig = orig; case 'AnyWave' orig = read_ahdf5_hdr(datafile); hdr.orig = orig; hdr.Fs = orig.channels(1).samplingRate; hdr.nChans = numel(orig.channels); hdr.nSamples = orig.numberOfSamples; hdr.nTrials = orig.numberOfBlocks; hdr.nSamplesPre = 0; hdr.label = orig.label; hdr.reference = orig.reference(:); hdr.chanunit = orig.unit(:); hdr.chantype = orig.type(:); case 'bci2000_dat' % this requires the load_bcidat mex file to be present on the path ft_hastoolbox('BCI2000', 1); % this is inefficient, since it reads the complete data [signal, states, parameters, total_samples] = load_bcidat(filename); % convert into a FieldTrip-like header hdr = []; hdr.nChans = size(signal,2); hdr.nSamples = total_samples; hdr.nSamplesPre = 0; % it is continuous hdr.nTrials = 1; % it is continuous hdr.Fs = parameters.SamplingRate.NumericValue; % there are some differences in the fields that are present in the % *.dat files, probably due to different BCI2000 versions if isfield(parameters, 'ChannelNames') && isfield(parameters.ChannelNames, 'Value') && ~isempty(parameters.ChannelNames.Value) hdr.label = parameters.ChannelNames.Value; elseif isfield(parameters, 'ChannelNames') && isfield(parameters.ChannelNames, 'Values') && ~isempty(parameters.ChannelNames.Values) hdr.label = parameters.ChannelNames.Values; else % give this warning only once ft_warning('creating fake channel names'); for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end end % remember the original header details hdr.orig.parameters = parameters; % also remember the complete data upon request if cache hdr.orig.signal = signal; hdr.orig.states = states; hdr.orig.total_samples = total_samples; end case 'besa_besa' if isempty(chanindx) hdr = read_besa_besa(filename); else hdr = read_besa_besa(filename,[],1); if chanindx > hdr.orig.channel_info.orig_n_channels error('FILEIO:InvalidChanIndx', 'selected channels are not present in the data'); else hdr = read_besa_besa(filename,[],chanindx); end; end; case 'besa_avr' orig = read_besa_avr(filename); hdr.Fs = 1000/orig.di; hdr.nChans = size(orig.data,1); hdr.nSamples = size(orig.data,2); hdr.nSamplesPre = -(hdr.Fs * orig.tsb/1000); % convert from ms to samples hdr.nTrials = 1; if isfield(orig, 'label') && iscell(orig.label) hdr.label = orig.label; elseif isfield(orig, 'label') && ischar(orig.label) hdr.label = tokenize(orig.label, ' '); else % give this warning only once ft_warning('creating fake channel names'); for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end end case 'besa_swf' orig = read_besa_swf(filename); hdr.Fs = 1000/orig.di; hdr.nChans = size(orig.data,1); hdr.nSamples = size(orig.data,2); hdr.nSamplesPre = -(hdr.Fs * orig.tsb/1000); % convert from ms to samples hdr.nTrials = 1; hdr.label = orig.label; case 'biosig' % this requires the biosig toolbox ft_hastoolbox('BIOSIG', 1); hdr = read_biosig_header(filename); case {'biosemi_bdf', 'bham_bdf'} hdr = read_biosemi_bdf(filename); if any(diff(hdr.orig.SampleRate)) error('channels with different sampling rate not supported'); end if ~ft_senstype(hdr, 'ext1020') % assign the channel type and units for the known channels hdr.chantype = repmat({'unknown'}, size(hdr.label)); hdr.chanunit = repmat({'unknown'}, size(hdr.label)); chan = ~cellfun(@isempty, regexp(hdr.label, '^[A-D]\d*$')); hdr.chantype(chan) = {'eeg'}; hdr.chanunit(chan) = {'uV'}; end if ft_filetype(filename, 'bham_bdf') % TODO channel renaming should be made a general option % this is for the Biosemi system used at the University of Birmingham labelold = { 'A1' 'A2' 'A3' 'A4' 'A5' 'A6' 'A7' 'A8' 'A9' 'A10' 'A11' 'A12' 'A13' 'A14' 'A15' 'A16' 'A17' 'A18' 'A19' 'A20' 'A21' 'A22' 'A23' 'A24' 'A25' 'A26' 'A27' 'A28' 'A29' 'A30' 'A31' 'A32' 'B1' 'B2' 'B3' 'B4' 'B5' 'B6' 'B7' 'B8' 'B9' 'B10' 'B11' 'B12' 'B13' 'B14' 'B15' 'B16' 'B17' 'B18' 'B19' 'B20' 'B21' 'B22' 'B23' 'B24' 'B25' 'B26' 'B27' 'B28' 'B29' 'B30' 'B31' 'B32' 'C1' 'C2' 'C3' 'C4' 'C5' 'C6' 'C7' 'C8' 'C9' 'C10' 'C11' 'C12' 'C13' 'C14' 'C15' 'C16' 'C17' 'C18' 'C19' 'C20' 'C21' 'C22' 'C23' 'C24' 'C25' 'C26' 'C27' 'C28' 'C29' 'C30' 'C31' 'C32' 'D1' 'D2' 'D3' 'D4' 'D5' 'D6' 'D7' 'D8' 'D9' 'D10' 'D11' 'D12' 'D13' 'D14' 'D15' 'D16' 'D17' 'D18' 'D19' 'D20' 'D21' 'D22' 'D23' 'D24' 'D25' 'D26' 'D27' 'D28' 'D29' 'D30' 'D31' 'D32' 'EXG1' 'EXG2' 'EXG3' 'EXG4' 'EXG5' 'EXG6' 'EXG7' 'EXG8' 'Status'}; labelnew = { 'P9' 'PPO9h' 'PO7' 'PPO5h' 'PPO3h' 'PO5h' 'POO9h' 'PO9' 'I1' 'OI1h' 'O1' 'POO1' 'PO3h' 'PPO1h' 'PPO2h' 'POz' 'Oz' 'Iz' 'I2' 'OI2h' 'O2' 'POO2' 'PO4h' 'PPO4h' 'PO6h' 'POO10h' 'PO10' 'PO8' 'PPO6h' 'PPO10h' 'P10' 'P8' 'TPP9h' 'TP7' 'TTP7h' 'CP5' 'TPP7h' 'P7' 'P5' 'CPP5h' 'CCP5h' 'CP3' 'P3' 'CPP3h' 'CCP3h' 'CP1' 'P1' 'Pz' 'CPP1h' 'CPz' 'CPP2h' 'P2' 'CPP4h' 'CP2' 'CCP4h' 'CP4' 'P4' 'P6' 'CPP6h' 'CCP6h' 'CP6' 'TPP8h' 'TP8' 'TPP10h' 'T7' 'FTT7h' 'FT7' 'FC5' 'FCC5h' 'C5' 'C3' 'FCC3h' 'FC3' 'FC1' 'C1' 'CCP1h' 'Cz' 'FCC1h' 'FCz' 'FFC1h' 'Fz' 'FFC2h' 'FC2' 'FCC2h' 'CCP2h' 'C2' 'C4' 'FCC4h' 'FC4' 'FC6' 'FCC6h' 'C6' 'TTP8h' 'T8' 'FTT8h' 'FT8' 'FT9' 'FFT9h' 'F7' 'FFT7h' 'FFC5h' 'F5' 'AFF7h' 'AF7' 'AF5h' 'AFF5h' 'F3' 'FFC3h' 'F1' 'AF3h' 'Fp1' 'Fpz' 'Fp2' 'AFz' 'AF4h' 'F2' 'FFC4h' 'F4' 'AFF6h' 'AF6h' 'AF8' 'AFF8h' 'F6' 'FFC6h' 'FFT8h' 'F8' 'FFT10h' 'FT10'}; % rename the channel labels for i=1:length(labelnew) chan = strcmp(labelold(i), hdr.label); hdr.label(chan) = labelnew(chan); end end case {'biosemi_old'} % this uses the openbdf and readbdf functions that were copied from EEGLAB orig = openbdf(filename); if any(orig.Head.SampleRate~=orig.Head.SampleRate(1)) error('channels with different sampling rate not supported'); end hdr.Fs = orig.Head.SampleRate(1); hdr.nChans = orig.Head.NS; hdr.label = cellstr(orig.Head.Label); % it is continuous data, therefore append all records in one trial hdr.nSamples = orig.Head.NRec * orig.Head.Dur * orig.Head.SampleRate(1); hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.orig = orig; % close the file between separate read operations fclose(orig.Head.FILE.FID); case 'blackrock_nev' error('this still needs some work'); case 'blackrock_nsx' ft_hastoolbox('NPMK', 1); % ensure that the filename contains a full path specification, % otherwise the low-level function fails [p, f, x] = fileparts(filename); if ~isempty(p) % this is OK elseif isempty(p) filename = which(filename); end orig = openNSx(filename, 'noread'); hdr = []; hdr.Fs = orig.MetaTags.SamplingFreq; hdr.nChans = orig.MetaTags.ChannelCount; hdr.nSamples = orig.MetaTags.DataPoints; hdr.nSamplesPre = 0; hdr.nTrials = 1; %? hdr.label = deblank({orig.ElectrodesInfo.Label})'; hdr.chanunit = deblank({hdr.orig.ElectrodesInfo.AnalogUnits})'; hdr.orig = orig; case {'brainvision_vhdr', 'brainvision_seg', 'brainvision_eeg', 'brainvision_dat'} orig = read_brainvision_vhdr(filename); hdr.Fs = orig.Fs; hdr.nChans = orig.NumberOfChannels; hdr.label = orig.label; hdr.nSamples = orig.nSamples; hdr.nSamplesPre = orig.nSamplesPre; hdr.nTrials = orig.nTrials; hdr.orig = orig; % assign the channel type and units for the known channels hdr.chantype = repmat({'eeg'}, size(hdr.label)); hdr.chanunit = repmat({'uV'}, size(hdr.label)); case 'bucn_nirs' orig = read_bucn_nirshdr(filename); hdr = rmfield(orig, 'time'); 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); if isempty(orig) % this is to deal with data from the 64 channel system and the error % readCTFds: .meg4 file header=MEG4CPT Valid header options: MEG41CP MEG42CP error('could not read CTF with this implementation, please try again with the ''ctf_old'' file format'); end hdr.Fs = orig.res4.sample_rate; hdr.nChans = orig.res4.no_channels; hdr.nSamples = orig.res4.no_samples; hdr.nSamplesPre = orig.res4.preTrigPts; hdr.nTrials = orig.res4.no_trials; hdr.label = cellstr(orig.res4.chanNames); for i=1:numel(hdr.label) % remove the site-specific numbers from each channel name, e.g. 'MZC01-1706' becomes 'MZC01' hdr.label{i} = strtok(hdr.label{i}, '-'); end % read the balance coefficients, these are used to compute the synthetic gradients coeftype = cellstr(char(orig.res4.scrr(:).coefType)); try [alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig,'NONE', 'T'); orig.BalanceCoefs.none.alphaMEG = alphaMEG; orig.BalanceCoefs.none.MEGlist = MEGlist; orig.BalanceCoefs.none.Refindex = Refindex; catch warning('cannot read balancing coefficients for NONE'); end if any(~cellfun(@isempty,strfind(coeftype, 'G1BR'))) try [alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig,'G1BR', 'T'); orig.BalanceCoefs.G1BR.alphaMEG = alphaMEG; orig.BalanceCoefs.G1BR.MEGlist = MEGlist; orig.BalanceCoefs.G1BR.Refindex = Refindex; catch warning('cannot read balancing coefficients for G1BR'); end end if any(~cellfun(@isempty,strfind(coeftype, 'G2BR'))) try [alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig, 'G2BR', 'T'); orig.BalanceCoefs.G2BR.alphaMEG = alphaMEG; orig.BalanceCoefs.G2BR.MEGlist = MEGlist; orig.BalanceCoefs.G2BR.Refindex = Refindex; catch warning('cannot read balancing coefficients for G2BR'); end end if any(~cellfun(@isempty,strfind(coeftype, 'G3BR'))) try [alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig, 'G3BR', 'T'); orig.BalanceCoefs.G3BR.alphaMEG = alphaMEG; orig.BalanceCoefs.G3BR.MEGlist = MEGlist; orig.BalanceCoefs.G3BR.Refindex = Refindex; catch warning('cannot read balancing coefficients for G3BR'); end end if any(~cellfun(@isempty,strfind(coeftype, 'G3AR'))) try [alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig, 'G3AR', 'T'); orig.BalanceCoefs.G3AR.alphaMEG = alphaMEG; orig.BalanceCoefs.G3AR.MEGlist = MEGlist; orig.BalanceCoefs.G3AR.Refindex = Refindex; catch % May not want a warning here if these are not commonly used. % Already get a (fprintf) warning from getCTFBalanceCoefs.m % warning('cannot read balancing coefficients for G3AR'); end end % add a gradiometer structure for forward and inverse modelling try hdr.grad = ctf2grad(orig, strcmp(coordsys, 'dewar'), coilaccuracy); catch % this fails if the res4 file is not correctly closed, e.g. during realtime processing tmp = lasterror; disp(tmp.message); warning('could not construct gradiometer definition from the header'); end % for realtime analysis EOF chasing the res4 does not correctly % estimate the number of samples, so we compute it on the fly from the % meg4 file sizes. sz = 0; files = dir([filename '/*.*meg4']); for j=1:numel(files) sz = sz + files(j).bytes; end hdr.nTrials = floor((sz - 8) / (hdr.nChans*4) / hdr.nSamples); % add the original header details hdr.orig = orig; case {'ctf_old', 'read_ctf_res4'} % read it using the open-source MATLAB code that originates from CTF and that was modified by the FCDC orig = read_ctf_res4(headerfile); hdr.Fs = orig.Fs; hdr.nChans = orig.nChans; hdr.nSamples = orig.nSamples; hdr.nSamplesPre = orig.nSamplesPre; hdr.nTrials = orig.nTrials; hdr.label = orig.label; % add a gradiometer structure for forward and inverse modelling try hdr.grad = ctf2grad(orig); catch % this fails if the res4 file is not correctly closed, e.g. during realtime processing tmp = lasterror; disp(tmp.message); warning('could not construct gradiometer definition from the header'); end % add the original header details hdr.orig = orig; case 'ctf_read_res4' % check that the required low-level toolbos ix available ft_hastoolbox('eegsf', 1); % read it using the CTF importer from the NIH and Daren Weber orig = ctf_read_res4(fileparts(headerfile), 0); % convert the header into a structure that FieldTrip understands hdr = []; hdr.Fs = orig.setup.sample_rate; hdr.nChans = length(orig.sensor.info); hdr.nSamples = orig.setup.number_samples; hdr.nSamplesPre = orig.setup.pretrigger_samples; hdr.nTrials = orig.setup.number_trials; for i=1:length(orig.sensor.info) hdr.label{i} = orig.sensor.info(i).label; end hdr.label = hdr.label(:); % add a gradiometer structure for forward and inverse modelling try hdr.grad = ctf2grad(orig); catch % this fails if the res4 file is not correctly closed, e.g. during realtime processing tmp = lasterror; disp(tmp.message); warning('could not construct gradiometer definition from the header'); end % add the original header details hdr.orig = orig; case 'ctf_shm' % read the header information from shared memory hdr = read_shm_header(filename); case 'dataq_wdq' orig = read_wdq_header(filename); hdr = []; hdr.Fs = orig.fsample; hdr.nChans = orig.nchan; hdr.nSamples = orig.nbytesdat/(2*hdr.nChans); hdr.nSamplesPre = 0; hdr.nTrials = 1; for k = 1:hdr.nChans if isfield(orig.chanhdr(k), 'annot') && ~isempty(orig.chanhdr(k).annot) hdr.label{k,1} = orig.chanhdr(k).annot; else hdr.label{k,1} = orig.chanhdr(k).label; end end % add the original header details hdr.orig = orig; case {'deymed_ini' 'deymed_dat'} % the header is stored in a *.ini file orig = read_deymed_ini(headerfile); hdr = []; hdr.Fs = orig.Fs; hdr.nChans = orig.nChans; hdr.nSamples = orig.nSamples; hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.label = orig.label(:); hdr.orig = orig; % remember the original details case 'edf' % this reader is largely similar to the bdf reader if isempty(chanindx) hdr = read_edf(filename); else hdr = read_edf(filename,[],1); if chanindx > hdr.orig.NS error('FILEIO:InvalidChanIndx', 'selected channels are not present in the data'); else hdr = read_edf(filename,[],chanindx); end end case 'eep_avr' % check that the required low-level toolbox is available ft_hastoolbox('eeprobe', 1); % read the whole average and keep only header info (it is a bit silly, but the easiest to do here) hdr = read_eep_avr(filename); hdr.Fs = hdr.rate; hdr.nChans = size(hdr.data,1); hdr.nSamples = size(hdr.data,2); hdr.nSamplesPre = hdr.xmin*hdr.rate/1000; hdr.nTrials = 1; % it can always be interpreted as continuous data % remove the data and variance if present hdr = removefields(hdr, {'data', 'variance'}); case 'eep_cnt' % check that the required low-level toolbox is available ft_hastoolbox('eeprobe', 1); % read the first sample from the continous data, this will also return the header orig = read_eep_cnt(filename, 1, 1); hdr.Fs = orig.rate; hdr.nSamples = orig.nsample; hdr.nSamplesPre = 0; hdr.label = orig.label; hdr.nChans = orig.nchan; hdr.nTrials = 1; % it can always be interpreted as continuous data hdr.orig = orig; % remember the original details case 'eeglab_set' hdr = read_eeglabheader(filename); case 'eeglab_erp' hdr = read_erplabheader(filename); case 'emotiv_mat' % This is a MATLAB *.mat file that is created using the Emotiv MATLAB % example code. It contains a 25xNsamples matrix and some other stuff. orig = load(filename); hdr.Fs = 128; hdr.nChans = 25; hdr.nSamples = size(orig.data_eeg,1); hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.label = {'ED_COUNTER','ED_INTERPOLATED','ED_RAW_CQ','ED_AF3','ED_F7','ED_F3','ED_FC5','ED_T7','ED_P7','ED_O1','ED_O2','ED_P8','ED_T8','ED_FC6','ED_F4','ED_F8','ED_AF4','ED_GYROX','ED_GYROY','ED_TIMESTAMP','ED_ES_TIMESTAMP','ED_FUNC_ID','ED_FUNC_VALUE','ED_MARKER','ED_SYNC_SIGNAL'}; % store the complete information in hdr.orig % ft_read_data and ft_read_event will get it from there hdr.orig = orig; case 'eyelink_asc' asc = read_eyelink_asc(filename); hdr.nChans = size(asc.dat,1); hdr.nSamples = size(asc.dat,2); hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.FirstTimeStamp = asc.dat(1,1); hdr.TimeStampPerSample = mean(diff(asc.dat(1,:))); hdr.Fs = 1000/hdr.TimeStampPerSample; % these timestamps are in miliseconds % give this warning only once ft_warning('creating fake channel names'); for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end % remember the original header details hdr.orig.header = asc.header; % remember all header and data details upon request if cache hdr.orig = asc; end case 'spmeeg_mat' hdr = read_spmeeg_header(filename); case 'ced_spike6mat' hdr = read_spike6mat_header(filename); case 'egi_egia' [fhdr,chdr,ename,cnames,fcom,ftext] = read_egis_header(filename); [p, f, x] = fileparts(filename); if any(chdr(:,4)-chdr(1,4)) error('Sample rate not the same for all cells.'); end; hdr.Fs = chdr(1,4); %making assumption that sample rate is same for all cells hdr.nChans = fhdr(19); for i = 1:hdr.nChans % this should be consistent with ft_senslabel hdr.label{i,1} = ['E' num2str(i)]; end; %since NetStation does not properly set the fhdr(11) field, use the number of subjects from the chdr instead hdr.nTrials = chdr(1,2)*fhdr(18); %number of trials is numSubjects * numCells hdr.nSamplesPre = ceil(fhdr(14)/(1000/hdr.Fs)); if any(chdr(:,3)-chdr(1,3)) error('Number of samples not the same for all cells.'); end; hdr.nSamples = chdr(1,3); %making assumption that number of samples is same for all cells % remember the original header details hdr.orig.fhdr = fhdr; hdr.orig.chdr = chdr; hdr.orig.ename = ename; hdr.orig.cnames = cnames; hdr.orig.fcom = fcom; hdr.orig.ftext = ftext; case 'egi_egis' [fhdr,chdr,ename,cnames,fcom,ftext] = read_egis_header(filename); [p, f, x] = fileparts(filename); if any(chdr(:,4)-chdr(1,4)) error('Sample rate not the same for all cells.'); end; hdr.Fs = chdr(1,4); %making assumption that sample rate is same for all cells hdr.nChans = fhdr(19); for i = 1:hdr.nChans % this should be consistent with ft_senslabel hdr.label{i,1} = ['E' num2str(i)]; end; hdr.nTrials = sum(chdr(:,2)); hdr.nSamplesPre = ceil(fhdr(14)/(1000/hdr.Fs)); % assuming that a utility was used to insert the correct baseline % duration into the header since it is normally absent. This slot is % actually allocated to the age of the subject, although NetStation % does not use it when generating an EGIS session file. if any(chdr(:,3)-chdr(1,3)) error('Number of samples not the same for all cells.'); end; hdr.nSamples = chdr(1,3); %making assumption that number of samples is same for all cells % remember the original header details hdr.orig.fhdr = fhdr; hdr.orig.chdr = chdr; hdr.orig.ename = ename; hdr.orig.cnames = cnames; hdr.orig.fcom = fcom; hdr.orig.ftext = ftext; case 'egi_sbin' [header_array, CateNames, CatLengths, preBaseline] = read_sbin_header(filename); [p, f, x] = fileparts(filename); hdr.Fs = header_array(9); hdr.nChans = header_array(10); for i = 1:hdr.nChans % this should be consistent with ft_senslabel hdr.label{i,1} = ['E' num2str(i)]; end; hdr.nTrials = header_array(15); hdr.nSamplesPre = preBaseline; hdr.nSamples = header_array(16); % making assumption that number of samples is same for all cells % remember the original header details hdr.orig.header_array = header_array; hdr.orig.CateNames = CateNames; hdr.orig.CatLengths = CatLengths; case {'egi_mff_v1' 'egi_mff'} % this is currently the default % The following represents the code that was written by Ingrid, Robert % and Giovanni to get started with the EGI mff dataset format. It might % not support all details of the file formats. % % An alternative implementation has been provided by EGI, this is % released as fieldtrip/external/egi_mff and referred further down in % this function as 'egi_mff_v2'. if ~usejava('jvm') error('the xml2struct requires MATLAB to be running with the Java virtual machine (JVM)'); % an alternative implementation which does not require the JVM but runs much slower is % available from http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0 end % get header info from .bin files binfiles = dir(fullfile(filename, 'signal*.bin')); if isempty(binfiles) error('could not find any signal.bin in mff directory') end orig = []; for iSig = 1:length(binfiles) signalname = binfiles(iSig).name; fullsignalname = fullfile(filename, signalname); orig.signal(iSig).blockhdr = read_mff_bin(fullsignalname); end % get hdr info from xml files warning('off', 'MATLAB:REGEXP:deprecated') % due to some small code xml2struct xmlfiles = dir( fullfile(filename, '*.xml')); disp('reading xml files to obtain header info...') for i = 1:numel(xmlfiles) if strcmpi(xmlfiles(i).name(1:2), '._') % Mac sometimes creates this useless files, don't use them elseif strcmpi(xmlfiles(i).name(1:6), 'Events') % don't read in events here, can take a lot of time, and we can do that in ft_read_event else fieldname = xmlfiles(i).name(1:end-4); filename_xml = fullfile(filename, xmlfiles(i).name); orig.xml.(fieldname) = xml2struct(filename_xml); end end warning('on', 'MATLAB:REGEXP:deprecated') % epochs.xml seems the most common version, but epoch.xml might also % occur, so use only one name if isfield(orig.xml, 'epoch') orig.xml.epochs = orig.xml.epoch; orig.xml = rmfield(orig.xml, 'epoch'); end % make hdr according to FieldTrip rules hdr = []; Fs = zeros(length(orig.signal),1); nChans = zeros(length(orig.signal),1); nSamples = zeros(length(orig.signal),1); for iSig = 1:length(orig.signal) Fs(iSig) = orig.signal(iSig).blockhdr(1).fsample(1); nChans(iSig) = orig.signal(iSig).blockhdr(1).nsignals; % the number of samples per block can be different nSamples_Block = zeros(length(orig.signal(iSig).blockhdr),1); for iBlock = 1:length(orig.signal(iSig).blockhdr) nSamples_Block(iBlock) = orig.signal(iSig).blockhdr(iBlock).nsamples(1); end nSamples(iSig) = sum(nSamples_Block); end if length(unique(Fs)) > 1 || length(unique(nSamples)) > 1 error('Fs and nSamples should be the same in all signals') end hdr.Fs = Fs(1); hdr.nChans = sum(nChans); hdr.nSamplesPre = 0; hdr.nSamples = nSamples(1); hdr.nTrials = 1; % get channel labels for signal 1 (main net), otherwise create them if isfield(orig.xml, 'sensorLayout') % asuming that signal1 is hdEEG sensornet, and channels are in xml file sensorLayout for iSens = 1:numel(orig.xml.sensorLayout.sensors) if ~isempty(orig.xml.sensorLayout.sensors(iSens).sensor.name) && ~(isstruct(orig.xml.sensorLayout.sensors(iSens).sensor.name) && numel(fieldnames(orig.xml.sensorLayout.sensors(iSens).sensor.name))==0) %only get name when channel is EEG (type 0), or REF (type 1), %rest are non interesting channels like place holders and COM and should not be added. if strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '0') || strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '1') % get the sensor name from the datafile hdr.label{iSens} = orig.xml.sensorLayout.sensors(iSens).sensor.name; end elseif strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '0') % EEG chan % this should be consistent with ft_senslabel hdr.label{iSens} = ['E' num2str(orig.xml.sensorLayout.sensors(iSens).sensor.number)]; elseif strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '1') % REF chan % ingnie: I now choose REF as name for REF channel since our discussion see bug 1407. Arbitrary choice... hdr.label{iSens} = ['REF' num2str(iSens)]; else % non interesting channels like place holders and COM end end % check if the amount of lables corresponds with nChannels in signal 1 if length(hdr.label) == nChans(1) % good elseif length(hdr.label) > orig.signal(1).blockhdr(1).nsignals warning('found more lables in xml.sensorLayout than channels in signal 1, thus can not use info in sensorLayout, creating labels on the fly') for iSens = 1:orig.signal(1).blockhdr(1).nsignals % this should be consistent with ft_senslabel hdr.label{iSens} = ['E' num2str(iSens)]; end else warning('found less lables in xml.sensorLayout than channels in signal 1, thus can not use info in sensorLayout, creating labels on the fly') for iSens = 1:orig.signal(1).blockhdr(1).nsignals % this should be consistent with ft_senslabel hdr.label{iSens} = ['E' num2str(iSens)]; end end % get lables for other signals if length(orig.signal) == 2 if isfield(orig.xml, 'pnsSet') % signal2 is PIB box, and lables are in xml file pnsSet nbEEGchan = length(hdr.label); for iSens = 1:numel(orig.xml.pnsSet.sensors) hdr.label{nbEEGchan+iSens} = num2str(orig.xml.pnsSet.sensors(iSens).sensor.name); end if length(hdr.label) == orig.signal(2).blockhdr(1).nsignals + orig.signal(2).blockhdr(1).nsignals % good elseif length(hdr.label) < orig.signal(1).blockhdr(1).nsignals + orig.signal(2).blockhdr(1).nsignals warning('found less lables in xml.pnsSet than channels in signal 2, labeling with s2_unknownN instead') for iSens = length(hdr.label)+1 : orig.signal(1).blockhdr(1).nsignals + orig.signal(2).blockhdr(1).nsignals hdr.label{iSens} = ['s2_unknown', num2str(iSens)]; end else warning('found more lables in xml.pnsSet than channels in signal 2, thus can not use info in pnsSet, and labeling with s2_eN instead') for iSens = orig.signal(1).blockhdr(1).nsignals+1 : orig.signal(1).blockhdr(1).nsignals + orig.signal(2).blockhdr(1).nsignals hdr.label{iSens} = ['s2_E', num2str(iSens)]; end end else % signal2 is not PIBbox warning('creating channel labels for signal 2 on the fly') for iSens = 1:orig.signal(2).blockhdr(1).nsignals hdr.label{end+1} = ['s2_E', num2str(iSens)]; end end elseif length(orig.signal) > 2 % loop over signals and label channels accordingly warning('creating channel labels for signal 2 to signal N on the fly') for iSig = 2:length(orig.signal) for iSens = 1:orig.signal(iSig).blockhdr(1).nsignals if iSig == 1 && iSens == 1 hdr.label{1} = ['s',num2str(iSig),'_E', num2str(iSens)]; else hdr.label{end+1} = ['s',num2str(iSig),'_E', num2str(iSens)]; end end end end else % no xml.sensorLayout present warning('no sensorLayout found in xml files, creating channel labels on the fly') for iSig = 1:length(orig.signal) for iSens = 1:orig.signal(iSig).blockhdr(1).nsignals if iSig == 1 && iSens == 1 hdr.label{1} = ['s',num2str(iSig),'_E', num2str(iSens)]; else hdr.label{end+1} = ['s',num2str(iSig),'_E', num2str(iSens)]; end end end end % check if multiple epochs are present if isfield(orig.xml,'epochs') % add info to header about which sample correspond to which epochs, becasue this is quite hard for user to get... epochdef = zeros(length(orig.xml.epochs),3); for iEpoch = 1:length(orig.xml.epochs) if iEpoch == 1 epochdef(iEpoch,1) = round(str2double(orig.xml.epochs(iEpoch).epoch.beginTime)./(1000000./hdr.Fs))+1; epochdef(iEpoch,2) = round(str2double(orig.xml.epochs(iEpoch).epoch.endTime )./(1000000./hdr.Fs)); epochdef(iEpoch,3) = round(str2double(orig.xml.epochs(iEpoch).epoch.beginTime)./(1000000./hdr.Fs)); % offset corresponds to timing else NbSampEpoch = round(str2double(orig.xml.epochs(iEpoch).epoch.endTime)./(1000000./hdr.Fs) - str2double(orig.xml.epochs(iEpoch).epoch.beginTime)./(1000000./hdr.Fs)); epochdef(iEpoch,1) = epochdef(iEpoch-1,2) + 1; epochdef(iEpoch,2) = epochdef(iEpoch-1,2) + NbSampEpoch; epochdef(iEpoch,3) = round(str2double(orig.xml.epochs(iEpoch).epoch.beginTime)./(1000000./hdr.Fs)); % offset corresponds to timing end end if epochdef(end,2) ~= hdr.nSamples % check for NS 4.5.4 picosecond timing if (epochdef(end,2)/1000) == hdr.nSamples for iEpoch=1:size(epochdef,1) epochdef(iEpoch,1) = ((epochdef(iEpoch,1)-1)/1000)+1; epochdef(iEpoch,2) = epochdef(iEpoch,2)/1000; epochdef(iEpoch,3) = epochdef(iEpoch,3)/1000; end; warning('mff apparently generated by NetStation 4.5.4. Adjusting time scale to microseconds from nanoseconds.'); else error('number of samples in all epochs do not add up to total number of samples') end end epochLengths = epochdef(:,2)-epochdef(:,1)+1; if ~any(diff(epochLengths)) hdr.nSamples = epochLengths(1); hdr.nTrials = length(epochLengths); else warning('the data contains multiple epochs with variable length, possibly causing discontinuities in the data') % sanity check if epochdef(end,2) ~= hdr.nSamples % check for NS 4.5.4 picosecond timing if (epochdef(end,2)/1000) == hdr.nSamples for iEpoch=1:size(epochdef,1) epochdef(iEpoch,1)=((epochdef(iEpoch,1)-1)/1000)+1; epochdef(iEpoch,2)=epochdef(iEpoch,2)/1000; epochdef(iEpoch,3)=epochdef(iEpoch,3)/1000; end; disp('mff apparently generated by NetStation 4.5.4. Adjusting time scale to microseconds from nanoseconds.'); else error('number of samples in all epochs do not add up to total number of samples') end; end end orig.epochdef = epochdef; end; hdr.orig = orig; case 'egi_mff_v2' % ensure that the EGI_MFF toolbox is on the path ft_hastoolbox('egi_mff', 1); % ensure that the JVM is running and the jar file is on the path %%%%%%%%%%%%%%%%%%%%%% %workaround for MATLAB bug resulting in global variables being cleared globalTemp=cell(0); globalList=whos('global'); varList=whos; for i=1:length(globalList) eval(['global ' globalList(i).name ';']); eval(['globalTemp{end+1}=' globalList(i).name ';']); end; %%%%%%%%%%%%%%%%%%%%%% mff_setup; %%%%%%%%%%%%%%%%%%%%%% %workaround for MATLAB bug resulting in global variables being cleared varNames={varList.name}; for i=1:length(globalList) eval(['global ' globalList(i).name ';']); eval([globalList(i).name '=globalTemp{i};']); if ~any(strcmp(globalList(i).name,varNames)) %was global variable originally out of scope? eval(['clear ' globalList(i).name ';']); %clears link to global variable without affecting it end; end; clear globalTemp globalList varNames varList; %%%%%%%%%%%%%%%%%%%%%% if isunix && filename(1)~=filesep % add the full path to the dataset directory filename = fullfile(pwd, filename); elseif ispc && ~any(strcmp(filename(2),{':','\'})) % add the full path, including drive letter or slashes as needed. filename = fullfile(pwd, filename); end hdr = read_mff_header(filename); case 'fcdc_buffer' % read from a networked buffer for realtime analysis [host, port] = filetype_check_uri(filename); if retry orig = []; while isempty(orig) try % try reading the header, catch the error and retry orig = buffer('get_hdr', [], host, port); catch warning('could not read header from %s, retrying in 1 second', filename); pause(1); end end % while else % try reading the header only once, give error if it fails orig = buffer('get_hdr', [], host, port); end % if retry % construct the standard header elements hdr.Fs = orig.fsample; hdr.nChans = orig.nchans; hdr.nSamples = orig.nsamples; hdr.nSamplesPre = 0; % since continuous hdr.nTrials = 1; % since continuous hdr.orig = []; % this will contain the chunks (if present) % add the contents of attached FIF_header chunk after decoding to MATLAB structure if isfield(orig, 'neuromag_header') if isempty(cachechunk) % this only needs to be decoded once cachechunk = decode_fif(orig); end % convert to FieldTrip format header hdr.label = cachechunk.ch_names(:); hdr.nChans = cachechunk.nchan; hdr.Fs = cachechunk.sfreq; % add a gradiometer structure for forward and inverse modelling try [grad, elec] = mne2grad(cachechunk, true, coilaccuracy); % the coordsys is 'dewar' if ~isempty(grad) hdr.grad = grad; end if ~isempty(elec) hdr.elec = elec; end catch disp(lasterr); end % store the original details hdr.orig = cachechunk; end % add the contents of attached RES4 chunk after decoding to MATLAB structure if isfield(orig, 'ctf_res4') if isempty(cachechunk) % this only needs to be decoded once cachechunk = decode_res4(orig.ctf_res4); end % copy the gradiometer details hdr.grad = cachechunk.grad; hdr.orig = cachechunk.orig; if isfield(orig, 'channel_names') % get the same selection of channels from the two chunks [selbuf, selres4] = match_str(orig.channel_names, cachechunk.label); if length(selres4)<length(orig.channel_names) error('the res4 chunk did not contain all channels') end % copy some of the channel details hdr.label = cachechunk.label(selres4); hdr.chantype = cachechunk.chantype(selres4); hdr.chanunit = cachechunk.chanunit(selres4); % add the channel names chunk as well hdr.orig.channel_names = orig.channel_names; end % add the raw chunk as well hdr.orig.ctf_res4 = orig.ctf_res4; end % add the contents of attached NIFTI-1 chunk after decoding to MATLAB structure if isfield(orig, 'nifti_1') hdr.nifti_1 = decode_nifti1(orig.nifti_1); % add the raw chunk as well hdr.orig.nifti_1 = orig.nifti_1; end % add the contents of attached SiemensAP chunk after decoding to MATLAB structure if isfield(orig, 'siemensap') && exist('sap2matlab')==3 % only run this if MEX file is present hdr.siemensap = sap2matlab(orig.siemensap); % add the raw chunk as well hdr.orig.siemensap = orig.siemensap; end if ~isfield(hdr, 'label') % prevent overwriting the labels that we might have gotten from a RES4 chunk if isfield(orig, 'channel_names') hdr.label = orig.channel_names; else hdr.label = cell(hdr.nChans,1); if hdr.nChans < 2000 % don't do this for fMRI etc. ft_warning('creating fake channel names'); % give this warning only once for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end else ft_warning('skipping fake channel names'); % give this warning only once checkUniqueLabels = false; end end end if ~isfield(hdr, 'chantype') % prevent overwriting the chantypes that we might have gotten from a RES4 chunk hdr.chantype = cell(hdr.nChans,1); if hdr.nChans < 2000 % don't do this for fMRI etc. hdr.chantype = repmat({'unknown'}, 1, hdr.nChans); end end if ~isfield(hdr, 'chanunit') % prevent overwriting the chanunits that we might have gotten from a RES4 chunk hdr.chanunit = cell(hdr.nChans,1); if hdr.nChans < 2000 % don't do this for fMRI etc. hdr.chanunit = repmat({'unknown'}, 1, hdr.nChans); end end hdr.orig.bufsize = orig.bufsize; case 'fcdc_buffer_offline' [hdr, nameFlag] = read_buffer_offline_header(headerfile); switch nameFlag case 0 % no labels generated (fMRI etc) checkUniqueLabels = false; % no need to check these case 1 % has generated fake channels % give this warning only once ft_warning('creating fake channel names'); checkUniqueLabels = false; % no need to check these case 2 % got labels from chunk, check those checkUniqueLabels = true; end case 'fcdc_matbin' % this is multiplexed data in a *.bin file, accompanied by a MATLAB file containing the header load(headerfile, 'hdr'); case 'fcdc_mysql' % check that the required low-level toolbox is available ft_hastoolbox('mysql', 1); % read from a MySQL server listening somewhere else on the network db_open(filename); if db_blob hdr = db_select_blob('fieldtrip.header', 'msg', 1); else hdr = db_select('fieldtrip.header', {'nChans', 'nSamples', 'nSamplesPre', 'Fs', 'label'}, 1); hdr.label = mxDeserialize(hdr.label); end case 'gtec_mat' % this is a simple MATLAB format, it contains a log and a names variable tmp = load(headerfile); log = tmp.log; names = tmp.names; hdr.label = cellstr(names); hdr.nChans = size(log,1); hdr.nSamples = size(log,2); hdr.nSamplesPre = 0; hdr.nTrials = 1; % assume continuous data, not epoched % compute the sampling frequency from the time channel sel = strcmp(hdr.label, 'Time'); time = log(sel,:); hdr.Fs = 1./(time(2)-time(1)); % also remember the complete data upon request if cache hdr.orig.log = log; hdr.orig.names = names; end case 'gdf' % this requires the biosig toolbox ft_hastoolbox('BIOSIG', 1); % In the case that the gdf files are written by one of the FieldTrip % realtime applications, such as biosig2ft, the gdf recording can be % split over multiple 1GB files. The sequence of files is then % filename.gdf <- this is the one that should be specified as the filename/dataset % filename_1.gdf % filename_2.gdf % ... [p, f, x] = fileparts(filename); if exist(sprintf('%s_%d%s', fullfile(p, f), 1, x), 'file') % there are multiple files, count the number of additional files (excluding the first one) count = 0; while exist(sprintf('%s_%d%s', fullfile(p, f), count+1, x), 'file') count = count+1; end hdr = read_biosig_header(filename); for i=1:count hdr(i+1) = read_biosig_header(sprintf('%s_%d%s', fullfile(p, f), i, x)); % do some sanity checks if hdr(i+1).nChans~=hdr(1).nChans error('multiple GDF files detected that should be appended, but the channel count is inconsistent'); elseif hdr(i+1).Fs~=hdr(1).Fs error('multiple GDF files detected that should be appended, but the sampling frequency is inconsistent'); elseif ~isequal(hdr(i+1).label, hdr(1).label) error('multiple GDF files detected that should be appended, but the channel names are inconsistent'); end end % for count % combine all headers into one combinedhdr = []; combinedhdr.Fs = hdr(1).Fs; combinedhdr.nChans = hdr(1).nChans; combinedhdr.nSamples = sum([hdr.nSamples].*[hdr.nTrials]); combinedhdr.nSamplesPre = 0; combinedhdr.nTrials = 1; combinedhdr.label = hdr(1).label; combinedhdr.orig = hdr; % include all individual file details hdr = combinedhdr; else % there is only a single file hdr = read_biosig_header(filename); % the GDF format is always continuous hdr.nSamples = hdr.nSamples * hdr.nTrials; hdr.nTrials = 1; hdr.nSamplesPre = 0; end % if single or multiple gdf files case {'itab_raw' 'itab_mhd'} % read the full header information frtom the binary header structure header_info = read_itab_mhd(headerfile); % these are the channels that are visible to fieldtrip chansel = 1:header_info.nchan; % convert the header information into a FieldTrip compatible format hdr.nChans = length(chansel); hdr.label = {header_info.ch(chansel).label}; hdr.label = hdr.label(:); % should be column vector hdr.Fs = header_info.smpfq; % it will always be continuous data hdr.nSamples = header_info.ntpdata; hdr.nSamplesPre = 0; % it is a single continuous trial hdr.nTrials = 1; % it is a single continuous trial % keep the original details AND the list of channels as used by fieldtrip hdr.orig = header_info; hdr.orig.chansel = chansel; % add the gradiometer definition hdr.grad = itab2grad(header_info); case 'jaga16' % this is hard-coded for the Jinga-Hi JAGA16 system with 16 channels packetsize = (4*2 + 6*2 + 16*43*2); % in bytes % read the first packet fid = fopen(filename, 'r'); buf = fread(fid, packetsize/2, 'uint16'); fclose(fid); if buf(1)==0 % it does not have timestamps, i.e. it is the raw UDP stream packetsize = packetsize - 8; % in bytes packet = jaga16_packet(buf(1:(packetsize/2)), false); else % each packet starts with a timestamp packet = jaga16_packet(buf, true); end % determine the number of packets from the file size info = dir(filename); npackets = floor((info.bytes)/packetsize/2); hdr = []; hdr.Fs = packet.fsample; hdr.nChans = packet.nchan; hdr.nSamples = 43; hdr.nSamplesPre = 0; hdr.nTrials = npackets; hdr.label = cell(hdr.nChans,1); hdr.chantype = cell(hdr.nChans,1); hdr.chanunit = cell(hdr.nChans,1); for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); hdr.chantype{i} = 'eeg'; hdr.chanunit{i} = 'uV'; end % store some low-level details hdr.orig.offset = 0; hdr.orig.packetsize = packetsize; hdr.orig.packet = packet; hdr.orig.info = info; case {'manscan_mbi', 'manscan_mb2'} orig = in_fopen_manscan(filename); hdr.Fs = orig.prop.sfreq; hdr.nChans = numel(orig.channelmat.Channel); hdr.nTrials = 1; if isfield(orig, 'epochs') && ~isempty(orig.epochs) hdr.nSamples = 0; for i = 1:numel(orig.epochs) hdr.nSamples = hdr.nSamples + diff(orig.epochs(i).samples) + 1; end else hdr.nSamples = diff(orig.prop.samples) + 1; end if orig.prop.times(1) < 0 hdr.nSamplesPre = round(orig.prop.times(1)/hdr.Fs); else hdr.nSamplesPre = 0; end for i=1:hdr.nChans hdr.label{i,1} = orig.channelmat.Channel(i).Name; hdr.chantype{i,1} = lower(orig.channelmat.Channel(i).Type); if isequal(hdr.chantype{i,1}, 'eeg') hdr.chanunit{i, 1} = 'uV'; else hdr.chanunit{i, 1} = 'unknown'; end end hdr.orig = orig; case 'mega_neurone' % ensure that this external toolbox is on the path ft_hastoolbox('neurone', 1); if filename(end)~=filesep % it should end with a slash filename = [filename filesep]; end % this is like the EEGLAB data structure EEG = readneurone(filename); hdr.Fs = EEG.srate; hdr.nChans = EEG.nbchan; hdr.nSamples = EEG.pnts; hdr.nSamplesPre = -EEG.xmin*EEG.srate; hdr.nTrials = EEG.trials; try hdr.label = { EEG.chanlocs.labels }'; catch warning('creating default channel names'); for i=1:hdr.nChans hdr.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) hdr.elec.label{ind, 1} = EEG.chanlocs(i).labels; % this channel has a position hdr.elec.elecpos(ind,1) = EEG.chanlocs(i).X; hdr.elec.elecpos(ind,2) = EEG.chanlocs(i).Y; hdr.elec.elecpos(ind,3) = EEG.chanlocs(i).Z; ind = ind+1; end end if cache % also remember the data and events hdr.orig = EEG; else % remember only the header details hdr.orig = removefields(EEG, {'data', 'event'}); end case 'micromed_trc' orig = read_micromed_trc(filename); hdr = []; hdr.Fs = orig.Rate_Min; % FIXME is this correct? hdr.nChans = orig.Num_Chan; hdr.nSamples = orig.Num_Samples; hdr.nSamplesPre = 0; % continuous hdr.nTrials = 1; % continuous hdr.label = cell(1,hdr.nChans); % give this warning only once hdr.label = {orig.elec.Name}; hdr.chanunit = {orig.elec.Unit}; hdr.subjectname = orig.name; %warning('using a modified read_micromed_trc() function'); % this should be a column vector hdr.label = hdr.label(:); % remember the original header details hdr.orig = orig; case {'mpi_ds', 'mpi_dap'} hdr = read_mpi_ds(filename); case 'netmeg' ft_hastoolbox('netcdf', 1); % this will read all NetCDF data from the file and subsequently convert % each of the three elements into a more easy to parse MATLAB structure s = netcdf(filename); for i=1:numel(s.AttArray) fname = fixname(s.AttArray(i).Str); fval = s.AttArray(i).Val; if ischar(fval) fval = fval(fval~=0); % remove the \0 characters fval = strtrim(fval); % remove insignificant whitespace end Att.(fname) = fval; end for i=1:numel(s.VarArray) fname = fixname(s.VarArray(i).Str); fval = s.VarArray(i).Data; if ischar(fval) fval = fval(fval~=0); % remove the \0 characters fval = strtrim(fval); % remove insignificant whitespace end Var.(fname) = fval; end for i=1:numel(s.DimArray) fname = fixname(s.DimArray(i).Str); fval = s.DimArray(i).Dim; if ischar(fval) fval = fval(fval~=0); % remove the \0 characters fval = strtrim(fval); % remove insignificant whitespace end Dim.(fname) = fval; end % convert the relevant fields into the default header structure hdr.Fs = 1000/Var.samplinginterval; hdr.nChans = length(Var.channelstatus); hdr.nSamples = Var.numsamples; hdr.nSamplesPre = 0; hdr.nTrials = size(Var.waveforms, 1); hdr.chanunit = cellstr(reshape(Var.channelunits, hdr.nChans, 2)); hdr.chantype = cellstr(reshape(lower(Var.channeltypes), hdr.nChans, 3)); ft_warning('creating fake channel names'); hdr.label = cell(hdr.nChans, 1); for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end % remember the original details of the file % note that this also includes the data % this is large, but can be reused elsewhere hdr.orig.Att = Att; hdr.orig.Var = Var; hdr.orig.Dim = Dim; % construct the gradiometer structure from the complete header information hdr.grad = netmeg2grad(hdr); case 'nervus_eeg' hdr = read_nervus_header(filename); checkUniqueLabels = false; case 'neuralynx_dma' hdr = read_neuralynx_dma(filename); case 'neuralynx_sdma' hdr = read_neuralynx_sdma(filename); case 'neuralynx_ncs' ncs = read_neuralynx_ncs(filename, 1, 0); [p, f, x] = fileparts(filename); hdr.Fs = ncs.hdr.SamplingFrequency; hdr.label = {f}; hdr.nChans = 1; hdr.nTrials = 1; hdr.nSamplesPre = 0; hdr.nSamples = ncs.NRecords * 512; hdr.orig = ncs.hdr; FirstTimeStamp = ncs.hdr.FirstTimeStamp; % this is the first timestamp of the first block LastTimeStamp = ncs.hdr.LastTimeStamp; % this is the first timestamp of the last block, i.e. not the timestamp of the last sample hdr.TimeStampPerSample = double(LastTimeStamp - FirstTimeStamp) ./ ((ncs.NRecords-1)*512); hdr.FirstTimeStamp = FirstTimeStamp; case 'neuralynx_nse' nse = read_neuralynx_nse(filename, 1, 0); [p, f, x] = fileparts(filename); hdr.Fs = nse.hdr.SamplingFrequency; hdr.label = {f}; hdr.nChans = 1; hdr.nTrials = nse.NRecords; % each record contains one waveform hdr.nSamples = 32; % there are 32 samples in each waveform hdr.nSamplesPre = 0; hdr.orig = nse.hdr; % FIXME add hdr.FirstTimeStamp and hdr.TimeStampPerSample case {'neuralynx_ttl', 'neuralynx_tsl', 'neuralynx_tsh'} % these are hardcoded, they contain an 8-byte header and int32 values for a single channel % FIXME this should be done similar as neuralynx_bin, i.e. move the hdr into the function hdr = []; hdr.Fs = 32556; hdr.nChans = 1; hdr.nSamples = (filesize(filename)-8)/4; hdr.nSamplesPre = 1; hdr.nTrials = 1; hdr.label = {headerformat((end-3):end)}; case 'neuralynx_bin' hdr = read_neuralynx_bin(filename); case 'neuralynx_ds' hdr = read_neuralynx_ds(filename); case 'neuralynx_cds' hdr = read_neuralynx_cds(filename); case 'nexstim_nxe' hdr = read_nexstim_nxe(filename); case {'neuromag_fif' 'neuromag_mne'} % check that the required low-level toolbox is available ft_hastoolbox('mne', 1); info = fiff_read_meas_info(filename); % convert to FieldTrip format header hdr.label = info.ch_names(:); hdr.nChans = info.nchan; hdr.Fs = info.sfreq; % add a gradiometer structure for forward and inverse modelling try [grad, elec] = mne2grad(info, strcmp(coordsys, 'dewar'), coilaccuracy); if ~isempty(grad) hdr.grad = grad; end if ~isempty(elec) hdr.elec = elec; end catch disp(lasterr); end iscontinuous = 0; isepoched = 0; isaverage = 0; if isempty(fiff_find_evoked(filename)) % true if file contains no evoked responses try epochs = fiff_read_epochs(filename); isepoched = 1; catch % the "catch me" syntax is broken on MATLAB74, this fixes it me = lasterror; if strcmp(me.identifier, 'MNE:fiff_read_events') iscontinuous = 1; else rethrow(me) end end else isaverage = 1; end if iscontinuous try % we only use 1 input argument here to allow backward % compatibility up to MNE 2.6.x: raw = fiff_setup_read_raw(filename); catch % the "catch me" syntax is broken on MATLAB74, this fixes it me = lasterror; % there is an error - we try to use MNE 2.7.x (if present) to % determine if the cause is maxshielding: try allow_maxshield = true; raw = fiff_setup_read_raw(filename,allow_maxshield); catch % unknown problem, or MNE version 2.6.x or less: rethrow(me); end % no error message from fiff_setup_read_raw? Then maxshield % was applied, but maxfilter wasn't, so return this error: if istrue(checkmaxfilter) error('Maxshield data should be corrected using Maxfilter prior to importing in FieldTrip.'); else ft_warning('Maxshield data should be corrected using Maxfilter prior to importing in FieldTrip.'); end end hdr.nSamples = raw.last_samp - raw.first_samp + 1; % number of samples per trial hdr.nSamplesPre = 0; % otherwise conflicts will occur in read_data hdr.nTrials = 1; info.raw = raw; % keep all the details elseif isepoched hdr.nSamples = length(epochs.times); hdr.nSamplesPre = sum(epochs.times < 0); hdr.nTrials = size(epochs.data, 1); info.epochs = epochs; % this is used by read_data to get the actual data, i.e. to prevent re-reading elseif isaverage try, evoked_data = fiff_read_evoked_all(filename); vartriallength = any(diff([evoked_data.evoked.first])) || any(diff([evoked_data.evoked.last])); if vartriallength % there are trials averages with variable durations in the file warning('EVOKED FILE with VARIABLE TRIAL LENGTH! - check data have been processed accurately'); hdr.nSamples = 0; for i=1:length(evoked_data.evoked) hdr.nSamples = hdr.nSamples + size(evoked_data.evoked(i).epochs, 2); end % represent it as a continuous file with a single trial % all trial average details will be available through read_event hdr.nSamplesPre = 0; hdr.nTrials = 1; info.evoked = evoked_data.evoked; % this is used by read_data to get the actual data, i.e. to prevent re-reading info.info = evoked_data.info; % keep all the details info.vartriallength = 1; else % represent it as a file with multiple trials, each trial has the same length % all trial average details will be available through read_event hdr.nSamples = evoked_data.evoked(1).last - evoked_data.evoked(1).first + 1; hdr.nSamplesPre = -evoked_data.evoked(1).first; % represented as negative number in fif file hdr.nTrials = length(evoked_data.evoked); info.evoked = evoked_data.evoked; % this is used by read_data to get the actual data, i.e. to prevent re-reading info.info = evoked_data.info; % keep all the details info.vartriallength = 0; end catch % this happens if fiff_read_evoked_all cannot find evoked % responses, in which case it errors due to not assigning the % output variable "data" warning('%s does not contain data', filename); hdr.nSamples = 0; hdr.nSamplesPre = 0; hdr.nTrials = 0; end end % remember the original header details hdr.orig = info; % these are useful to know in ft_read_event and ft_read_data hdr.orig.isaverage = isaverage; hdr.orig.iscontinuous = iscontinuous; hdr.orig.isepoched = isepoched; case 'neuromag_mex' % check that the required low-level toolbox is available ft_hastoolbox('meg-pd', 1); rawdata('any',filename); rawdata('goto', 0); megmodel('head',[0 0 0],filename); % get the available information from the fif file [orig.rawdata.range,orig.rawdata.calib] = rawdata('range'); [orig.rawdata.sf] = rawdata('sf'); [orig.rawdata.samples] = rawdata('samples'); [orig.chaninfo.N,orig.chaninfo.S,orig.chaninfo.T] = chaninfo; % Numbers, names & places [orig.chaninfo.TY,orig.chaninfo.NA] = chaninfo('type'); % Coil type [orig.chaninfo.NO] = chaninfo('noise'); % Default noise level [orig.channames.NA,orig.channames.KI,orig.channames.NU] = channames(filename); % names, kind, logical numbers % read a single trial to determine the data size [buf, status] = rawdata('next'); rawdata('close'); % This is to solve a problem reported by Doug Davidson: The problem % is that rawdata('samples') is not returning the number of samples % correctly. It appears that the example script rawchannels in meg-pd % might work, however, so I want to use rawchannels to read in one % channel of data in order to get the number of samples in the file: if orig.rawdata.samples<0 tmpchannel = 1; tmpvar = rawchannels(filename,tmpchannel); [orig.rawdata.samples] = size(tmpvar,2); clear tmpvar tmpchannel; end % convert to FieldTrip format header hdr.label = orig.channames.NA; hdr.Fs = orig.rawdata.sf; hdr.nSamplesPre = 0; % I don't know how to get this out of the file hdr.nChans = size(buf,1); hdr.nSamples = size(buf,2); % number of samples per trial hdr.nTrials = orig.rawdata.samples ./ hdr.nSamples; % add a gradiometer structure for forward and inverse modelling hdr.grad = fif2grad(filename); % remember the original header details hdr.orig = orig; case 'neuroprax_eeg' orig = np_readfileinfo(filename); hdr.Fs = orig.fa; hdr.nChans = orig.K; hdr.nSamples = orig.N; hdr.nSamplesPre = 0; % continuous hdr.nTrials = 1; % continuous hdr.label = orig.channels(:); hdr.unit = orig.units(:); % remember the original header details hdr.orig = orig; case 'neuroscope_bin' [p,f,e] = fileparts(filename); headerfile = fullfile(p,[f,'.xml']); hdr = ft_read_header(headerfile, 'headerformat', 'neuroscope_xml'); case 'neuroscope_ds' listing = dir(filename); filenames = {listing.name}'; headerfile = filenames{~cellfun('isempty',strfind(filenames,'.xml'))}; hdr = ft_read_header(headerfile, 'headerformat', 'neuroscope_xml'); case 'neuroscope_xml' ft_hastoolbox('neuroscope', 1); ft_hastoolbox('gifti', 1); % this pertains to generic header file, and the other neuroscope % formats will recurse into this one [p,f,e] = fileparts(filename); if isempty(p), p = pwd; end listing = dir(p); filenames = {listing.name}'; lfpfile_idx = find(~cellfun('isempty',strfind(filenames,'.eeg'))); rawfile_idx = find(~cellfun('isempty',strfind(filenames,'.dat'))); if ~isempty(lfpfile_idx) % FIXME this assumes only 1 such file, or at least it only takes the % first one. lfpfile = filenames{lfpfile_idx(1)}; end if ~isempty(rawfile_idx) rawfile = filenames{rawfile_idx(1)}; end params = LoadParameters(filename); hdr = []; hdr.nChans = params.nChannels; hdr.nTrials = 1; % is it always continuous? FIXME hdr.nSamplesPre = 0; if ~isempty(lfpfile) % use the sampling of the lfp-file to be leading hdr.Fs = params.rates.lfp; hdr.nSamples = listing(strcmp(filenames,lfpfile)).bytes./(hdr.nChans*params.nBits/8); hdr.TimeStampPerSample = params.rates.wideband./params.rates.lfp; else % use the sampling of the raw-file to be leading hdr.Fs = params.rates.wideband; hdr.nSamples = listing(strcmp(filenames,rawfile)).bytes./(hdr.nChans*params.nBits/8); hdr.TimeStampPerSample = 1; end hdr.orig = params; hdr.label = cell(hdr.nChans,1); for k = 1:hdr.nChans hdr.label{k} = ['chan',num2str(k,'%0.3d')]; end case 'neurosim_evolution' hdr = read_neurosim_evolution(filename); case {'neurosim_ds' 'neurosim_signals'} hdr = read_neurosim_signals(filename); case 'neurosim_spikes' headerOnly = true; hdr = read_neurosim_spikes(filename, headerOnly); case 'nihonkohden_m00' hdr = read_nihonkohden_hdr(filename); case 'nimh_cortex' cortex = read_nimh_cortex(filename, 'epp', 'no', 'eog', 'no'); % look at the first trial to determine whether it contains data in the EPP and EOG channels trial1 = read_nimh_cortex(filename, 'epp', 'yes', 'eog', 'yes', 'begtrial', 1, 'endtrial', 1); hasepp = ~isempty(trial1.epp); haseog = ~isempty(trial1.eog); if hasepp warning('EPP channels are not yet supported'); end % at the moment only the EOG channels are supported here if haseog hdr.label = {'EOGx' 'EOGy'}; hdr.nChans = 2; else hdr.label = {}; hdr.nChans = 0; end hdr.nTrials = length(cortex); hdr.nSamples = inf; hdr.nSamplesPre = 0; hdr.orig.trial = cortex; hdr.orig.hasepp = hasepp; hdr.orig.haseog = haseog; case 'ns_avg' orig = read_ns_hdr(filename); % do some reformatting/renaming of the header items hdr.Fs = orig.rate; hdr.nSamples = orig.npnt; hdr.nSamplesPre = round(-orig.rate*orig.xmin/1000); hdr.nChans = orig.nchan; hdr.label = orig.label(:); hdr.nTrials = 1; % the number of trials in this datafile is only one, i.e. the average % remember the original header details hdr.orig = orig; case {'ns_cnt' 'ns_cnt16', 'ns_cnt32'} ft_hastoolbox('eeglab', 1); if strcmp(headerformat, 'ns_cnt') orig = loadcnt(filename); % let loadcnt figure it out elseif strcmp(headerformat, 'ns_cnt16') orig = loadcnt(filename, 'dataformat', 'int16'); elseif strcmp(headerformat, 'ns_cnt32') orig = loadcnt(filename, 'dataformat', 'int32'); end % do some reformatting/renaming of the header items hdr.Fs = orig.header.rate; hdr.nChans = orig.header.nchannels; hdr.nSamples = orig.ldnsamples; hdr.nSamplesPre = 0; hdr.nTrials = 1; for i=1:hdr.nChans hdr.label{i} = deblank(orig.electloc(i).lab); end % remember the original header details hdr.orig = orig; case 'ns_eeg' orig = read_ns_hdr(filename); % do some reformatting/renaming of the header items hdr.label = orig.label; hdr.Fs = orig.rate; hdr.nSamples = orig.npnt; hdr.nSamplesPre = round(-orig.rate*orig.xmin/1000); hdr.nChans = orig.nchan; hdr.nTrials = orig.nsweeps; % remember the original header details hdr.orig = orig; case 'nmc_archive_k' hdr = read_nmc_archive_k_hdr(filename); case 'neuroshare' % NOTE: still under development % check that the required neuroshare toolbox is available ft_hastoolbox('neuroshare', 1); tmp = read_neuroshare(filename); hdr.Fs = tmp.hdr.analoginfo(end).SampleRate; % take the sampling freq from the last analog channel (assuming this is the same for all chans) hdr.nChans = length(tmp.list.analog(tmp.analog.contcount~=0)); % get the analog channels, only the ones that are not empty hdr.nSamples = max([tmp.hdr.entityinfo(tmp.list.analog).ItemCount]); % take the number of samples from the longest channel hdr.nSamplesPre = 0; % continuous data hdr.nTrials = 1; % continuous data hdr.label = {tmp.hdr.entityinfo(tmp.list.analog(tmp.analog.contcount~=0)).EntityLabel}; %%% contains non-unique chans? hdr.orig = tmp; % remember the original header case 'oxy3' ft_hastoolbox('artinis', 1); hdr = read_artinis_oxy3(filename); case 'plexon_ds' hdr = read_plexon_ds(filename); case 'plexon_ddt' orig = read_plexon_ddt(filename); hdr.nChans = orig.NChannels; hdr.Fs = orig.Freq; hdr.nSamples = orig.NSamples; hdr.nSamplesPre = 0; % continuous hdr.nTrials = 1; % continuous hdr.label = cell(1,hdr.nChans); % give this warning only once warning('creating fake channel names'); for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end % also remember the original header hdr.orig = orig; case {'read_nex_data'} % this is an alternative reader for nex files orig = read_nex_header(filename); % assign the obligatory items to the output FCDC header numsmp = cell2mat({orig.varheader.numsmp}); adindx = find(cell2mat({orig.varheader.typ})==5); if isempty(adindx) error('file does not contain continuous channels'); end hdr.nChans = length(orig.varheader); hdr.Fs = orig.varheader(adindx(1)).wfrequency; % take the sampling frequency from the first A/D channel hdr.nSamples = max(numsmp(adindx)); % take the number of samples from the longest A/D channel hdr.nTrials = 1; % it can always be interpreted as continuous data hdr.nSamplesPre = 0; % and therefore it is not trial based for i=1:hdr.nChans hdr.label{i} = deblank(char(orig.varheader(i).nam)); end hdr.label = hdr.label(:); % also remember the original header details hdr.orig = orig; case {'plexon_nex' 'read_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 'smi_txt' smi = read_smi_txt(filename); hdr.nChans = size(smi.dat,1); hdr.nSamples = size(smi.dat,2); hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.FirstTimeStamp = smi.trigger(1,1).timestamp; % if the header contains the sampling rate use it and if not, compute % it from scratch. If computed, sampling rate might have numerical % issues due to tolerance (the reason that I write the two options) if isfield(smi,'Fs') && ~isempty(smi.Fs); hdr.Fs = smi.Fs; hdr.TimeStampPerSample = 1000./hdr.Fs; else hdr.TimeStampPerSample = mean(diff(smi.dat(1,:))); hdr.Fs = 1000/hdr.TimeStampPerSample; % these timestamps are in miliseconds end if hdr.nChans ~= size(smi.label,1); error('data and header have different number of channels'); else hdr.label = smi.label; end % remember the original header details hdr.orig.header = smi.header; % remember all header and data details upon request if cache hdr.orig = smi; end % add channel units when possible. for i=1:hdr.nChans; chanunit = regexp(hdr.label{i,1},'(?<=\[).+?(?=\])','match'); if ~isempty(chanunit) hdr.chanunit{i,1} = chanunit{1}; hdr.chantype{i,1} = 'eyetracker'; else hdr.chanunit{i,1} = 'unknown'; hdr.chantype{i,1} = 'unknown'; end end case 'tmsi_poly5' orig = read_tmsi_poly5(filename); % the header contains all channels twice (for the low and high data word) % it seems that the file format was designed for 16 bit, and only later extended to 32 bit hdr = []; hdr.nChans = orig.header.NumberOfSignals/2; hdr.Fs = orig.header.FS; hdr.nSamples = orig.header.NumberSampleBlocks * orig.header.SamplePeriodsPerBlock; hdr.nSamplesPre = 0; hdr.nTrials = 1; % continuous for i=2:2:orig.header.NumberOfSignals % remove the '(Lo) ' and the '(Hi) ' section hdr.label{i/2} = strtrim(orig.description(i).SignalName(6:end)'); end % determine the EEG channels iseeg = true(size(hdr.label)); iseeg = iseeg & cellfun(@isempty, regexp(hdr.label, 'BIP.*')); iseeg = iseeg & cellfun(@isempty, regexp(hdr.label, 'AUX.*')); iseeg = iseeg & cellfun(@isempty, regexp(hdr.label, 'Digi.*')); iseeg = iseeg & cellfun(@isempty, regexp(hdr.label, 'Saw.*')); iseeg = iseeg & cellfun(@isempty, regexp(hdr.label, 'Bit.*')); istrg = ~cellfun(@isempty, regexp(hdr.label, 'Digi.*')); hdr.chanunit = cell(size(hdr.label)); hdr.chantype = cell(size(hdr.label)); hdr.chanunit(:) = {'unknown'}; hdr.chantype(:) = {'unknown'}; hdr.chanunit(iseeg) = {'uV'}; hdr.chantype(iseeg) = {'eeg'}; hdr.chantype(istrg) = {'trigger'}; % remember the original header details hdr.orig = orig; case 'tobii_tsv' tsv = read_tobii_tsv(filename); % keyboard % remember the original header details hdr.orig = tsv; case {'tdt_tsq', 'tdt_tev'} % FIXME the code below is not yet functional, it requires more input from the ESI in Frankfurt % tsq = read_tdt_tsq(headerfile); % k = 0; % chan = unique([tsq.channel]); % % loop over the physical channels % for i=1:length(chan) % chansel = [tsq.channel]==chan(i); % code = unique({tsq(chansel).code}); % % loop over the logical channels % for j=1:length(code) % codesel = false(size(tsq)); % for k=1:numel(codesel) % codesel(k) = identical(tsq(k).code, code{j}); % end % % find the first instance of this logical channel % this = find(chansel(:) & codesel(:), 1); % % add it to the list of channels % k = k + 1; % frequency(k) = tsq(this).frequency; % label{k} = [char(typecast(tsq(this).code, 'uint8')) num2str(tsq(this).channel)]; % tsqorig(k) = tsq(this); % end % end error('not yet implemented'); case {'yokogawa_ave', 'yokogawa_con', 'yokogawa_raw', 'yokogawa_mrk'} % header can be read with two toolboxes: Yokogawa MEG Reader and Yokogawa MEG160 (old inofficial toolbox) % newest toolbox takes precedence. if ft_hastoolbox('yokogawa_meg_reader', 3); % stay silent if it cannot be added hdr = read_yokogawa_header_new(filename); % add a gradiometer structure for forward and inverse modelling hdr.grad = yokogawa2grad_new(hdr); else ft_hastoolbox('yokogawa', 1); % try it with the old version of the toolbox hdr = read_yokogawa_header(filename); % add a gradiometer structure for forward and inverse modelling hdr.grad = yokogawa2grad(hdr); end case 'riff_wave' [y, fs, nbits, opts] = wavread(filename, 1); % read one sample siz = wavread(filename,'size'); hdr.Fs = fs; hdr.nChans = siz(2); hdr.nSamples = siz(1); hdr.nSamplesPre = 0; hdr.nTrials = 1; [p, f, x] = fileparts(filename); if hdr.nChans>1 for i=1:hdr.nChans % use the file name and channel number hdr.label{i,1} = sprintf('%s channel %d', f, i); hdr.chantype{i,1} = 'audio'; end else hdr.label{1,1} = f; hdr.chantype{1,1} = 'audio'; end % remember the details hdr.orig = opts; case 'videomeg_aud' hdr = read_videomeg_aud(filename); case 'videomeg_vid' hdr = read_videomeg_vid(filename); checkUniqueLabels = false; otherwise if strcmp(fallback, 'biosig') && ft_hastoolbox('BIOSIG', 1) hdr = read_biosig_header(filename); else error('unsupported header format "%s"', headerformat); end end % switch headerformat % Sometimes, the not all labels are correctly filled in by low-level reading % functions. See for example bug #1572. % First, make sure that there are enough (potentially empty) labels: if numel(hdr.label) < hdr.nChans warning('low-level reading function did not supply enough channel labels'); hdr.label{hdr.nChans} = []; end % Now, replace all empty labels with new name: if any(cellfun(@isempty, hdr.label)) warning('channel labels should not be empty, creating unique labels'); hdr.label = fix_empty(hdr.label); end if checkUniqueLabels if length(hdr.label)~=length(unique(hdr.label)) % all channels must have unique names warning('all channels must have unique labels, creating unique labels'); megflag = ft_chantype(hdr, 'meg'); eegflag = ft_chantype(hdr, 'eeg'); for i=1:hdr.nChans sel = find(strcmp(hdr.label{i}, hdr.label)); if length(sel)>1 % there is no need to rename the first instance % can be particularly disruptive when part of standard MEG % or EEG channel set, so should be avoided if any(megflag(sel)) sel = setdiff(sel, sel(find(megflag(sel), 1))); elseif any(eegflag(sel)) sel = setdiff(sel, sel(find(eegflag(sel), 1))); else sel = sel(2:end); end for j=1:length(sel) hdr.label{sel(j)} = sprintf('%s-%d', hdr.label{sel(j)}, j); end end end end end % as of November 2011, the header is supposed to include the channel type (see FT_CHANTYPE, % e.g. meggrad, megref, eeg) and the units of each channel (see FT_CHANUNIT, e.g. uV, fT) if ~isfield(hdr, 'chantype') && checkUniqueLabels % use a helper function which has some built in intelligence hdr.chantype = ft_chantype(hdr); end % for if ~isfield(hdr, 'chanunit') && checkUniqueLabels % use a helper function which has some built in intelligence hdr.chanunit = ft_chanunit(hdr); end % for % ensure that the output grad is according to the latest definition if isfield(hdr, 'grad') hdr.grad = ft_datatype_sens(hdr.grad); end % ensure that the output elec is according to the latest definition if isfield(hdr, 'elec') hdr.elec = ft_datatype_sens(hdr.elec); end % ensure that these are column arrays hdr.label = hdr.label(:); if isfield(hdr, 'chantype'), hdr.chantype = hdr.chantype(:); end if isfield(hdr, 'chanunit'), hdr.chanunit = hdr.chanunit(:); 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 inflated % compressed file has been unzipped on the fly, clean up if strcmp(headerformat, 'brainvision_vhdr') % don't delete the header file yet, ft_read_data might still need it % the files will be cleaned up by ft_read_data else delete(filename); end end if cache && exist(headerfile, 'file') % put the header in the cache cacheheader = hdr; % update the header details (including time stampp, size and name) cacheheader.details = dir(headerfile); % fprintf('added header to cache\n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to determine the file size in bytes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [siz] = filesize(filename) l = dir(filename); if l.isdir error('"%s" is not a file', filename); end siz = l.bytes; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to determine the file size in bytes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [hdr] = recursive_read_header(filename) [p, f, x] = fileparts(filename); ls = dir(filename); ls = ls(~strcmp({ls.name}, '.')); % exclude this directory ls = ls(~strcmp({ls.name}, '..')); % exclude parent directory for i=1:length(ls) % make sure that the directory listing includes the complete path ls(i).name = fullfile(filename, ls(i).name); end lst = {ls.name}; hdr = cell(size(lst)); sel = zeros(size(lst)); for i=1:length(lst) % read the header of each individual file try thishdr = ft_read_header(lst{i}); if isstruct(thishdr) thishdr.filename = lst{i}; end catch thishdr = []; warning(lasterr); fprintf('while reading %s\n\n', lst{i}); end if ~isempty(thishdr) hdr{i} = thishdr; sel(i) = true; else sel(i) = false; end end sel = logical(sel(:)); hdr = hdr(sel); tmp = {}; for i=1:length(hdr) if isstruct(hdr{i}) tmp = cat(1, tmp, hdr(i)); elseif iscell(hdr{i}) tmp = cat(1, tmp, hdr{i}{:}); end end hdr = tmp; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to fill in empty labels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function labels = fix_empty(labels) for i = find(cellfun(@isempty, {labels{:}})); labels{i} = sprintf('%d', i); end
github
lcnbeapp/beapp-master
ft_read_mri.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/ft_read_mri.m
16,412
utf_8
5f31e0b2de7b0f1c54df82c39a9d8b73
function [mri] = ft_read_mri(filename, varargin) % FT_READ_MRI reads anatomical and functional MRI data from different % file formats. The output data is structured in such a way that it is % comparable to a FieldTrip source reconstruction. % % Use as % [mri] = ft_read_mri(filename) % % Additional options should be specified in key-value pairs and can be % 'dataformat' = string specifying the file format, determining the low- % level reading routine to be used. If no format is given, % it is determined automatically from the file. % The following formats can be specified: % 'afni_head'/'afni_brik' uses afni % 'analyze_img'/'analyze_hdr' uses spm % 'analyze_old' uses Darren Webber's code % 'asa_mri' % 'ctf_mri' % 'ctf_mri4' % 'ctf_svl' % 'dicom' uses freesurfer % 'dicom_old' uses own code % 'freesurfer_mgh' uses freesurfer % 'freesurfer_mgz' uses freesurfer % 'minc' uses spm (<= version spm5) % 'nifti' uses freesurfer % 'nifti_fsl' uses freesurfer % 'nifti_spm' uses spm % 'neuromag_fif' uses mne toolbox % 'neuromag_fif_old' uses meg-pd toolbox % 'yokogawa_mri' % 'matlab' assumes a MATLAB *.mat file containing a mri structure % according FieldTrip standards % % The following MRI file formats are supported % CTF - VSM MedTech (*.svl, *.mri version 4 and 5) % NIFTi (*.nii) and zipped NIFTi (*.nii.gz) % Analyze (*.img, *.hdr) % DICOM (*.dcm, *.ima) % AFNI (*.head, *.brik) % FreeSurfer (*.mgz, *.mgh) % MINC (*.mnc) % Neuromag - Elekta (*.fif) % ANT - Advanced Neuro Technology (*.mri) % Yokogawa (*.mrk, incomplete) % % If you have a series of DICOM files, please provide the name of any of the files % in the series (e.g. the first one). The other files will be found automatically. % % The output MRI may have a homogenous transformation matrix that converts % the coordinates of each voxel (in xgrid/ygrid/zgrid) into head % coordinates. % % See also FT_WRITE_MRI, FT_READ_DATA, FT_READ_HEADER, FT_READ_EVENT % Copyright (C) 2008-2013, Robert Oostenveld & Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % optionally get the data from the URL and make a temporary local copy filename = fetch_url(filename); % get the options dataformat = ft_getopt(varargin, 'dataformat'); % the following is added for backward compatibility of using 'format' rather than 'dataformat' format = ft_getopt(varargin, 'format'); if ~isempty(format) warning('the option ''format'' will be deprecated soon, please use ''dataformat'' instead'); if isempty(dataformat) dataformat = format; end end if isempty(dataformat) % only do the autodetection if the format was not specified dataformat = ft_filetype(filename); end if strcmp(dataformat, 'compressed') % the file is compressed, unzip on the fly inflated = true; filename = inflate_file(filename); dataformat = ft_filetype(filename); else inflated = false; end % test whether the file exists if ~exist(filename, 'file') error('file ''%s'' does not exist', filename); end % test for the presence of some external functions from other toolboxes hasspm2 = ft_hastoolbox('spm2'); % see http://www.fil.ion.ucl.ac.uk/spm/ hasspm5 = ft_hastoolbox('spm5'); % see http://www.fil.ion.ucl.ac.uk/spm/ hasspm8 = ft_hastoolbox('spm8'); % see http://www.fil.ion.ucl.ac.uk/spm/ hasspm12 = ft_hastoolbox('spm12'); % see http://www.fil.ion.ucl.ac.uk/spm/ switch dataformat case 'ctf_mri' [img, hdr] = read_ctf_mri(filename); transform = hdr.transformMRI2Head; coordsys = 'ctf'; case 'ctf_mri4' [img, hdr] = read_ctf_mri4(filename); transform = hdr.transformMRI2Head; coordsys = 'ctf'; case 'ctf_svl' [img, hdr] = read_ctf_svl(filename); transform = hdr.transform; case 'asa_mri' [img, seg, hdr] = read_asa_mri(filename); transform = hdr.transformMRI2Head; if isempty(seg) % in case seg exists it will be added to the output clear seg end case 'minc' if ~(hasspm2 || hasspm5) fprintf('the SPM2 or SPM5 toolbox is required to read *.mnc files\n'); ft_hastoolbox('spm2',1); end % use the functions from SPM hdr = spm_vol_minc(filename); img = spm_read_vols(hdr); transform = hdr.mat; case 'nifti_spm' if ~(hasspm5 || hasspm8 || hasspm12) fprintf('the SPM5 or newer toolbox is required to read *.nii files\n'); ft_hastoolbox('spm8', 1); end % use the functions from SPM hdr = spm_vol_nifti(filename); img = spm_read_vols(hdr); transform = hdr.mat; case {'analyze_img' 'analyze_hdr'} if ~(hasspm8) fprintf('the SPM8 toolbox is required to read analyze files\n'); ft_hastoolbox('spm8', 1); end % use the image file instead of the header filename((end-2):end) = 'img'; % use the functions from SPM to read the Analyze MRI hdr = spm_vol(filename); img = spm_read_vols(hdr); transform = hdr.mat; case 'analyze_old' % use the functions from Darren Weber's mri_toolbox to read the Analyze MRI ft_hastoolbox('mri', 1); % from Darren Weber, see http://eeg.sourceforge.net/ avw = avw_img_read(filename, 0); % returned volume is LAS* img = avw.img; hdr = avw.hdr; % The default Analyze orientation is axial unflipped (LAS*), which means % that the resulting volume is according to the radiological convention. % Most other fMRI and EEG/MEG software (except Mayo/Analyze) uses % neurological conventions and a right-handed coordinate system, hence % the first axis of the 3D volume (right-left) should be flipped to make % the coordinate system comparable to SPM warning('flipping 1st dimension (L-R) to obtain volume in neurological convention'); img = flipdim(img, 1); transform = diag(hdr.dime.pixdim(2:4)); transform(4,4) = 1; case {'afni_brik' 'afni_head'} % needs afni ft_hastoolbox('afni', 1); % see http://afni.nimh.nih.gov/ [err, img, hdr, ErrMessage] = BrikLoad(filename); if err error('could not read AFNI file'); end % FIXME: this should be checked, but I only have a single BRIK file % construct the homogenous transformation matrix that defines the axes warning('homogenous transformation might be incorrect for AFNI file'); transform = eye(4); transform(1:3,4) = hdr.ORIGIN(:); transform(1,1) = hdr.DELTA(1); transform(2,2) = hdr.DELTA(2); transform(3,3) = hdr.DELTA(3); % FIXME: I am not sure about the "RAI" image orientation img = flipdim(img,1); img = flipdim(img,2); dim = size(img); transform(1,4) = -dim(1) - transform(1,4); transform(2,4) = -dim(2) - transform(2,4); case 'neuromag_fif' % needs mne toolbox ft_hastoolbox('mne', 1); % use the mne functions to read the Neuromag MRI hdr = fiff_read_mri(filename); img_t = cat(3, hdr.slices.data); img = permute(img_t,[2 1 3]); hdr.slices = rmfield(hdr.slices, 'data'); % remove the image data to save memory % information below is from MNE - fiff_define_constants.m % coordinate system 4 - is the MEG head coordinate system (fiducials) % coordinate system 5 - is the MRI coordinate system % coordinate system 2001 - MRI voxel coordinates % coordinate system 2002 - Surface RAS coordinates (is mainly vertical % shift, no rotation to 2001) % MEG sensor positions come in system 4 % MRI comes in system 2001 transform = eye(4); if isfield(hdr, 'trans') && issubfield(hdr.trans, 'trans') if (hdr.trans.from == 4) && (hdr.trans.to == 5) transform = hdr.trans.trans; else warning('W: trans does not transform from 4 to 5.'); warning('W: Please check the MRI fif-file'); end else warning('W: trans structure is not defined.'); warning('W: Maybe coregistration is missing?'); end if isfield(hdr, 'voxel_trans') && issubfield(hdr.voxel_trans, 'trans') % centers the coordinate system % and switches from mm to m if (hdr.voxel_trans.from == 2001) && (hdr.voxel_trans.to == 5) % matlab_shift compensates for the different index conventions % between C and matlab % the lines below is old code (prior to Jan 3, 2013) and only works with % 1 mm resolution MRIs %matlab_shift = [ 0 0 0 0.001; 0 0 0 -0.001; 0 0 0 0.001; 0 0 0 0]; % transform transforms from 2001 to 5 and further to 4 %transform = transform\(hdr.voxel_trans.trans+matlab_shift); % the lines below should work with arbitrary resolution matlab_shift = eye(4); matlab_shift(1:3,4) = [-1,-1,-1]; transform = transform\(hdr.voxel_trans.trans * matlab_shift); coordsys = 'neuromag'; mri.unit = 'm'; else warning('W: voxel_trans does not transform from 2001 to 5.'); warning('W: Please check the MRI fif-file'); end else warning('W: voxel_trans structure is not defined.'); warning('W: Please check the MRI fif-file'); end case 'neuromag_fif_old' % needs meg_pd toolbox ft_hastoolbox('meg-pd', 1); % use the meg_pd functions to read the Neuromag MRI [img,coords] = loadmri(filename); dev = loadtrans(filename,'MRI','HEAD'); transform = dev*coords; hdr.coords = coords; hdr.dev = dev; case 'dicom' % this seems to return a right-handed volume with the transformation % matrix stored in the file headers. % needs the freesurfer toolbox ft_hastoolbox('freesurfer', 1); [dcmdir,junk1,junk2] = fileparts(filename); if isempty(dcmdir), dcmdir = '.'; end [img,transform,hdr,mr_params] = load_dicom_series(dcmdir,dcmdir,filename); transform = vox2ras_0to1(transform); case 'dicom_old' % this does not necessarily return a right-handed volume and only a % transformation-matrix with the voxel size % this uses the Image processing toolbox % the DICOM file probably represents a stack of slices, possibly even multiple volumes orig = dicominfo(filename); dim(1) = orig.Rows; dim(2) = orig.Columns; [p, f] = fileparts(filename); % this works for the Siemens scanners at the FCDC tok = tokenize(f, '.'); for i=5:length(tok) tok{i} = '*'; end filename = sprintf('%s.', tok{:}); % reconstruct the filename with wildcards and '.' between the segments filename = filename(1:end-1); % remove the last '.' dirlist = dir(fullfile(p, filename)); dirlist = {dirlist.name}; if isempty(dirlist) % this is for the Philips data acquired at KI warning('could not determine list of dicom files, trying with *.dcm'); dirlist = dir(fullfile(p, '*.dcm')); dirlist = {dirlist.name}; end if isempty(dirlist) warning('could not determine list of dicom files, trying with *.ima'); dirlist = dir(fullfile(p, '*.ima')); dirlist = {dirlist.name}; end if length(dirlist)==1 % try something else to get a list of all the slices dirlist = dir(fullfile(p, '*')); dirlist = {dirlist(~[dirlist.isdir]).name}; end keep = false(1, length(dirlist)); for i=1:length(dirlist) filename = char(fullfile(p, dirlist{i})); if ~strcmp(dataformat, 'dicom_old') keep(i) = false; fprintf('skipping ''%s'' because of incorrect filetype\n', filename); end % read the header information info = dicominfo(filename); if info.SeriesNumber~=orig.SeriesNumber keep(i) = false; fprintf('skipping ''%s'' because of different SeriesNumber\n', filename); else keep(i) = true; hdr(i) = info; end end % remove the files that were skipped hdr = hdr(keep); dirlist = dirlist(keep); % pre-allocate enough space for the subsequent slices dim(3) = length(dirlist); img = zeros(dim(1), dim(2), dim(3)); for i=1:length(dirlist) filename = char(fullfile(p, dirlist{i})); fprintf('reading image data from ''%s''\n', filename); img(:,:,i) = dicomread(hdr(i)); end % reorder the slices [z, indx] = sort(cell2mat({hdr.SliceLocation})); hdr = hdr(indx); img = img(:,:,indx); try % construct a homgeneous transformation matrix that performs the scaling from voxels to mm dx = hdr(1).PixelSpacing(1); dy = hdr(1).PixelSpacing(2); dz = hdr(2).SliceLocation - hdr(1).SliceLocation; transform = eye(4); transform(1,1) = dx; transform(2,2) = dy; transform(3,3) = dz; end case {'nifti', 'freesurfer_mgz', 'freesurfer_mgh', 'nifti_fsl'} if strcmp(dataformat, 'freesurfer_mgz') && ispc error('Compressed .mgz files cannot be read on a PC'); end ft_hastoolbox('freesurfer', 1); tmp = MRIread(filename); ndims = numel(size(tmp.vol)); if ndims==3 img = permute(tmp.vol, [2 1 3]); %FIXME although this is probably correct %see the help of MRIread, anecdotally columns and rows seem to need a swap %in order to match the transform matrix (alternatively a row switch of the %latter can be done) elseif ndims==4 img = permute(tmp.vol, [2 1 3 4]); end hdr = rmfield(tmp, 'vol'); transform = tmp.vox2ras1; case 'yokogawa_mri' ft_hastoolbox('yokogawa', 1); fid = fopen(filename, 'rb'); mri_info = GetMeg160MriInfoM(fid); patient_info = GetMeg160PatientInfoFromMriFileM(fid); [data_style, model, marker, image_parameter, normalize, besa_fiducial_point] = GetMeg160MriFileHeaderInfoM(fid); fclose(fid); % gather all meta-information hdr.mri_info = mri_info; hdr.patient_info = patient_info; hdr.data_style = data_style; hdr.model = model; hdr.marker = marker; hdr.image_parameter = image_parameter; hdr.normalize = normalize; hdr.besa_fiducial_point = besa_fiducial_point; error('FIXME yokogawa_mri implementation is incomplete'); case 'matlab' mri = loadvar(filename, 'mri'); otherwise error(sprintf('unrecognized filetype ''%s'' for ''%s''', dataformat, filename)); end if exist('img', 'var') % set up the axes of the volume in voxel coordinates nx = size(img,1); ny = size(img,2); nz = size(img,3); mri.dim = [nx ny nz]; % store the anatomical data mri.anatomy = img; end if exist('seg', 'var') % store the segmented data mri.seg = seg; end if exist('hdr', 'var') % store the header with all file format specific details mri.hdr = hdr; end try % store the homogenous transformation matrix if present mri.transform = transform; end try % try to determine the units of the coordinate system mri = ft_convert_units(mri); end try % try to add a descriptive label for the coordinate system mri.coordsys = coordsys; end if inflated % compressed file has been unzipped on the fly, clean up delete(filename); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function value = loadvar(filename, varname) var = whos('-file', filename); if length(var)==1 filecontent = load(filename); % read the one variable in the file, regardless of how it is called value = filecontent.(var.name); clear filecontent else filecontent = load(filename, varname); value = filecontent.(varname); % read the variable named according to the input specification clear filecontent end
github
lcnbeapp/beapp-master
ft_filetype.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/ft_filetype.m
66,474
utf_8
5b944ec5e2bf4cdb91d29ed2c5644618
function [type] = ft_filetype(filename, desired, varargin) % FT_FILETYPE determines the filetype of many EEG/MEG/MRI data files by % looking at the name, extension and optionally (part of) its contents. % It tries to determine the global type of file (which usually % corresponds to the manufacturer, the recording system or to the % software used to create the file) and the particular subtype (e.g. % continuous, average). % % Use as % type = ft_filetype(filename) % type = ft_filetype(dirname) % % This gives you a descriptive string with the data type, and can be % used in a switch-statement. The descriptive string that is returned % usually is something like 'XXX_YYY'/ where XXX refers to the % manufacturer and YYY to the type of the data. % % Alternatively, use as % flag = ft_filetype(filename, type) % flag = ft_filetype(dirname, type) % This gives you a boolean flag (0 or 1) indicating whether the file % is of the desired type, and can be used to check whether the % user-supplied file is what your subsequent code expects. % % Alternatively, use as % flag = ft_filetype(dirlist, type) % where the dirlist contains a list of files contained within one % directory. This gives you a boolean vector indicating for each file % whether it is of the desired type. % % Most filetypes of the following manufacturers and/or software programs are recognized % - 4D/BTi % - AFNI % - ASA % - Analyse % - Analyze/SPM % - BESA % - BrainSuite % - BrainVisa % - BrainVision % - Curry % - Dataq % - EDF % - EEProbe % - Elektra/Neuromag % - FreeSurfer % - LORETA % - Localite % - MINC % - Neuralynx % - Neuroscan % - Nihon Koden (*.m00) % - Plexon % - SR Research Eyelink % - SensoMotoric Instruments (SMI) *.txt % - Tobii *.tsv % - Stanford *.ply % - Tucker Davis Technology % - VSM-Medtech/CTF % - Yokogawa % - nifti, gifti % - Nicolet *.e (currently from Natus, formerly Carefusion, Viasys and % Taugagreining. Also known as Oxford/Teca/Medelec Valor % - Nervus) % Copyright (C) 2003-2013 Robert Oostenveld % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % these are for remembering the type on subsequent calls with the same input arguments persistent previous_argin previous_argout previous_pwd if nargin<2 % ensure that all input arguments are defined desired = []; end current_argin = {filename, desired, varargin{:}}; current_pwd = pwd; if isequal(current_argin, previous_argin) && isequal(current_pwd, previous_pwd) % don't do the detection again, but return the previous value from cache type = previous_argout{1}; return end if isa(filename, 'memmapfile') filename = filename.Filename; end % % get the optional arguments % checkheader = ft_getopt(varargin, 'checkheader', true); % % if ~checkheader % % assume that the header is always ok, e.g when the file does not yet exist % % this replaces the normal function with a function that always returns true % filetype_check_header = @filetype_true; % end if iscell(filename) if ~isempty(desired) % perform the test for each filename, return a boolean vector type = false(size(filename)); else % return a string with the type for each filename type = cell(size(filename)); end for i=1:length(filename) if strcmp(filename{i}(end), '.') % do not recurse into this directory or the parent directory continue else if iscell(type) type{i} = ft_filetype(filename{i}, desired); else type(i) = ft_filetype(filename{i}, desired); end end end return end % start with unknown values type = 'unknown'; manufacturer = 'unknown'; content = 'unknown'; if isempty(filename) if isempty(desired) % return the "unknown" outputs return else % return that it is a non-match type = false; return end end % the parts of the filename are used further down if isdir(filename) [p, f, x] = fileparts(filename); p = filename; % the full path to the directory name d = f; % the last part of the directory name f = ''; x = ''; else [p, f, x] = fileparts(filename); end % prevent this test if the filename resembles an URI, i.e. like "scheme://" if isempty(strfind(filename , '://')) && isdir(filename) % the directory listing is needed below ls = dir(filename); % remove the parent directory and the directory itself from the list ls = ls(~strcmp({ls.name}, '.')); ls = ls(~strcmp({ls.name}, '..')); for i=1:length(ls) % make sure that the directory listing includes the complete path ls(i).name = fullfile(filename, ls(i).name); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % start determining the filetype %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this checks for a compressed file (of arbitrary type) if filetype_check_extension(filename, 'zip')... || (filetype_check_extension(filename, '.gz') && ~filetype_check_extension(filename, '.nii.gz'))... || filetype_check_extension(filename, 'tgz')... || filetype_check_extension(filename, 'tar') type = 'compressed'; manufacturer = 'undefined'; content = 'unknown, extract first'; % these are some streams for asynchronous BCI elseif filetype_check_uri(filename, 'fifo') type = 'fcdc_fifo'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'buffer') type = 'fcdc_buffer'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'mysql') type = 'fcdc_mysql'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'tcp') type = 'fcdc_tcp'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'udp') type = 'fcdc_udp'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'rfb') type = 'fcdc_rfb'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'serial') type = 'fcdc_serial'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'global') type = 'fcdc_global'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'global variable'; elseif filetype_check_uri(filename, 'shm') type = 'ctf_shm'; manufacturer = 'CTF'; content = 'real-time shared memory buffer'; elseif filetype_check_uri(filename, 'empty') type = 'empty'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = '/dev/null'; % known CTF file types elseif isdir(filename) && filetype_check_extension(filename, '.ds') && exist(fullfile(filename, [f '.res4']), 'file') type = 'ctf_ds'; manufacturer = 'CTF'; content = 'MEG dataset'; elseif isdir(filename) && ~isempty(dir(fullfile(filename, '*.res4'))) && ~isempty(dir(fullfile(filename, '*.meg4'))) type = 'ctf_ds'; manufacturer = 'CTF'; content = 'MEG dataset'; elseif filetype_check_extension(filename, '.res4') && (filetype_check_header(filename, 'MEG41RS') || filetype_check_header(filename, 'MEG42RS') || filetype_check_header(filename, 'MEG4RES') || filetype_check_header(filename, 'MEG3RES')) %'MEG3RES' pertains to ctf64.ds type = 'ctf_res4'; manufacturer = 'CTF'; content = 'MEG/EEG header information'; elseif filetype_check_extension(filename, '.meg4') && (filetype_check_header(filename, 'MEG41CP') || filetype_check_header(filename, 'MEG4CPT')) %'MEG4CPT' pertains to ctf64.ds type = 'ctf_meg4'; manufacturer = 'CTF'; content = 'MEG/EEG'; elseif strcmp(f, 'MarkerFile') && filetype_check_extension(filename, '.mrk') && filetype_check_header(filename, 'PATH OF DATASET:') type = 'ctf_mrk'; manufacturer = 'CTF'; content = 'marker file'; elseif filetype_check_extension(filename, '.mri') && filetype_check_header(filename, 'CTF_MRI_FORMAT VER 2.2') type = 'ctf_mri'; manufacturer = 'CTF'; content = 'MRI'; elseif filetype_check_extension(filename, '.mri') && filetype_check_header(filename, 'CTF_MRI_FORMAT VER 4', 31) type = 'ctf_mri4'; manufacturer = 'CTF'; content = 'MRI'; elseif filetype_check_extension(filename, '.hdm') type = 'ctf_hdm'; manufacturer = 'CTF'; content = 'volume conduction model'; elseif filetype_check_extension(filename, '.hc') type = 'ctf_hc'; manufacturer = 'CTF'; content = 'headcoil locations'; elseif filetype_check_extension(filename, '.shape') type = 'ctf_shape'; manufacturer = 'CTF'; content = 'headshape points'; elseif filetype_check_extension(filename, '.shape_info') type = 'ctf_shapeinfo'; manufacturer = 'CTF'; content = 'headshape information'; elseif filetype_check_extension(filename, '.wts') type = 'ctf_wts'; manufacturer = 'CTF'; content = 'SAM coefficients, i.e. spatial filter weights'; elseif filetype_check_extension(filename, '.svl') type = 'ctf_svl'; manufacturer = 'CTF'; content = 'SAM (pseudo-)statistic volumes'; % known Micromed file types elseif filetype_check_extension(filename, '.trc') && filetype_check_header(filename, '* MICROMED') type = 'micromed_trc'; manufacturer = 'Micromed'; content = 'Electrophysiological data'; % known Neuromag file types elseif filetype_check_extension(filename, '.fif') type = 'neuromag_fif'; manufacturer = 'Neuromag'; content = 'MEG header and data'; elseif filetype_check_extension(filename, '.bdip') type = 'neuromag_bdip'; manufacturer = 'Neuromag'; content = 'dipole model'; elseif filetype_check_extension(filename, '.eve') && exist(fullfile(p, [f '.fif']), 'file') type = 'neuromag_eve'; % these are being used by Tristan Technologies for the BabySQUID system manufacturer = 'Neuromag'; content = 'events'; % known Yokogawa file types elseif filetype_check_extension(filename, '.ave') || filetype_check_extension(filename, '.sqd') type = 'yokogawa_ave'; manufacturer = 'Yokogawa'; content = 'averaged MEG data'; elseif filetype_check_extension(filename, '.con') type = 'yokogawa_con'; manufacturer = 'Yokogawa'; content = 'continuous MEG data'; elseif filetype_check_extension(filename, '.raw') && filetype_check_header(filename, char([0 0 0 0])) % FIXME, this detection should possibly be improved type = 'yokogawa_raw'; manufacturer = 'Yokogawa'; content = 'evoked/trialbased MEG data'; elseif filetype_check_extension(filename, '.mrk') && filetype_check_header(filename, char([0 0 0 0])) % FIXME, this detection should possibly be improved type = 'yokogawa_mrk'; manufacturer = 'Yokogawa'; content = 'headcoil locations'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-coregis')) == 1 type = 'yokogawa_coregis'; manufacturer = 'Yokogawa'; content = 'exported fiducials'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-calib')) == 1 type = 'yokogawa_calib'; manufacturer = 'Yokogawa'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-channel')) == 1 type = 'yokogawa_channel'; manufacturer = 'Yokogawa'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-property')) == 1 type = 'yokogawa_property'; manufacturer = 'Yokogawa'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-TextData')) == 1 type = 'yokogawa_textdata'; manufacturer = 'Yokogawa'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-FLL')) == 1 type = 'yokogawa_fll'; manufacturer = 'Yokogawa'; elseif filetype_check_extension(filename, '.hsp') type = 'yokogawa_hsp'; manufacturer = 'Yokogawa'; % Neurosim files; this has to go before the 4D detection elseif ~isdir(filename) && (strcmp(f,'spikes') || filetype_check_header(filename,'# Spike information')) type = 'neurosim_spikes'; manufacturer = 'Jan van der Eerden (DCCN)'; content = 'simulated spikes'; elseif ~isdir(filename) && (strcmp(f,'evolution') || filetype_check_header(filename,'# Voltages')) type = 'neurosim_evolution'; manufacturer = 'Jan van der Eerden (DCCN)'; content = 'simulated membrane voltages and currents'; elseif ~isdir(filename) && (strcmp(f,'signals') || filetype_check_header(filename,'# Internal',2)) type = 'neurosim_signals'; manufacturer = 'Jan van der Eerden (DCCN)'; content = 'simulated network signals'; elseif isdir(filename) && exist(fullfile(filename, 'signals'), 'file') && exist(fullfile(filename, 'spikes'), 'file') type = 'neurosim_ds'; manufacturer = 'Jan van der Eerden (DCCN)'; content = 'simulated spikes and continuous signals'; % known 4D/BTI file types elseif filetype_check_extension(filename, '.pdf') && filetype_check_header(filename, 'E|lk') % I am not sure whether this header always applies type = '4d_pdf'; manufacturer = '4D/BTI'; content = 'raw MEG data (processed data file)'; elseif exist([filename '.m4d'], 'file') && exist([filename '.xyz'], 'file') % these two ascii header files accompany the raw data type = '4d_pdf'; manufacturer = '4D/BTI'; content = 'raw MEG data (processed data file)'; elseif filetype_check_extension(filename, '.m4d') && exist([filename(1:(end-3)) 'xyz'], 'file') % these come in pairs type = '4d_m4d'; manufacturer = '4D/BTI'; content = 'MEG header information'; elseif filetype_check_extension(filename, '.xyz') && exist([filename(1:(end-3)) 'm4d'], 'file') % these come in pairs type = '4d_xyz'; manufacturer = '4D/BTI'; content = 'MEG sensor positions'; elseif isequal(f, 'hs_file') % the filename is "hs_file" type = '4d_hs'; manufacturer = '4D/BTI'; content = 'head shape'; elseif length(filename)>=4 && ~isempty(strfind(filename,',rf')) type = '4d'; manufacturer = '4D/BTi'; content = ''; elseif filetype_check_extension(filename, '.el.ascii') && filetype_check_ascii(filename, 20) % assume that there are at least 20 bytes in the file, the example one has 4277 bytes type = '4d_el_ascii'; manufacturer = '4D/BTi'; content = 'electrode positions'; elseif length(f)<=4 && filetype_check_dir(p, 'config')%&& ~isempty(p) && exist(fullfile(p,'config'), 'file') %&& exist(fullfile(p,'hs_file'), 'file') % this could be a 4D file with non-standard/processed name % it will be detected as a 4D file when there is a config file in the % same directory as the specified file type = '4d'; manufacturer = '4D/BTi'; content = ''; % known EEProbe file types elseif filetype_check_extension(filename, '.cnt') && (filetype_check_header(filename, 'RIFF') || filetype_check_header(filename, 'RF64')) type = 'eep_cnt'; manufacturer = 'EEProbe'; content = 'EEG'; elseif filetype_check_extension(filename, '.avr') && filetype_check_header(filename, char([38 0 16 0])) type = 'eep_avr'; manufacturer = 'EEProbe'; content = 'ERP'; elseif filetype_check_extension(filename, '.trg') type = 'eep_trg'; manufacturer = 'EEProbe'; content = 'trigger information'; elseif filetype_check_extension(filename, '.rej') type = 'eep_rej'; manufacturer = 'EEProbe'; content = 'rejection marks'; % the yokogawa_mri has to be checked prior to asa_mri, because this one is more strict elseif filetype_check_extension(filename, '.mri') && filetype_check_header(filename, char(0)) % FIXME, this detection should possibly be improved type = 'yokogawa_mri'; manufacturer = 'Yokogawa'; content = 'anatomical MRI'; % known ASA file types elseif filetype_check_extension(filename, '.elc') type = 'asa_elc'; manufacturer = 'ASA'; content = 'electrode positions'; elseif filetype_check_extension(filename, '.vol') type = 'asa_vol'; manufacturer = 'ASA'; content = 'volume conduction model'; elseif filetype_check_extension(filename, '.bnd') type = 'asa_bnd'; manufacturer = 'ASA'; content = 'boundary element model details'; elseif filetype_check_extension(filename, '.msm') type = 'asa_msm'; manufacturer = 'ASA'; content = 'ERP'; elseif filetype_check_extension(filename, '.msr') type = 'asa_msr'; manufacturer = 'ASA'; content = 'ERP'; elseif filetype_check_extension(filename, '.dip') % FIXME, can also be CTF dipole file type = 'asa_dip'; manufacturer = 'ASA'; elseif filetype_check_extension(filename, '.mri') % FIXME, can also be CTF mri file type = 'asa_mri'; manufacturer = 'ASA'; content = 'MRI image header'; elseif filetype_check_extension(filename, '.iso') type = 'asa_iso'; manufacturer = 'ASA'; content = 'MRI image data'; % known BCI2000 file types elseif filetype_check_extension(filename, '.dat') && (filetype_check_header(filename, 'BCI2000') || filetype_check_header(filename, 'HeaderLen=')) type = 'bci2000_dat'; manufacturer = 'BCI2000'; content = 'continuous EEG'; % known Neuroscan file types elseif filetype_check_extension(filename, '.avg') && filetype_check_header(filename, 'Version 3.0') type = 'ns_avg'; manufacturer = 'Neuroscan'; content = 'averaged EEG'; elseif filetype_check_extension(filename, '.cnt') && filetype_check_header(filename, 'Version 3.0') type = 'ns_cnt'; manufacturer = 'Neuroscan'; content = 'continuous EEG'; elseif filetype_check_extension(filename, '.eeg') && filetype_check_header(filename, 'Version 3.0') type = 'ns_eeg'; manufacturer = 'Neuroscan'; content = 'epoched EEG'; elseif filetype_check_extension(filename, '.eeg') && filetype_check_header(filename, 'V3.0') type = 'neuroprax_eeg'; manufacturer = 'eldith GmbH'; content = 'continuous EEG'; elseif filetype_check_extension(filename, '.ee_') type = 'neuroprax_mrk'; manufacturer = 'eldith GmbH'; content = 'EEG markers'; % known Analyze & SPM file types elseif filetype_check_extension(filename, '.hdr') type = 'analyze_hdr'; manufacturer = 'Mayo Analyze'; content = 'PET/MRI image header'; elseif filetype_check_extension(filename, '.img') type = 'analyze_img'; manufacturer = 'Mayo Analyze'; content = 'PET/MRI image data'; elseif filetype_check_extension(filename, '.mnc') type = 'minc'; content = 'MRI image data'; elseif filetype_check_extension(filename, '.nii') && filetype_check_header(filename, {[92 1 0 0], [0 0 1 92]}) % header starts with the number 348 type = 'nifti'; content = 'MRI image data'; elseif filetype_check_extension(filename, '.nii') && filetype_check_header(filename, {[28 2 0 0], [0 0 2 28]}) % header starts with the number 540 type = 'nifti2'; content = 'MRI image data'; % known FSL file types elseif filetype_check_extension(filename, '.nii.gz') type = 'nifti_fsl'; content = 'MRI image data'; % known LORETA file types elseif filetype_check_extension(filename, '.lorb') type = 'loreta_lorb'; manufacturer = 'old LORETA'; content = 'source reconstruction'; elseif filetype_check_extension(filename, '.slor') type = 'loreta_slor'; manufacturer = 'sLORETA'; content = 'source reconstruction'; % known AFNI file types elseif filetype_check_extension(filename, '.brik') || filetype_check_extension(filename, '.BRIK') type = 'afni_brik'; content = 'MRI image data'; elseif filetype_check_extension(filename, '.head') || filetype_check_extension(filename, '.HEAD') type = 'afni_head'; content = 'MRI header data'; % known BrainVison file types elseif filetype_check_extension(filename, '.vhdr') type = 'brainvision_vhdr'; manufacturer = 'BrainProducts'; content = 'EEG header'; elseif filetype_check_extension(filename, '.vmrk') type = 'brainvision_vmrk'; manufacturer = 'BrainProducts'; content = 'EEG markers'; elseif filetype_check_extension(filename, '.vabs') type = 'brainvision_vabs'; manufacturer = 'BrainProducts'; content = 'Brain Vison Analyzer macro'; elseif filetype_check_extension(filename, '.eeg') && exist(fullfile(p, [f '.vhdr']), 'file') type = 'brainvision_eeg'; manufacturer = 'BrainProducts'; content = 'continuous EEG data'; elseif filetype_check_extension(filename, '.seg') type = 'brainvision_seg'; manufacturer = 'BrainProducts'; content = 'segmented EEG data'; elseif filetype_check_extension(filename, '.dat') && exist(fullfile(p, [f '.vhdr']), 'file') &&... ~filetype_check_header(filename, 'HeaderLen=') && ~filetype_check_header(filename, 'BESA_SA_IMAGE') &&... ~(exist(fullfile(p, [f '.gen']), 'file') || exist(fullfile(p, [f '.generic']), 'file')) % WARNING this is a very general name, it could be exported BrainVision % data but also a BESA beamformer source reconstruction or BCI2000 type = 'brainvision_dat'; manufacturer = 'BrainProducts'; content = 'exported EEG data'; elseif filetype_check_extension(filename, '.marker') type = 'brainvision_marker'; manufacturer = 'BrainProducts'; content = 'rejection markers'; % known Polhemus file types elseif filetype_check_extension(filename, '.pos') type = 'polhemus_pos'; manufacturer = 'BrainProducts/CTF/Polhemus?'; % actually I don't know whose software it is content = 'electrode positions'; % known Blackrock Microsystems file types elseif strncmp(x,'.ns',3) && (filetype_check_header(filename, 'NEURALCD') || filetype_check_header(filename, 'NEURALSG')) type = 'blackrock_nsx'; manufacturer = 'Blackrock Microsystems'; content = 'conintuously sampled data'; elseif filetype_check_extension(filename, '.nev') && filetype_check_header(filename, 'NEURALEV') type = 'blackrock_nev'; manufacturer = 'Blackrock Microsystems'; contenct = 'extracellular electrode spike information'; % known Neuralynx file types elseif filetype_check_extension(filename, '.nev') || filetype_check_extension(filename, '.Nev') type = 'neuralynx_nev'; manufacturer = 'Neuralynx'; content = 'event information'; elseif filetype_check_extension(filename, '.ncs') && filetype_check_header(filename, '####') type = 'neuralynx_ncs'; manufacturer = 'Neuralynx'; content = 'continuous single channel recordings'; elseif filetype_check_extension(filename, '.nse') && filetype_check_header(filename, '####') type = 'neuralynx_nse'; manufacturer = 'Neuralynx'; content = 'spike waveforms'; elseif filetype_check_extension(filename, '.nts') && filetype_check_header(filename, '####') type = 'neuralynx_nts'; manufacturer = 'Neuralynx'; content = 'timestamps only'; elseif filetype_check_extension(filename, '.nvt') type = 'neuralynx_nvt'; manufacturer = 'Neuralynx'; content = 'video tracker'; elseif filetype_check_extension(filename, '.nst') type = 'neuralynx_nst'; manufacturer = 'Neuralynx'; content = 'continuous stereotrode recordings'; elseif filetype_check_extension(filename, '.ntt') type = 'neuralynx_ntt'; manufacturer = 'Neuralynx'; content = 'continuous tetrode recordings'; elseif strcmpi(f, 'logfile') && strcmpi(x, '.txt') % case insensitive type = 'neuralynx_log'; manufacturer = 'Neuralynx'; content = 'log information in ASCII format'; elseif ~isempty(strfind(lower(f), 'dma')) && strcmpi(x, '.log') % this is not a very strong detection type = 'neuralynx_dma'; manufacturer = 'Neuralynx'; content = 'raw aplifier data directly from DMA'; elseif filetype_check_extension(filename, '.nrd') % see also above, since Cheetah 5.x the file extension has changed type = 'neuralynx_dma'; manufacturer = 'Neuralynx'; content = 'raw aplifier data directly from DMA'; elseif isdir(filename) && (any(filetype_check_extension({ls.name}, '.nev')) || any(filetype_check_extension({ls.name}, '.Nev'))) % a regular Neuralynx dataset directory that contains an event file type = 'neuralynx_ds'; manufacturer = 'Neuralynx'; content = 'dataset'; elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.ncs')) % a directory containing continuously sampled channels in Neuralynx format type = 'neuralynx_ds'; manufacturer = 'Neuralynx'; content = 'continuously sampled channels'; elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.nse')) % a directory containing spike waveforms in Neuralynx format type = 'neuralynx_ds'; manufacturer = 'Neuralynx'; content = 'spike waveforms'; elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.nte')) % a directory containing spike timestamps in Neuralynx format type = 'neuralynx_ds'; manufacturer = 'Neuralynx'; content = 'spike timestamps'; elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.ntt')) % a directory containing tetrode recordings in Neuralynx format type = 'neuralynx_ds'; manufacturer = 'Neuralynx'; content = 'tetrode recordings '; elseif isdir(p) && exist(fullfile(p, 'header'), 'file') && exist(fullfile(p, 'samples'), 'file') && exist(fullfile(p, 'events'), 'file') type = 'fcdc_buffer_offline'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'FieldTrip buffer offline dataset'; elseif isdir(filename) && exist(fullfile(filename, 'info.xml'), 'file') && exist(fullfile(filename, 'signal1.bin'), 'file') % this is an OS X package directory representing a complete EEG dataset % it contains a Content file, multiple xml files and one or more signalN.bin files type = 'egi_mff'; manufacturer = 'Electrical Geodesics Incorporated'; content = 'raw EEG data'; elseif ~isdir(filename) && isdir(p) && exist(fullfile(p, 'info.xml'), 'file') && exist(fullfile(p, 'signal1.bin'), 'file') % the file that the user specified is one of the files in an mff package directory type = 'egi_mff'; manufacturer = 'Electrical Geodesics Incorporated'; content = 'raw EEG data'; % these are formally not Neuralynx file formats, but at the FCDC we use them together with Neuralynx elseif isdir(filename) && filetype_check_neuralynx_cds(filename) % a downsampled Neuralynx DMA file can be split into three separate lfp/mua/spike directories % treat them as one combined dataset type = 'neuralynx_cds'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'dataset containing separate lfp/mua/spike directories'; elseif filetype_check_extension(filename, '.tsl') && filetype_check_header(filename, 'tsl') type = 'neuralynx_tsl'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'timestamps from DMA log file'; elseif filetype_check_extension(filename, '.tsh') && filetype_check_header(filename, 'tsh') type = 'neuralynx_tsh'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'timestamps from DMA log file'; elseif filetype_check_extension(filename, '.ttl') && filetype_check_header(filename, 'ttl') type = 'neuralynx_ttl'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'Parallel_in from DMA log file'; elseif filetype_check_extension(filename, '.bin') && filetype_check_header(filename, {'uint8', 'uint16', 'uint32', 'int8', 'int16', 'int32', 'int64', 'float32', 'float64'}) type = 'neuralynx_bin'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'single channel continuous data'; elseif isdir(filename) && any(filetype_check_extension({ls.name}, '.ttl')) && any(filetype_check_extension({ls.name}, '.tsl')) && any(filetype_check_extension({ls.name}, '.tsh')) % a directory containing the split channels from a DMA logfile type = 'neuralynx_sdma'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'split DMA log file'; elseif isdir(filename) && filetype_check_extension(filename, '.sdma') % a directory containing the split channels from a DMA logfile type = 'neuralynx_sdma'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'split DMA log file'; % known Plexon file types elseif filetype_check_extension(filename, '.nex') && filetype_check_header(filename, 'NEX1') type = 'plexon_nex'; manufacturer = 'Plexon'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.plx') && filetype_check_header(filename, 'PLEX') type = 'plexon_plx'; manufacturer = 'Plexon'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.ddt') type = 'plexon_ddt'; manufacturer = 'Plexon'; elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.nex')) && most(filetype_check_header({ls.name}, 'NEX1')) % a directory containing multiple plexon NEX files type = 'plexon_ds'; manufacturer = 'Plexon'; content = 'electrophysiological data'; % known Cambridge Electronic Design file types elseif filetype_check_extension(filename, '.smr') type = 'ced_son'; manufacturer = 'Cambridge Electronic Design'; content = 'Spike2 SON filing system'; % known BESA file types elseif filetype_check_extension(filename, '.avr') && strcmp(type, 'unknown') type = 'besa_avr'; % FIXME, can also be EEProbe average EEG manufacturer = 'BESA'; content = 'average EEG'; elseif filetype_check_extension(filename, '.elp') type = 'besa_elp'; manufacturer = 'BESA'; content = 'electrode positions'; elseif filetype_check_extension(filename, '.eps') type = 'besa_eps'; manufacturer = 'BESA'; content = 'digitizer information'; elseif filetype_check_extension(filename, '.sfp') type = 'besa_sfp'; manufacturer = 'BESA'; content = 'sensor positions'; elseif filetype_check_extension(filename, '.ela') type = 'besa_ela'; manufacturer = 'BESA'; content = 'sensor information'; elseif filetype_check_extension(filename, '.pdg') type = 'besa_pdg'; manufacturer = 'BESA'; content = 'paradigm file'; elseif filetype_check_extension(filename, '.tfc') type = 'besa_tfc'; manufacturer = 'BESA'; content = 'time frequency coherence'; elseif filetype_check_extension(filename, '.mul') type = 'besa_mul'; manufacturer = 'BESA'; content = 'multiplexed ascii format'; elseif filetype_check_extension(filename, '.dat') && filetype_check_header(filename, 'BESA_SA') % header can start with BESA_SA_IMAGE or BESA_SA_MN_IMAGE type = 'besa_src'; manufacturer = 'BESA'; content = 'beamformer source reconstruction'; elseif filetype_check_extension(filename, '.swf') && filetype_check_header(filename, 'Npts=') type = 'besa_swf'; manufacturer = 'BESA'; content = 'beamformer source waveform'; elseif filetype_check_extension(filename, '.bsa') type = 'besa_bsa'; manufacturer = 'BESA'; content = 'beamformer source locations and orientations'; elseif exist(fullfile(p, [f '.dat']), 'file') && (exist(fullfile(p, [f '.gen']), 'file') || exist(fullfile(p, [f '.generic']), 'file')) type = 'besa_sb'; manufacturer = 'BESA'; content = 'simple binary channel data with a separate generic ascii header'; elseif filetype_check_extension(filename, '.sfh') && filetype_check_header(filename, 'NrOfPoints') type = 'besa_sfh'; manufacturer = 'BESA'; content = 'electrode and fiducial information'; elseif filetype_check_extension(filename, '.besa') type = 'besa_besa'; manufacturer = 'BESA'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.srf') && filetype_check_header(filename, [0 0 0 0], 4) type = 'brainvoyager_srf'; manufacturer = 'BrainVoyager'; % see http://support.brainvoyager.com/installation-introduction/23-file-formats/375-users-guide-23-the-format-of-srf-files.html content = 'surface'; % known Dataq file formats elseif filetype_check_extension(upper(filename), '.WDQ') type = 'dataq_wdq'; manufacturer = 'dataq instruments'; content = 'electrophysiological data'; % old files from Pascal Fries' PhD research at the MPI elseif filetype_check_extension(filename, '.dap') && filetype_check_header(filename, char(1)) type = 'mpi_dap'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; elseif isdir(filename) && ~isempty(cell2mat(regexp({ls.name}, '.dap$'))) type = 'mpi_ds'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; % Frankfurt SPASS format, which uses the Labview Datalog (DTLG) format elseif filetype_check_extension(filename, '.ana') && filetype_check_header(filename, 'DTLG') type = 'spass_ana'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.swa') && filetype_check_header(filename, 'DTLG') type = 'spass_swa'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.spi') && filetype_check_header(filename, 'DTLG') type = 'spass_spi'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.stm') && filetype_check_header(filename, 'DTLG') type = 'spass_stm'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.bhv') && filetype_check_header(filename, 'DTLG') type = 'spass_bhv'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; % known Chieti ITAB file types elseif filetype_check_extension(filename, '.raw') && (filetype_check_header(filename, 'FORMAT: ATB-BIOMAGDATA') || filetype_check_header(filename, '[HeaderType]')) type = 'itab_raw'; manufacturer = 'Chieti ITAB'; content = 'MEG data, including sensor positions'; elseif filetype_check_extension(filename, '.raw.mhd') type = 'itab_mhd'; manufacturer = 'Chieti ITAB'; content = 'MEG header data, including sensor positions'; elseif filetype_check_extension(filename, '.asc') && ~filetype_check_header(filename, '**') type = 'itab_asc'; manufacturer = 'Chieti ITAB'; content = 'headshape digitization file'; % known Nexstim file types elseif filetype_check_extension(filename, '.nxe') type = 'nexstim_nxe'; manufacturer = 'Nexstim'; content = 'electrophysiological data'; % known Tucker-Davis-Technology file types elseif filetype_check_extension(filename, '.tbk') type = 'tdt_tbk'; manufacturer = 'Tucker-Davis-Technology'; content = 'database/tank meta-information'; elseif filetype_check_extension(filename, '.tdx') type = 'tdt_tdx'; manufacturer = 'Tucker-Davis-Technology'; content = 'database/tank meta-information'; elseif filetype_check_extension(filename, '.tsq') type = 'tdt_tsq'; manufacturer = 'Tucker-Davis-Technology'; content = 'block header information'; elseif filetype_check_extension(filename, '.tev') type = 'tdt_tev'; manufacturer = 'Tucker-Davis-Technology'; content = 'electrophysiological data'; % raw audio and video data from https://github.com/andreyzhd/VideoMEG % the extension *.aud/*.vid is used at NatMEG and *.audio.dat/*.video.dat seems to be used in Helsinki elseif (filetype_check_extension(filename, '.aud') || filetype_check_extension(filename, '.audio.dat')) && filetype_check_header(filename, 'ELEKTA_AUDIO_FILE') % this should go before curry_dat type = 'videomeg_aud'; manufacturer = 'VideoMEG'; content = 'audio'; elseif (filetype_check_extension(filename, '.vid') || filetype_check_extension(filename, '.video.dat')) && filetype_check_header(filename, 'ELEKTA_VIDEO_FILE') % this should go before curry_dat type = 'videomeg_vid'; manufacturer = 'VideoMEG'; content = 'video'; elseif (filetype_check_extension(filename, '.dat') || filetype_check_extension(filename, '.Dat')) && (exist(fullfile(p, [f '.ini']), 'file') || exist(fullfile(p, [f '.Ini']), 'file')) % this should go before curry_dat type = 'deymed_dat'; manufacturer = 'Deymed'; content = 'raw eeg data'; elseif (filetype_check_extension(filename, '.ini') || filetype_check_extension(filename, '.Ini')) && (exist(fullfile(p, [f '.dat']), 'file') || exist(fullfile(p, [f '.Dat']), 'file')) type = 'deymed_ini'; manufacturer = 'Deymed'; content = 'eeg header information'; elseif filetype_check_extension(filename, '.dat') && (filetype_check_header(filename, [0 0 16 0 16 0], 8) || filetype_check_header(filename, [0 0 16 0 16 0], 0)) % this should go before curry_dat type = 'jaga16'; manufacturer = 'Jinga-Hi'; content = 'electrophysiological data'; % known Curry V4 file types elseif filetype_check_extension(filename, '.dap') type = 'curry_dap'; % FIXME, can also be MPI Frankfurt electrophysiological data manufacturer = 'Curry'; content = 'data parameter file'; elseif filetype_check_extension(filename, '.dat') type = 'curry_dat'; manufacturer = 'Curry'; content = 'raw data file'; elseif filetype_check_extension(filename, '.rs4') type = 'curry_rs4'; manufacturer = 'Curry'; content = 'sensor geometry file'; elseif filetype_check_extension(filename, '.par') type = 'curry_par'; manufacturer = 'Curry'; content = 'data or image parameter file'; elseif filetype_check_extension(filename, '.bd0') || filetype_check_extension(filename, '.bd1') || filetype_check_extension(filename, '.bd2') || filetype_check_extension(filename, '.bd3') || filetype_check_extension(filename, '.bd4') || filetype_check_extension(filename, '.bd5') || filetype_check_extension(filename, '.bd6') || filetype_check_extension(filename, '.bd7') || filetype_check_extension(filename, '.bd8') || filetype_check_extension(filename, '.bd9') type = 'curry_bd'; manufacturer = 'Curry'; content = 'BEM description file'; elseif filetype_check_extension(filename, '.bt0') || filetype_check_extension(filename, '.bt1') || filetype_check_extension(filename, '.bt2') || filetype_check_extension(filename, '.bt3') || filetype_check_extension(filename, '.bt4') || filetype_check_extension(filename, '.bt5') || filetype_check_extension(filename, '.bt6') || filetype_check_extension(filename, '.bt7') || filetype_check_extension(filename, '.bt8') || filetype_check_extension(filename, '.bt9') type = 'curry_bt'; manufacturer = 'Curry'; content = 'BEM transfer matrix file'; elseif filetype_check_extension(filename, '.bm0') || filetype_check_extension(filename, '.bm1') || filetype_check_extension(filename, '.bm2') || filetype_check_extension(filename, '.bm3') || filetype_check_extension(filename, '.bm4') || filetype_check_extension(filename, '.bm5') || filetype_check_extension(filename, '.bm6') || filetype_check_extension(filename, '.bm7') || filetype_check_extension(filename, '.bm8') || filetype_check_extension(filename, '.bm9') type = 'curry_bm'; manufacturer = 'Curry'; content = 'BEM full matrix file'; elseif filetype_check_extension(filename, '.dig') type = 'curry_dig'; manufacturer = 'Curry'; content = 'digitizer file'; elseif filetype_check_extension(filename, '.txt') && filetype_check_header(filename, '##') type = 'smi_txt'; manufacturer = 'SensoMotoric Instruments (SMI)'; content = 'eyetracker data'; % 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)'; elseif filetype_check_extension(filename, '.tsv') && (filetype_check_header(filename, 'Data Properties:') || filetype_check_header(filename, 'System Properties:')) type = 'tobii_tsv'; manufacturer = 'Tobii'; content = 'eyetracker data (ascii)'; % known Curry V2 file types elseif filetype_check_extension(filename, '.sp0') || filetype_check_extension(filename, '.sp1') || filetype_check_extension(filename, '.sp2') || filetype_check_extension(filename, '.sp3') || filetype_check_extension(filename, '.sp4') || filetype_check_extension(filename, '.sp5') || filetype_check_extension(filename, '.sp6') || filetype_check_extension(filename, '.sp7') || filetype_check_extension(filename, '.sp8') || filetype_check_extension(filename, '.sp9') type = 'curry_sp'; manufacturer = 'Curry'; content = 'point list'; elseif filetype_check_extension(filename, '.s10') || filetype_check_extension(filename, '.s11') || filetype_check_extension(filename, '.s12') || filetype_check_extension(filename, '.s13') || filetype_check_extension(filename, '.s14') || filetype_check_extension(filename, '.s15') || filetype_check_extension(filename, '.s16') || filetype_check_extension(filename, '.s17') || filetype_check_extension(filename, '.s18') || filetype_check_extension(filename, '.s19') || filetype_check_extension(filename, '.s20') || filetype_check_extension(filename, '.s21') || filetype_check_extension(filename, '.s22') || filetype_check_extension(filename, '.s23') || filetype_check_extension(filename, '.s24') || filetype_check_extension(filename, '.s25') || filetype_check_extension(filename, '.s26') || filetype_check_extension(filename, '.s27') || filetype_check_extension(filename, '.s28') || filetype_check_extension(filename, '.s29') || filetype_check_extension(filename, '.s30') || filetype_check_extension(filename, '.s31') || filetype_check_extension(filename, '.s32') || filetype_check_extension(filename, '.s33') || filetype_check_extension(filename, '.s34') || filetype_check_extension(filename, '.s35') || filetype_check_extension(filename, '.s36') || filetype_check_extension(filename, '.s37') || filetype_check_extension(filename, '.s38') || filetype_check_extension(filename, '.s39') type = 'curry_s'; manufacturer = 'Curry'; content = 'triangle or tetraedra list'; elseif filetype_check_extension(filename, '.pom') type = 'curry_pom'; manufacturer = 'Curry'; content = 'anatomical localization file'; elseif filetype_check_extension(filename, '.res') type = 'curry_res'; manufacturer = 'Curry'; content = 'functional localization file'; % known MBFYS file types elseif filetype_check_extension(filename, '.tri') type = 'mbfys_tri'; manufacturer = 'MBFYS'; content = 'triangulated surface'; elseif filetype_check_extension(filename, '.ama') && filetype_check_header(filename, [10 0 0 0]) type = 'mbfys_ama'; manufacturer = 'MBFYS'; content = 'BEM volume conduction model'; % Electrical Geodesics Incorporated formats % the egi_mff format is checked earlier elseif (filetype_check_extension(filename, '.egis') || filetype_check_extension(filename, '.ave') || filetype_check_extension(filename, '.gave') || filetype_check_extension(filename, '.raw')) && (filetype_check_header(filename, [char(1) char(2) char(3) char(4) char(255) char(255)]) || filetype_check_header(filename, [char(3) char(4) char(1) char(2) char(255) char(255)])) type = 'egi_egia'; manufacturer = 'Electrical Geodesics Incorporated'; content = 'averaged EEG data'; elseif (filetype_check_extension(filename, '.egis') || filetype_check_extension(filename, '.ses') || filetype_check_extension(filename, '.raw')) && (filetype_check_header(filename, [char(1) char(2) char(3) char(4) char(0) char(3)]) || filetype_check_header(filename, [char(3) char(4) char(1) char(2) char(0) char(3)])) type = 'egi_egis'; manufacturer = 'Electrical Geodesics Incorporated'; content = 'raw EEG data'; elseif (filetype_check_extension(filename, '.sbin') || filetype_check_extension(filename, '.raw')) % note that the Chieti MEG data format also has the extension *.raw % but that can be detected by looking at the file header type = 'egi_sbin'; manufacturer = 'Electrical Geodesics Incorporated'; content = 'averaged EEG data'; % FreeSurfer file formats, see also http://www.grahamwideman.com/gw/brain/fs/surfacefileformats.htm elseif filetype_check_extension(filename, '.mgz') type = 'freesurfer_mgz'; manufacturer = 'FreeSurfer'; content = 'anatomical MRI'; elseif filetype_check_extension(filename, '.mgh') type = 'freesurfer_mgh'; manufacturer = 'FreeSurfer'; content = 'anatomical MRI'; elseif filetype_check_header(filename, [255 255 254]) % FreeSurfer Triangle Surface Binary Format type = 'freesurfer_triangle_binary'; % there is also an ascii triangle format manufacturer = 'FreeSurfer'; content = 'surface description'; elseif filetype_check_header(filename, [255 255 255]) % Quadrangle File type = 'freesurfer_quadrangle'; % there is no ascii quadrangle format manufacturer = 'FreeSurfer'; content = 'surface description'; elseif filetype_check_header(filename, [255 255 253]) && ~exist([filename(1:(end-4)) '.mat'], 'file') % "New" Quadrangle File type = 'freesurfer_quadrangle_new'; manufacturer = 'FreeSurfer'; content = 'surface description'; elseif filetype_check_extension(filename, '.curv') && filetype_check_header(filename, [255 255 255]) % "New" Curv File type = 'freesurfer_curv_new'; manufacturer = 'FreeSurfer'; content = 'surface description'; elseif filetype_check_extension(filename, '.annot') % Freesurfer annotation file type = 'freesurfer_annot'; manufacturer = 'FreeSurfer'; content = 'parcellation annotation'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'_nrs_')) == 1 % This may be improved by looking into the file, rather than assuming the % filename has "_nrs_" somewhere. Also, distinction by the different file % types could be made type = 'bucn_nirs'; manufacturer = 'BUCN'; content = 'ascii formatted nirs data'; % Homer is MATLAB software for NIRS processing, see http://www.nmr.mgh.harvard.edu/DOT/resources/homer2/home.htm elseif filetype_check_extension(filename, '.nirs') && filetype_check_header(filename, 'MATLAB') type = 'homer_nirs'; manufacturer = 'Homer'; content = '(f)NIRS data'; % known Artinis file format elseif filetype_check_extension(filename, '.oxy3') type = 'oxy3'; manufacturer = 'Artinis Medical Systems'; content = '(f)NIRS data'; % known TETGEN file types, see http://tetgen.berlios.de/fformats.html elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.poly']), 'file') type = 'tetgen_poly'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with piecewise linear complex'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.smesh']), 'file') type = 'tetgensmesh'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with simple piecewise linear complex'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.ele']), 'file') type = 'tetgen_ele'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with tetrahedra'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.face']), 'file') type = 'tetgen_face'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with triangular faces'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.edge']), 'file') type = 'tetgen_edge'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with boundary edges'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.vol']), 'file') type = 'tetgen_vol'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with maximum volumes'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.var']), 'file') type = 'tetgen_var'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with variant constraints for facets/segments'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.neigh']), 'file') type = 'tetgen_neigh'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with neighbors'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) type = 'tetgen_node'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with only nodes'; % some BrainSuite file formats, see http://brainsuite.bmap.ucla.edu/ elseif filetype_check_extension(filename, '.dfs') && filetype_check_header(filename, 'DFS_LE v2.0') type = 'brainsuite_dfs'; manufacturer = 'BrainSuite, see http://brainsuite.bmap.ucla.edu'; content = 'list of triangles and vertices'; elseif filetype_check_extension(filename, '.bst') && filetype_check_ascii(filename) type = 'brainsuite_dst'; manufacturer = 'BrainSuite, see http://brainsuite.bmap.ucla.edu'; content = 'a collection of files with geometrical data'; % it seems to be similar to a Caret *.spec file elseif filetype_check_extension(filename, '.dfc') && filetype_check_header(filename, 'LONIDFC') type = 'loni_dfc'; manufacturer = 'LONI'; % it is used in BrainSuite content = 'curvature information'; % some BrainVISA file formats, see http://brainvisa.info elseif filetype_check_extension(filename, '.mesh') && (filetype_check_header(filename, 'ascii') || filetype_check_header(filename, 'binarABCD') || filetype_check_header(filename, 'binarDCBA')) % http://brainvisa.info/doc/documents-4.4/formats/mesh.pdf type = 'brainvisa_mesh'; manufacturer = 'BrainVISA'; content = 'vertices and triangles'; elseif filetype_check_extension(filename, '.minf') && filetype_check_ascii(filename) type = 'brainvisa_minf'; manufacturer = 'BrainVISA'; content = 'annotation/metadata'; % some other known file types elseif length(filename)>4 && exist([filename(1:(end-4)) '.mat'], 'file') && exist([filename(1:(end-4)) '.bin'], 'file') % this is a self-defined FCDC data format, consisting of two files % there is a MATLAB V6 file with the header and a binary file with the data (multiplexed, ieee-le, double) type = 'fcdc_matbin'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'multiplexed electrophysiology data'; elseif filetype_check_extension(filename, '.lay') type = 'layout'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'layout of channels for plotting'; elseif filetype_check_extension(filename, '.stl') type = 'stl'; manufacturer = 'various'; content = 'stereo litography file'; elseif filetype_check_extension(filename, '.obj') type = 'obj'; manufacturer = 'Wavefront Technologies'; content = 'Wavefront OBJ'; elseif filetype_check_extension(filename, '.dcm') || filetype_check_extension(filename, '.ima') || filetype_check_header(filename, 'DICM', 128) type = 'dicom'; manufacturer = 'Dicom'; content = 'image data'; elseif filetype_check_extension(filename, '.trl') type = 'fcdc_trl'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'trial definitions'; elseif filetype_check_extension(filename, '.bdf') && filetype_check_header(filename, [255 'BIOSEMI']) type = 'biosemi_bdf'; manufacturer = 'Biosemi Data Format'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.edf') type = 'edf'; manufacturer = 'European Data Format'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.gdf') && filetype_check_header(filename, 'GDF') type = 'gdf'; manufacturer = 'BIOSIG - Alois Schloegl'; content = 'biosignals'; elseif filetype_check_extension(filename, '.mat') && filetype_check_header(filename, 'MATLAB') && filetype_check_spmeeg_mat(filename) type = 'spmeeg_mat'; manufacturer = 'Wellcome Trust Centre for Neuroimaging, UCL, UK'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.mat') && filetype_check_header(filename, 'MATLAB') && filetype_check_gtec_mat(filename) type = 'gtec_mat'; manufacturer = 'Guger Technologies, http://www.gtec.at'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.mat') && filetype_check_header(filename, 'MATLAB') && filetype_check_ced_spike6mat(filename) type = 'ced_spike6mat'; manufacturer = 'Cambridge Electronic Design Limited'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.mat') && filetype_check_header(filename, 'MATLAB') type = 'matlab'; manufacturer = 'MATLAB'; content = 'MATLAB binary data'; elseif filetype_check_header(filename, 'RIFF', 0) && filetype_check_header(filename, 'WAVE', 8) type = 'riff_wave'; manufacturer = 'Microsoft'; content = 'audio'; elseif filetype_check_extension(filename, '.txt') && filetype_check_header(filename, 'Site') type = 'easycap_txt'; manufacturer = 'Easycap'; content = 'electrode positions'; elseif filetype_check_extension(filename, '.txt') type = 'ascii_txt'; manufacturer = ''; content = ''; elseif filetype_check_extension(filename, '.pol') type = 'polhemus_fil'; manufacturer = 'Functional Imaging Lab, London, UK'; content = 'headshape points'; elseif filetype_check_extension(filename, '.set') type = 'eeglab_set'; manufacturer = 'Swartz Center for Computational Neuroscience, San Diego, USA'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.erp') type = 'eeglab_erp'; manufacturer = 'Swartz Center for Computational Neuroscience, San Diego, USA'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.t') && filetype_check_header(filename, '%%BEGINHEADER') type = 'mclust_t'; manufacturer = 'MClust'; content = 'sorted spikes'; elseif filetype_check_header(filename, 26) type = 'nimh_cortex'; manufacturer = 'NIMH Laboratory of Neuropsychology, http://www.cortex.salk.edu'; content = 'events and eye channels'; elseif filetype_check_extension(filename, '.foci') && filetype_check_header(filename, '<?xml') type = 'caret_foci'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.border') && filetype_check_header(filename, '<?xml') type = 'caret_border'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.spec') && (filetype_check_header(filename, '<?xml') || filetype_check_header(filename, 'BeginHeader')) type = 'caret_spec'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.coord.')) && filetype_check_header(filename, '<?xml') type = 'caret_coord'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.topo.')) && filetype_check_header(filename, '<?xml') type = 'caret_topo'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.surf.')) && filetype_check_header(filename, '<?xml') type = 'caret_surf'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.label.')) && filetype_check_header(filename, '<?xml') type = 'caret_label'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.func.')) && filetype_check_header(filename, '<?xml') type = 'caret_func'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.shape.')) && filetype_check_header(filename, '<?xml') type = 'caret_shape'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && filetype_check_header(filename, '<?xml') type = 'gifti'; manufacturer = 'Neuroimaging Informatics Technology Initiative'; content = 'tesselated surface description'; elseif filetype_check_extension(filename, '.v') type = 'vista'; manufacturer = 'University of British Columbia, Canada, http://www.cs.ubc.ca/nest/lci/vista/vista.html'; content = 'A format for computer vision research, contains meshes or volumes'; elseif filetype_check_extension(filename, '.tet') type = 'tet'; manufacturer = 'a.o. INRIA, see http://shapes.aimatshape.net/'; content = 'tetraedral mesh'; elseif filetype_check_extension(filename, '.nc') type = 'netmeg'; manufacturer = 'Center for Biomedical Research Excellence (COBRE), see http://cobre.mrn.org/megsim/tools/netMEG/netMEG.html'; content = 'MEG data'; elseif filetype_check_extension(filename, 'trk') type = 'trackvis_trk'; manufacturer = 'Martinos Center for Biomedical Imaging, see http://www.trackvis.org'; content = 'fiber tracking data from diffusion MR imaging'; elseif filetype_check_extension(filename, '.xml') && filetype_check_header(filename, '<EEGMarkerList', 39) type = 'localite_pos'; manufacturer = 'Localite'; content = 'EEG electrode positions'; elseif filetype_check_extension(filename, '.mbi') type = 'manscan_mbi'; manufacturer = 'MANSCAN'; content = 'EEG header'; elseif filetype_check_extension(filename, '.mb2') type = 'manscan_mb2'; manufacturer = 'MANSCAN'; content = 'EEG data'; elseif filetype_check_header(filename, 'ply') type = 'ply'; manufacturer = 'Stanford Triangle Format'; content = 'three dimensional data from 3D scanners, see http://en.wikipedia.org/wiki/PLY_(file_format)'; elseif filetype_check_extension(filename, '.csv') type = 'csv'; manufacturer = 'Generic'; content = 'Comma-separated values, see http://en.wikipedia.org/wiki/Comma-separated_values'; elseif filetype_check_extension(filename, '.ah5') type = 'AnyWave'; manufacturer = 'AnyWave, http://meg.univ-amu.fr/wiki/AnyWave'; content = 'MEG/SEEG/EEG data'; elseif (isdir(filename) && exist(fullfile(p, [d '.EEG.Poly5']), 'file')) || filetype_check_extension(filename, '.Poly5') type = 'tmsi_poly5'; manufacturer = 'TMSi PolyBench'; content = 'EEG'; elseif (isdir(filename) && exist(fullfile(filename, 'DataSetSession.xml'), 'file') && exist(fullfile(filename, 'DataSetProtocol.xml'), 'file')) type = 'mega_neurone'; manufacturer = 'Mega - http://www.megaemg.com'; content = 'EEG'; elseif filetype_check_extension(filename, '.e') type = 'nervus_eeg'; % Nervus/Nicolet EEG files manufacturer = 'Natus'; content = 'EEG'; elseif filetype_check_extension(filename, '.m00') type = 'nihonkohden_m00'; manufacturer = 'Nihon Kohden'; content = 'continuous EEG'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % finished determining the filetype %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(type, 'unknown') if ~exist(filename, 'file') && ~exist(filename, 'dir') warning('file or directory "%s" does not exist, could not determine fileformat', filename); else warning('could not determine filetype of %s', filename); end end if ~isempty(desired) % return a boolean value instead of a descriptive string type = strcmp(type, desired); end % remember the current input and output arguments, so that they can be % reused on a subsequent call in case the same input argument is given current_argout = {type}; if isempty(previous_argin) && ~strcmp(type, 'unknown') previous_argin = current_argin; previous_argout = current_argout; previous_pwd = current_pwd; elseif isempty(previous_argin) && (exist(filename,'file') || exist(filename,'dir')) && strcmp(type, 'unknown') % if the type is unknown, but the file or dir exists, save the current output previous_argin = current_argin; previous_argout = current_argout; previous_pwd = current_pwd; else % don't remember in case unknown previous_argin = []; previous_argout = []; previous_pwd = []; end return % filetype main() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that helps in deciding whether a directory with files should % be treated as a "dataset". This function returns a logical 1 (TRUE) if more % than half of the element of a vector are nonzero number or are 1 or TRUE. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = most(x) x = x(~isnan(x(:))); y = sum(x==0)<ceil(length(x)/2); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that always returns a true value %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = filetype_true(varargin) y = 1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that checks for CED spike6 mat file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = filetype_check_ced_spike6mat(filename) res = 1; var = whos('-file', filename); % Check whether all the variables in the file are structs (representing channels) if ~all(strcmp('struct', unique({var(:).class})) == 1) res = 0; return; end var = load(filename, var(1).name); var = struct2cell(var); % Check whether the fields of the first struct have some particular names fnames = { 'title' 'comment' 'interval' 'scale' 'offset' 'units' 'start' 'length' 'values' 'times' }; res = (numel(intersect(fieldnames(var{1}), fnames)) >= 5); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that checks for a SPM eeg/meg mat file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = filetype_check_spmeeg_mat(filename) % check for the accompanying *.dat file res = exist([filename(1:(end-4)) '.dat'], 'file'); if ~res, return; end % check the content of the *.mat file var = whos('-file', filename); res = res && numel(var)==1; res = res && strcmp('D', getfield(var, {1}, 'name')); res = res && strcmp('struct', getfield(var, {1}, 'class')); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that checks for a GTEC mat file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = filetype_check_gtec_mat(filename) % check the content of the *.mat file var = whos('-file', filename); res = length(intersect({'log', 'names'}, {var.name}))==2; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that checks the presence of a specified file in a directory %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = filetype_check_dir(p, filename) if ~isempty(p) d = dir(p); else d = dir; end res = any(strcmp(filename,{d.name})); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that checks whether the directory is neuralynx_cds %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = filetype_check_neuralynx_cds(filename) res=false; files=dir(filename); dirlist=files([files.isdir]); % 1) check for a subdirectory with extension .lfp, .mua or .spike haslfp = any(filetype_check_extension({dirlist.name}, 'lfp')); hasmua = any(filetype_check_extension({dirlist.name}, 'mua')); hasspike = any(filetype_check_extension({dirlist.name}, 'spike')); % 2) check for each of the subdirs being a neuralynx_ds if haslfp || hasmua || hasspike sel=find(filetype_check_extension({dirlist.name}, 'lfp')+... filetype_check_extension({dirlist.name}, 'mua')+... filetype_check_extension({dirlist.name}, 'spike')); neuralynxdirs=cell(1,length(sel)); for n=1:length(sel) neuralynxdirs{n}=fullfile(filename, dirlist(sel(n)).name); end res=any(ft_filetype(neuralynxdirs, 'neuralynx_ds')); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that checks whether the file contains only ascii characters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = filetype_check_ascii(filename, len) % See http://en.wikipedia.org/wiki/ASCII if exist(filename, 'file') fid = fopen(filename, 'rt'); bin = fread(fid, len, 'uint8=>uint8'); fclose(fid); printable = bin>31 & bin<127; % the printable characters, represent letters, digits, punctuation marks, and a few miscellaneous symbols special = bin==10 | bin==13 | bin==11; % line feed, form feed, tab res = all(printable | special); else % always return true if the file does not (yet) exist, this is important % for determining the format to which data should be written res = 1; end
github
lcnbeapp/beapp-master
getdimord.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/getdimord.m
20,107
utf_8
706f4f45a5d4ae7535c204b8c010f76b
function dimord = getdimord(data, field, varargin) % GETDIMORD % % Use as % dimord = getdimord(data, field) % % See also GETDIMSIZ, GETDATFIELD if ~isfield(data, field) && isfield(data, 'avg') && isfield(data.avg, field) field = ['avg.' field]; elseif ~isfield(data, field) && isfield(data, 'trial') && isfield(data.trial, field) field = ['trial.' field]; elseif ~isfield(data, field) error('field "%s" not present in data', field); end if strncmp(field, 'avg.', 4) prefix = ''; field = field(5:end); % strip the avg data.(field) = data.avg.(field); % copy the avg into the main structure data = rmfield(data, 'avg'); elseif strncmp(field, 'trial.', 6) prefix = '(rpt)_'; field = field(7:end); % strip the trial data.(field) = data.trial(1).(field); % copy the first trial into the main structure data = rmfield(data, 'trial'); else prefix = ''; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 1: the specific dimord is simply present %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(data, [field 'dimord']) dimord = data.([field 'dimord']); return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if not present, we need some additional information about the data strucure %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nan means that the value is not known and might remain unknown % inf means that the value is not known but should be known ntime = inf; nfreq = inf; nchan = inf; nchancmb = inf; nsubj = nan; nrpt = nan; nrpttap = nan; npos = inf; nori = nan; % this will be 3 in many cases ntopochan = inf; nspike = inf; % this is only for the first spike channel nlag = nan; ndim1 = nan; ndim2 = nan; ndim3 = nan; % use an anonymous function assign = @(var, val) assignin('caller', var, val); % it is possible to pass additional ATTEMPTs such as nrpt, nrpttap, etc for i=1:2:length(varargin) assign(varargin{i}, varargin{i+1}); end % try to determine the size of each possible dimension in the data if isfield(data, 'label') nchan = length(data.label); end if isfield(data, 'labelcmb') nchancmb = size(data.labelcmb, 1); end if isfield(data, 'time') if iscell(data.time) && ~isempty(data.time) tmp = getdimsiz(data, 'time'); ntime = tmp(3); % raw data may contain variable length trials else ntime = length(data.time); end end if isfield(data, 'freq') nfreq = length(data.freq); end if isfield(data, 'trial') && ft_datatype(data, 'raw') nrpt = length(data.trial); end if isfield(data, 'trialtime') && ft_datatype(data, 'spike') nrpt = size(data.trialtime,1); end if isfield(data, 'cumtapcnt') nrpt = size(data.cumtapcnt,1); if numel(data.cumtapcnt)==length(data.cumtapcnt) % it is a vector, hence it only represents repetitions nrpttap = sum(data.cumtapcnt); else % it is a matrix, hence it is repetitions by frequencies % this happens after mtmconvol with keeptrials nrpttap = sum(data.cumtapcnt,2); if any(nrpttap~=nrpttap(1)) warning('unexpected variation of the number of tapers over trials') nrpttap = nan; else nrpttap = nrpttap(1); end end end if isfield(data, 'pos') npos = size(data.pos,1); elseif isfield(data, 'dim') npos = prod(data.dim); end if isfield(data, 'dim') ndim1 = data.dim(1); ndim2 = data.dim(2); ndim3 = data.dim(3); end if isfield(data, 'csdlabel') % this is used in PCC beamformers if length(data.csdlabel)==npos % each position has its own labels len = cellfun(@numel, data.csdlabel); len = len(len~=0); if all(len==len(1)) % they all have the same length nori = len(1); end else % one list of labels for all positions nori = length(data.csdlabel); end elseif isfinite(npos) % assume that there are three dipole orientations per source nori = 3; end if isfield(data, 'topolabel') % this is used in ICA and PCA decompositions ntopochan = length(data.topolabel); end if isfield(data, 'timestamp') && iscell(data.timestamp) nspike = length(data.timestamp{1}); % spike data: only for the first channel end if ft_datatype(data, 'mvar') && isfield(data, 'coeffs') nlag = size(data.coeffs,3); end % determine the size of the actual data datsiz = getdimsiz(data, field); tok = {'subj' 'rpt' 'rpttap' 'chan' 'chancmb' 'freq' 'time' 'pos' 'ori' 'topochan' 'lag' 'dim1' 'dim2' 'dim3'}; siz = [nsubj nrpt nrpttap nchan nchancmb nfreq ntime npos nori ntopochan nlag ndim1 ndim2 ndim3]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 2: a general dimord is present and might apply %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isfield(data, 'dimord') dimtok = tokenize(data.dimord, '_'); if length(dimtok)>length(datsiz) && check_trailingdimsunitlength(data, dimtok((length(datsiz)+1):end)) % add the trailing singleton dimensions to datsiz, if needed datsiz = [datsiz ones(1,max(0,length(dimtok)-length(datsiz)))]; end if length(dimtok)==length(datsiz) || (length(dimtok)==(length(datsiz)-1) && datsiz(end)==1) success = false(size(dimtok)); for i=1:length(dimtok) sel = strcmp(tok, dimtok{i}); if any(sel) && datsiz(i)==siz(sel) success(i) = true; elseif strcmp(dimtok{i}, 'subj') % the number of subjects cannot be determined, and will be indicated as nan success(i) = true; elseif strcmp(dimtok{i}, 'rpt') % the number of trials is hard to determine, and might be indicated as nan success(i) = true; end end % for if all(success) dimord = data.dimord; return end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 3: look at the size of some common fields that are known %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch field % the logic for this code is to first check whether the size of a field % has an exact match to a potential dimensionality, if not, check for a % partial match (ignoring nans) % note that the case for a cell dimension (typically pos) is handled at % the end of this section case {'pos'} if isequalwithoutnans(datsiz, [npos 3]) dimord = 'pos_unknown'; end case {'individual'} if isequalwithoutnans(datsiz, [nsubj nchan ntime]) dimord = 'subj_chan_time'; end case {'avg' 'var' 'dof'} if isequal(datsiz, [nrpt nchan ntime]) dimord = 'rpt_chan_time'; elseif isequal(datsiz, [nchan ntime]) dimord = 'chan_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan ntime]) dimord = 'rpt_chan_time'; elseif isequalwithoutnans(datsiz, [nchan ntime]) dimord = 'chan_time'; end case {'powspctrm' 'fourierspctrm'} if isequal(datsiz, [nrpt nchan nfreq ntime]) dimord = 'rpt_chan_freq_time'; elseif isequal(datsiz, [nrpt nchan nfreq]) dimord = 'rpt_chan_freq'; elseif isequal(datsiz, [nchan nfreq ntime]) dimord = 'chan_freq_time'; elseif isequal(datsiz, [nchan nfreq]) dimord = 'chan_freq'; elseif isequalwithoutnans(datsiz, [nrpt nchan nfreq ntime]) dimord = 'rpt_chan_freq_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan nfreq]) dimord = 'rpt_chan_freq'; elseif isequalwithoutnans(datsiz, [nchan nfreq ntime]) dimord = 'chan_freq_time'; elseif isequalwithoutnans(datsiz, [nchan nfreq]) dimord = 'chan_freq'; end case {'crsspctrm' 'cohspctrm'} if isequal(datsiz, [nrpt nchancmb nfreq ntime]) dimord = 'rpt_chancmb_freq_time'; elseif isequal(datsiz, [nrpt nchancmb nfreq]) dimord = 'rpt_chancmb_freq'; elseif isequal(datsiz, [nchancmb nfreq ntime]) dimord = 'chancmb_freq_time'; elseif isequal(datsiz, [nchancmb nfreq]) dimord = 'chancmb_freq'; elseif isequal(datsiz, [nrpt nchan nchan nfreq ntime]) dimord = 'rpt_chan_chan_freq_time'; elseif isequal(datsiz, [nrpt nchan nchan nfreq]) dimord = 'rpt_chan_chan_freq'; elseif isequal(datsiz, [nchan nchan nfreq ntime]) dimord = 'chan_chan_freq_time'; elseif isequal(datsiz, [nchan nchan nfreq]) dimord = 'chan_chan_freq'; elseif isequal(datsiz, [npos nori]) dimord = 'pos_ori'; elseif isequal(datsiz, [npos 1]) dimord = 'pos'; elseif isequalwithoutnans(datsiz, [nrpt nchancmb nfreq ntime]) dimord = 'rpt_chancmb_freq_time'; elseif isequalwithoutnans(datsiz, [nrpt nchancmb nfreq]) dimord = 'rpt_chancmb_freq'; elseif isequalwithoutnans(datsiz, [nchancmb nfreq ntime]) dimord = 'chancmb_freq_time'; elseif isequalwithoutnans(datsiz, [nchancmb nfreq]) dimord = 'chancmb_freq'; elseif isequalwithoutnans(datsiz, [nrpt nchan nchan nfreq ntime]) dimord = 'rpt_chan_chan_freq_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan nchan nfreq]) dimord = 'rpt_chan_chan_freq'; elseif isequalwithoutnans(datsiz, [nchan nchan nfreq ntime]) dimord = 'chan_chan_freq_time'; elseif isequalwithoutnans(datsiz, [nchan nchan nfreq]) dimord = 'chan_chan_freq'; elseif isequalwithoutnans(datsiz, [npos nori]) dimord = 'pos_ori'; elseif isequalwithoutnans(datsiz, [npos 1]) dimord = 'pos'; end case {'cov' 'coh' 'csd' 'noisecov' 'noisecsd'} % these occur in timelock and in source structures if isequal(datsiz, [nrpt nchan nchan]) dimord = 'rpt_chan_chan'; elseif isequal(datsiz, [nchan nchan]) dimord = 'chan_chan'; elseif isequal(datsiz, [npos nori nori]) dimord = 'pos_ori_ori'; elseif isequal(datsiz, [npos nrpt nori nori]) dimord = 'pos_rpt_ori_ori'; elseif isequalwithoutnans(datsiz, [nrpt nchan nchan]) dimord = 'rpt_chan_chan'; elseif isequalwithoutnans(datsiz, [nchan nchan]) dimord = 'chan_chan'; elseif isequalwithoutnans(datsiz, [npos nori nori]) dimord = 'pos_ori_ori'; elseif isequalwithoutnans(datsiz, [npos nrpt nori nori]) dimord = 'pos_rpt_ori_ori'; end case {'tf'} if isequal(datsiz, [npos nfreq ntime]) dimord = 'pos_freq_time'; end case {'pow'} if isequal(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequal(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequal(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequal(datsiz, [nrpt npos ntime]) dimord = 'rpt_pos_time'; elseif isequal(datsiz, [nrpt npos nfreq]) dimord = 'rpt_pos_freq'; elseif isequal(datsiz, [npos 1]) % in case there are no repetitions dimord = 'pos'; elseif isequalwithoutnans(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequalwithoutnans(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequalwithoutnans(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequalwithoutnans(datsiz, [nrpt npos ntime]) dimord = 'rpt_pos_time'; elseif isequalwithoutnans(datsiz, [nrpt npos nfreq]) dimord = 'rpt_pos_freq'; end case {'mom','itc','aa','stat','pval','statitc','pitc'} if isequal(datsiz, [npos nori nrpt]) dimord = 'pos_ori_rpt'; elseif isequal(datsiz, [npos nori ntime]) dimord = 'pos_ori_time'; elseif isequal(datsiz, [npos nori nfreq]) dimord = 'pos_ori_nfreq'; elseif isequal(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequal(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequal(datsiz, [npos 3]) dimord = 'pos_ori'; elseif isequal(datsiz, [npos 1]) dimord = 'pos'; elseif isequal(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequalwithoutnans(datsiz, [npos nori nrpt]) dimord = 'pos_ori_rpt'; elseif isequalwithoutnans(datsiz, [npos nori ntime]) dimord = 'pos_ori_time'; elseif isequalwithoutnans(datsiz, [npos nori nfreq]) dimord = 'pos_ori_nfreq'; elseif isequalwithoutnans(datsiz, [npos ntime]) dimord = 'pos_time'; elseif isequalwithoutnans(datsiz, [npos nfreq]) dimord = 'pos_freq'; elseif isequalwithoutnans(datsiz, [npos 3]) dimord = 'pos_ori'; elseif isequalwithoutnans(datsiz, [npos 1]) dimord = 'pos'; elseif isequalwithoutnans(datsiz, [npos nrpt]) dimord = 'pos_rpt'; elseif isequalwithoutnans(datsiz, [npos nrpt nori ntime]) dimord = 'pos_rpt_ori_time'; elseif isequalwithoutnans(datsiz, [npos nrpt 1 ntime]) dimord = 'pos_rpt_ori_time'; elseif isequal(datsiz, [npos nfreq ntime]) dimord = 'pos_freq_time'; end case {'filter'} if isequalwithoutnans(datsiz, [npos nori nchan]) || (isequal(datsiz([1 2]), [npos nori]) && isinf(nchan)) dimord = 'pos_ori_chan'; end case {'leadfield'} if isequalwithoutnans(datsiz, [npos nchan nori]) || (isequal(datsiz([1 3]), [npos nori]) && isinf(nchan)) dimord = 'pos_chan_ori'; end case {'ori' 'eta'} if isequal(datsiz, [npos nori]) || isequal(datsiz, [npos 3]) dimord = 'pos_ori'; end case {'csdlabel'} if isequal(datsiz, [npos nori]) || isequal(datsiz, [npos 3]) dimord = 'pos_ori'; end case {'trial'} if ~iscell(data.(field)) && isequalwithoutnans(datsiz, [nrpt nchan ntime]) dimord = 'rpt_chan_time'; elseif isequalwithoutnans(datsiz, [nrpt nchan ntime]) dimord = '{rpt}_chan_time'; elseif isequalwithoutnans(datsiz, [nchan nspike]) || isequalwithoutnans(datsiz, [nchan 1 nspike]) dimord = '{chan}_spike'; end case {'sampleinfo' 'trialinfo' 'trialtime'} if isequalwithoutnans(datsiz, [nrpt nan]) dimord = 'rpt_other'; end case {'cumtapcnt' 'cumsumcnt'} if isequalwithoutnans(datsiz, [nrpt nan]) dimord = 'rpt_other'; end case {'topo'} if isequalwithoutnans(datsiz, [ntopochan nchan]) dimord = 'topochan_chan'; end case {'unmixing'} if isequalwithoutnans(datsiz, [nchan ntopochan]) dimord = 'chan_topochan'; end case {'inside'} if isequalwithoutnans(datsiz, [npos]) dimord = 'pos'; end case {'timestamp' 'time'} if ft_datatype(data, 'spike') && iscell(data.(field)) && datsiz(1)==nchan dimord = '{chan}_spike'; elseif ft_datatype(data, 'raw') && iscell(data.(field)) && datsiz(1)==nrpt dimord = '{rpt}_time'; elseif isvector(data.(field)) && isequal(datsiz, [1 ntime ones(1,numel(datsiz)-2)]) dimord = 'time'; end case {'freq'} if isvector(data.(field)) && isequal(datsiz, [1 nfreq]) dimord = 'freq'; end otherwise if isfield(data, 'dim') && isequal(datsiz, data.dim) dimord = 'dim1_dim2_dim3'; end end % switch field % deal with possible first pos which is a cell if exist('dimord', 'var') && strcmp(dimord(1:3), 'pos') && iscell(data.(field)) dimord = ['{pos}' dimord(4:end)]; end if ~exist('dimord', 'var') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 4: there is only one way that the dimensions can be interpreted %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% dimtok = cell(size(datsiz)); for i=1:length(datsiz) sel = find(siz==datsiz(i)); if length(sel)==1 % there is exactly one corresponding dimension dimtok{i} = tok{sel}; else % there are zero or multiple corresponding dimensions dimtok{i} = []; end end if all(~cellfun(@isempty, dimtok)) if iscell(data.(field)) dimtok{1} = ['{' dimtok{1} '}']; end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); return end end % if dimord does not exist if ~exist('dimord', 'var') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 5: compare the size with the known size of each dimension %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% sel = ~isnan(siz) & ~isinf(siz); % nan means that the value is not known and might remain unknown % inf means that the value is not known and but should be known if length(unique(siz(sel)))==length(siz(sel)) % this should only be done if there is no chance of confusing dimensions dimtok = cell(size(datsiz)); dimtok(datsiz==npos) = {'pos'}; dimtok(datsiz==nori) = {'ori'}; dimtok(datsiz==nrpttap) = {'rpttap'}; dimtok(datsiz==nrpt) = {'rpt'}; dimtok(datsiz==nsubj) = {'subj'}; dimtok(datsiz==nchancmb) = {'chancmb'}; dimtok(datsiz==nchan) = {'chan'}; dimtok(datsiz==nfreq) = {'freq'}; dimtok(datsiz==ntime) = {'time'}; dimtok(datsiz==ndim1) = {'dim1'}; dimtok(datsiz==ndim2) = {'dim2'}; dimtok(datsiz==ndim3) = {'dim3'}; if isempty(dimtok{end}) && datsiz(end)==1 % remove the unknown trailing singleton dimension dimtok = dimtok(1:end-1); elseif isequal(dimtok{1}, 'pos') && isempty(dimtok{2}) && datsiz(2)==1 % remove the unknown leading singleton dimension dimtok(2) = []; end if all(~cellfun(@isempty, dimtok)) if iscell(data.(field)) dimtok{1} = ['{' dimtok{1} '}']; end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); return end end end % if dimord does not exist if ~exist('dimord', 'var') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % ATTEMPT 6: check whether it is a 3-D volume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if isequal(datsiz, [ndim1 ndim2 ndim3]) dimord = 'dim1_dim2_dim3'; end end % if dimord does not exist %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % FINAL RESORT: return "unknown" for all unknown dimensions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist('dimord', 'var') % this should not happen % if it does, it might help in diagnosis to have a very informative warning message % since there have been problems with trials not being selected correctly due to the warning going unnoticed % it is better to throw an error than a warning warning('could not determine dimord of "%s" in the following data', field) disp(data); dimtok(cellfun(@isempty, dimtok)) = {'unknown'}; if all(~cellfun(@isempty, dimtok)) if iscell(data.(field)) dimtok{1} = ['{' dimtok{1} '}']; end dimord = sprintf('%s_', dimtok{:}); dimord = dimord(1:end-1); end end % add '(rpt)' in case of source.trial dimord = [prefix dimord]; end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ok = isequalwithoutnans(a, b) % this is *only* used to compare matrix sizes, so we can ignore any singleton last dimension numdiff = numel(b)-numel(a); if numdiff > 0 % assume singleton dimensions missing in a a = [a(:); ones(numdiff, 1)]; b = b(:); elseif numdiff < 0 % assume singleton dimensions missing in b b = [b(:); ones(abs(numdiff), 1)]; a = a(:); end c = ~isnan(a(:)) & ~isnan(b(:)); ok = isequal(a(c), b(c)); end % function isequalwithoutnans %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function ok = check_trailingdimsunitlength(data, dimtok) ok = false; for k = 1:numel(dimtok) switch dimtok{k} case 'chan' ok = numel(data.label)==1; otherwise if isfield(data, dimtok{k}); % check whether field exists ok = numel(data.(dimtok{k}))==1; end; end if ok, break; end end end % function check_trailingdimsunitlength
github
lcnbeapp/beapp-master
read_mff_bin.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/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
lcnbeapp/beapp-master
ft_datatype_sens.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/ft_datatype_sens.m
22,743
utf_8
fab01996ef9a98c643827fb2767fbaf3
function [sens] = ft_datatype_sens(sens, varargin) % FT_DATATYPE_SENS describes the FieldTrip structure that represents an EEG, ECoG, or % MEG sensor array. This structure is commonly called "elec" for EEG, "grad" for MEG, % "opto" for NIRS, or general "sens" for either one. % % For all sensor types a distinction should be made between the channel (i.e. the % output of the transducer that is A/D converted) and the sensor, which may have some % spatial extent. E.g. with EEG you can have a bipolar channel, where the position of % the channel can be represented as in between the position of the two electrodes. % % The structure for MEG gradiometers and/or magnetometers contains % sens.label = Mx1 cell-array with channel labels % sens.chanpos = Mx3 matrix with channel positions % sens.chanori = Mx3 matrix with channel orientations, used for synthetic planar gradient computation % sens.tra = MxN matrix to combine coils into channels % sens.coilpos = Nx3 matrix with coil positions % sens.coilori = Nx3 matrix with coil orientations % sens.balance = structure containing info about the balancing, See FT_APPLY_MONTAGE % and optionally % sens.chanposold = Mx3 matrix with original channel positions (in case % sens.chanpos has been updated to contain NaNs, e.g. % after ft_componentanalysis) % sens.chanoriold = Mx3 matrix with original channel orientations % sens.labelold = Mx1 cell-array with original channel labels % % The structure for EEG or ECoG channels contains % sens.label = Mx1 cell-array with channel labels % sens.elecpos = Nx3 matrix with electrode positions % sens.chanpos = Mx3 matrix with channel positions (often the same as electrode positions) % sens.tra = MxN matrix to combine electrodes into channels % In case sens.tra is not present in the EEG sensor array, the channels % are assumed to be average referenced. % % The structure for NIRS channels contains % sens.optopos = contains information about the position of the optodes % sens.optotype = contains information about the type of optode (receiver or transmitter) % sens.chanpos = contains information about the position of the channels (i.e. average of optopos) % sens.tra = NxC matrix, boolean, contains information about how receiver and transmitter form channels % sens.wavelength = 1xM vector of all wavelengths that were used % sens.transmits = NxM matrix, boolean, where N is the number of optodes and M the number of wavelengths per transmitter. Specifies what optode is transmitting at what wavelength (or nothing at all, which indicates that it is a receiver) % sens.laserstrength = 1xM vector of the strength of the emitted light of the lasers % % The following fields apply to MEG and EEG % sens.chantype = Mx1 cell-array with the type of the channel, see FT_CHANTYPE % sens.chanunit = Mx1 cell-array with the units of the channel signal, e.g. 'V', 'fT' or 'T/cm', see FT_CHANUNIT % % The following fields are optional % sens.type = string with the type of acquisition system, see FT_SENSTYPE % sens.fid = structure with fiducial information % % Historical fields: % pnt, pos, ori, pnt1, pnt2 % % Revision history: % (2016/latest) The chantype and chanunit have become required fields. % Original channel details are specified with the suffix "old" rather than "org". % All numeric values are represented in double precision. % It is possible to convert the amplitude and distance units (e.g. from T to fT and % from m to mm) and it is possible to express planar and axial gradiometer channels % either in units of amplitude or in units of amplitude/distance (i.e. proper % gradient). % % (2011v2) The chantype and chanunit have been added for MEG. % % (2011v1) To facilitate determining the position of channels (e.g. for plotting) % in case of balanced MEG or bipolar EEG, an explicit distinction has been made % between chanpos+chanori and coilpos+coilori (for MEG) and chanpos and elecpos % (for EEG). The pnt and ori fields are removed % % (2010) Added support for bipolar or otherwise more complex linear combinations % of EEG electrodes using sens.tra, similar to MEG. % % (2009) Noice reduction has been added for MEG systems in the balance field. % % (2006) The optional fields sens.type and sens.unit were added. % % (2003) The initial version was defined, which looked like this for EEG % sens.pnt = Mx3 matrix with electrode positions % sens.label = Mx1 cell-array with channel labels % and like this for MEG % sens.pnt = Nx3 matrix with coil positions % sens.ori = Nx3 matrix with coil orientations % sens.tra = MxN matrix to combine coils into channels % sens.label = Mx1 cell-array with channel labels % % See also FT_READ_SENS, FT_SENSTYPE, FT_CHANTYPE, FT_APPLY_MONTAGE, CTF2GRAD, FIF2GRAD, % BTI2GRAD, YOKOGAWA2GRAD, ITAB2GRAD % Copyright (C) 2011-2016, Robert Oostenveld & Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ % undocumented options for the 2016 format % amplitude = string, can be 'T' or 'fT' % distance = string, can be 'm', 'cm' or 'mm' % scaling = string, can be 'amplitude' or 'amplitude/distance' % these are for remembering the type on subsequent calls with the same input arguments persistent previous_argin previous_argout current_argin = [{sens} varargin]; if isequal(current_argin, previous_argin) % don't do the whole cheking again, but return the previous output from cache sens = previous_argout{1}; return end % get the optional input arguments, which should be specified as key-value pairs version = ft_getopt(varargin, 'version', 'latest'); amplitude = ft_getopt(varargin, 'amplitude'); % should be 'V' 'uV' 'T' 'mT' 'uT' 'nT' 'pT' 'fT' distance = ft_getopt(varargin, 'distance'); % should be 'm' 'dm' 'cm' 'mm' scaling = ft_getopt(varargin, 'scaling'); % should be 'amplitude' or 'amplitude/distance', the default depends on the senstype if ~isempty(amplitude) && ~any(strcmp(amplitude, {'V' 'uV' 'T' 'mT' 'uT' 'nT' 'pT' 'fT'})) error('unsupported unit of amplitude "%s"', amplitude); end if ~isempty(distance) && ~any(strcmp(distance, {'m' 'dm' 'cm' 'mm'})) error('unsupported unit of distance "%s"', distance); end if strcmp(version, 'latest') version = '2016'; end if isempty(sens) return; end % this is needed further down nchan = length(sens.label); % there are many cases which deal with either eeg or meg ismeg = ft_senstype(sens, 'meg'); switch version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case '2016' % update it to the previous standard version sens = ft_datatype_sens(sens, 'version', '2011v2'); % ensure that all numbers are represented in double precision sens = ft_struct2double(sens); % use "old/new" rather than "org/new" if isfield(sens, 'labelorg') sens.labelold = sens.labelorg; sens = rmfield(sens, 'labelorg'); end if isfield(sens, 'chantypeorg') sens.chantypeold = sens.chantypeorg; sens = rmfield(sens, 'chantypeorg'); end if isfield(sens, 'chanuniteorg') sens.chanunitold = sens.chanunitorg; sens = rmfield(sens, 'chanunitorg'); end if isfield(sens, 'chanposorg') sens.chanposold = sens.chanposorg; sens = rmfield(sens, 'chanposorg'); end if isfield(sens, 'chanoriorg') sens.chanoriold = sens.chanoriorg; sens = rmfield(sens, 'chanoriorg'); end % in version 2011v2 this was optional, now it is required if ~isfield(sens, 'chantype') || all(strcmp(sens.chantype, 'unknown')) sens.chantype = ft_chantype(sens); end % in version 2011v2 this was optional, now it is required if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown')) sens.chanunit = ft_chanunit(sens); end if ~isempty(distance) % update the units of distance, this also updates the tra matrix sens = ft_convert_units(sens, distance); else % determine the default, this may be needed to set the scaling distance = sens.unit; end if ~isempty(amplitude) && isfield(sens, 'tra') % update the tra matrix for the units of amplitude, this ensures that % the leadfield values remain consistent with the units for i=1:nchan if ~isempty(regexp(sens.chanunit{i}, 'm$', 'once')) % this channel is expressed as amplitude per distance sens.tra(i,:) = sens.tra(i,:) * ft_scalingfactor(sens.chanunit{i}, [amplitude '/' distance]); sens.chanunit{i} = [amplitude '/' distance]; elseif ~isempty(regexp(sens.chanunit{i}, '[T|V]$', 'once')) % this channel is expressed as amplitude sens.tra(i,:) = sens.tra(i,:) * ft_scalingfactor(sens.chanunit{i}, amplitude); sens.chanunit{i} = amplitude; else error('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i); end end else % determine the default amplityde, this may be needed to set the scaling if any(~cellfun(@isempty, regexp(sens.chanunit, '^T'))) % one of the channel units starts with T amplitude = 'T'; elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^fT'))) % one of the channel units starts with fT amplitude = 'fT'; elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^V'))) % one of the channel units starts with V amplitude = 'V'; elseif any(~cellfun(@isempty, regexp(sens.chanunit, '^uV'))) % one of the channel units starts with uV amplitude = 'uV'; else % this unknown amplitude will cause a problem if the scaling needs to be changed between amplitude and amplitude/distance amplitude = 'unknown'; end end % perform some sanity checks if ismeg sel_m = ~cellfun(@isempty, regexp(sens.chanunit, '/m$')); sel_dm = ~cellfun(@isempty, regexp(sens.chanunit, '/dm$')); sel_cm = ~cellfun(@isempty, regexp(sens.chanunit, '/cm$')); sel_mm = ~cellfun(@isempty, regexp(sens.chanunit, '/mm$')); if strcmp(sens.unit, 'm') && (any(sel_dm) || any(sel_cm) || any(sel_mm)) error('inconsistent units in input gradiometer'); elseif strcmp(sens.unit, 'dm') && (any(sel_m) || any(sel_cm) || any(sel_mm)) error('inconsistent units in input gradiometer'); elseif strcmp(sens.unit, 'cm') && (any(sel_m) || any(sel_dm) || any(sel_mm)) error('inconsistent units in input gradiometer'); elseif strcmp(sens.unit, 'mm') && (any(sel_m) || any(sel_dm) || any(sel_cm)) error('inconsistent units in input gradiometer'); end % the default should be amplitude/distance for neuromag and amplitude for all others if isempty(scaling) if ft_senstype(sens, 'neuromag') scaling = 'amplitude/distance'; elseif ft_senstype(sens, 'yokogawa440') warning('asuming that the default scaling should be amplitude rather than amplitude/distance'); scaling = 'amplitude'; else scaling = 'amplitude'; end end % update the gradiometer scaling if strcmp(scaling, 'amplitude') && isfield(sens, 'tra') for i=1:nchan if strcmp(sens.chanunit{i}, [amplitude '/' distance]) % this channel is expressed as amplitude per distance coil = find(abs(sens.tra(i,:))~=0); if length(coil)~=2 error('unexpected number of coils contributing to channel %d', i); end baseline = norm(sens.coilpos(coil(1),:) - sens.coilpos(coil(2),:)); sens.tra(i,:) = sens.tra(i,:)*baseline; % scale with the baseline distance sens.chanunit{i} = amplitude; elseif strcmp(sens.chanunit{i}, amplitude) % no conversion needed else % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3144 ft_warning(sprintf('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i)); end % if end % for elseif strcmp(scaling, 'amplitude/distance') && isfield(sens, 'tra') for i=1:nchan if strcmp(sens.chanunit{i}, amplitude) % this channel is expressed as amplitude coil = find(abs(sens.tra(i,:))~=0); if length(coil)==1 || strcmp(sens.chantype{i}, 'megmag') % this is a magnetometer channel, no conversion needed continue elseif length(coil)~=2 error('unexpected number of coils (%d) contributing to channel %s (%d)', length(coil), sens.label{i}, i); end baseline = norm(sens.coilpos(coil(1),:) - sens.coilpos(coil(2),:)); sens.tra(i,:) = sens.tra(i,:)/baseline; % scale with the baseline distance sens.chanunit{i} = [amplitude '/' distance]; elseif strcmp(sens.chanunit{i}, [amplitude '/' distance]) % no conversion needed else % see http://bugzilla.fieldtriptoolbox.org/show_bug.cgi?id=3144 ft_warning(sprintf('unexpected channel unit "%s" in channel %d', sens.chanunit{i}, i)); end % if end % for end % if strcmp scaling else sel_m = ~cellfun(@isempty, regexp(sens.chanunit, '/m$')); sel_dm = ~cellfun(@isempty, regexp(sens.chanunit, '/dm$')); sel_cm = ~cellfun(@isempty, regexp(sens.chanunit, '/cm$')); sel_mm = ~cellfun(@isempty, regexp(sens.chanunit, '/mm$')); if any(sel_m | sel_dm | sel_cm | sel_mm) error('scaling of amplitude/distance has not been considered yet for EEG'); end end % if iseeg or ismeg %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case '2011v2' if ~isempty(amplitude) || ~isempty(distance) || ~isempty(scaling) warning('amplitude, distance and scaling are not supported for version "%s"', version); end % This speeds up subsequent calls to ft_senstype and channelposition. % However, if it is not more precise than MEG or EEG, don't keep it in % the output (see further down). if ~isfield(sens, 'type') sens.type = ft_senstype(sens); end if isfield(sens, 'pnt') if ismeg % sensor description is a MEG sensor-array, containing oriented coils sens.coilpos = sens.pnt; sens = rmfield(sens, 'pnt'); sens.coilori = sens.ori; sens = rmfield(sens, 'ori'); else % sensor description is something else, EEG/ECoG etc sens.elecpos = sens.pnt; sens = rmfield(sens, 'pnt'); end end if ~isfield(sens, 'chanpos') if ismeg % sensor description is a MEG sensor-array, containing oriented coils [chanpos, chanori, lab] = channelposition(sens); % the channel order can be different in the two representations [selsens, selpos] = match_str(sens.label, lab); sens.chanpos = nan(length(sens.label), 3); sens.chanori = nan(length(sens.label), 3); % insert the determined position/orientation on the appropriate rows sens.chanpos(selsens,:) = chanpos(selpos,:); sens.chanori(selsens,:) = chanori(selpos,:); if length(selsens)~=length(sens.label) warning('cannot determine the position and orientation for all channels'); end else % sensor description is something else, EEG/ECoG etc % note that chanori will be all NaNs [chanpos, chanori, lab] = channelposition(sens); % the channel order can be different in the two representations [selsens, selpos] = match_str(sens.label, lab); sens.chanpos = nan(length(sens.label), 3); % insert the determined position/orientation on the appropriate rows sens.chanpos(selsens,:) = chanpos(selpos,:); if length(selsens)~=length(sens.label) warning('cannot determine the position and orientation for all channels'); end end end if ~isfield(sens, 'chantype') || all(strcmp(sens.chantype, 'unknown')) if ismeg sens.chantype = ft_chantype(sens); else % for EEG it is not required end end if ~isfield(sens, 'unit') % this should be done prior to calling ft_chanunit, since ft_chanunit uses this for planar neuromag channels sens = ft_convert_units(sens); end if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown')) if ismeg sens.chanunit = ft_chanunit(sens); else % for EEG it is not required end end if any(strcmp(sens.type, {'meg', 'eeg', 'magnetometer', 'electrode', 'unknown'})) % this is not sufficiently informative, so better remove it % see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=1806 sens = rmfield(sens, 'type'); end if size(sens.chanpos,1)~=length(sens.label) || ... isfield(sens, 'tra') && size(sens.tra,1)~=length(sens.label) || ... isfield(sens, 'tra') && isfield(sens, 'elecpos') && size(sens.tra,2)~=size(sens.elecpos,1) || ... isfield(sens, 'tra') && isfield(sens, 'coilpos') && size(sens.tra,2)~=size(sens.coilpos,1) || ... isfield(sens, 'tra') && isfield(sens, 'coilori') && size(sens.tra,2)~=size(sens.coilori,1) || ... isfield(sens, 'chanpos') && size(sens.chanpos,1)~=length(sens.label) || ... isfield(sens, 'chanori') && size(sens.chanori,1)~=length(sens.label) error('inconsistent number of channels in sensor description'); end if ismeg % ensure that the magnetometer/gradiometer balancing is specified if ~isfield(sens, 'balance') || ~isfield(sens.balance, 'current') sens.balance.current = 'none'; end % try to add the chantype and chanunit to the CTF G1BR montage if isfield(sens, 'balance') && isfield(sens.balance, 'G1BR') && ~isfield(sens.balance.G1BR, 'chantype') sens.balance.G1BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G1BR.labelorg)); sens.balance.G1BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G1BR.labelorg)); sens.balance.G1BR.chantypenew = repmat({'unknown'}, size(sens.balance.G1BR.labelnew)); sens.balance.G1BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G1BR.labelnew)); % the synthetic gradient montage does not fundamentally change the chantype or chanunit [sel1, sel2] = match_str(sens.balance.G1BR.labelorg, sens.label); sens.balance.G1BR.chantypeorg(sel1) = sens.chantype(sel2); sens.balance.G1BR.chanunitorg(sel1) = sens.chanunit(sel2); [sel1, sel2] = match_str(sens.balance.G1BR.labelnew, sens.label); sens.balance.G1BR.chantypenew(sel1) = sens.chantype(sel2); sens.balance.G1BR.chanunitnew(sel1) = sens.chanunit(sel2); end % idem for G2BR if isfield(sens, 'balance') && isfield(sens.balance, 'G2BR') && ~isfield(sens.balance.G2BR, 'chantype') sens.balance.G2BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G2BR.labelorg)); sens.balance.G2BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G2BR.labelorg)); sens.balance.G2BR.chantypenew = repmat({'unknown'}, size(sens.balance.G2BR.labelnew)); sens.balance.G2BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G2BR.labelnew)); % the synthetic gradient montage does not fundamentally change the chantype or chanunit [sel1, sel2] = match_str(sens.balance.G2BR.labelorg, sens.label); sens.balance.G2BR.chantypeorg(sel1) = sens.chantype(sel2); sens.balance.G2BR.chanunitorg(sel1) = sens.chanunit(sel2); [sel1, sel2] = match_str(sens.balance.G2BR.labelnew, sens.label); sens.balance.G2BR.chantypenew(sel1) = sens.chantype(sel2); sens.balance.G2BR.chanunitnew(sel1) = sens.chanunit(sel2); end % idem for G3BR if isfield(sens, 'balance') && isfield(sens.balance, 'G3BR') && ~isfield(sens.balance.G3BR, 'chantype') sens.balance.G3BR.chantypeorg = repmat({'unknown'}, size(sens.balance.G3BR.labelorg)); sens.balance.G3BR.chanunitorg = repmat({'unknown'}, size(sens.balance.G3BR.labelorg)); sens.balance.G3BR.chantypenew = repmat({'unknown'}, size(sens.balance.G3BR.labelnew)); sens.balance.G3BR.chanunitnew = repmat({'unknown'}, size(sens.balance.G3BR.labelnew)); % the synthetic gradient montage does not fundamentally change the chantype or chanunit [sel1, sel2] = match_str(sens.balance.G3BR.labelorg, sens.label); sens.balance.G3BR.chantypeorg(sel1) = sens.chantype(sel2); sens.balance.G3BR.chanunitorg(sel1) = sens.chanunit(sel2); [sel1, sel2] = match_str(sens.balance.G3BR.labelnew, sens.label); sens.balance.G3BR.chantypenew(sel1) = sens.chantype(sel2); sens.balance.G3BR.chanunitnew(sel1) = sens.chanunit(sel2); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% otherwise error('converting to version %s is not supported', version); end % switch % this makes the display with the "disp" command look better sens = sortfieldnames(sens); % remember the current input and output arguments, so that they can be % reused on a subsequent call in case the same input argument is given current_argout = {sens}; previous_argin = current_argin; previous_argout = current_argout; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function b = sortfieldnames(a) fn = sort(fieldnames(a)); for i=1:numel(fn) b.(fn{i}) = a.(fn{i}); end
github
lcnbeapp/beapp-master
avw_img_read.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/avw_img_read.m
29,185
utf_8
0292be5a490e4b339a1682248d56c5ee
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$ $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$]'; 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
lcnbeapp/beapp-master
read_yokogawa_event.m
.m
beapp-master/Packages/eeglab14_1_2b/plugins/fieldtrip-20160917/fileio/private/read_yokogawa_event.m
7,046
utf_8
df3f4e01815283a7efc0b36ed8e51c29
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.fieldtriptoolbox.org % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id$ event = []; handles = definehandles; % get the options, the default is set below trigindx = ft_getopt(varargin, 'trigindx'); threshold = ft_getopt(varargin, 'threshold'); detectflank = ft_getopt(varargin, 'detectflank'); % ensure that the required toolbox is on the path if ft_hastoolbox('yokogawa_meg_reader'); % read the dataset header hdr = read_yokogawa_header_new(filename); ch_info = hdr.orig.channel_info.channel; type = [ch_info.type]; % determine the trigger channels (if not specified by the user) if isempty(trigindx) trigindx = find(type==handles.TriggerChannel); end % Use the MEG Reader documentation if more detailed support is % required. if hdr.orig.acq_type==handles.AcqTypeEvokedRaw % read the trigger id from all trials event = getYkgwHdrEvent(filename); % use the standard FieldTrip header for trial events % make an event for each trial as defined in the header for i=1:hdr.nTrials event(end+1).type = 'trial'; event(end ).sample = (i-1)*hdr.nSamples + 1; event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; if ~isempty(value) event(end ).value = event(i).code; end end % Use the MEG Reader documentation if more detailed support is required. elseif hdr.orig.acq_type==handles.AcqTypeEvokedAve % make an event for the average event(1).type = 'average'; event(1).sample = 1; event(1).offset = -hdr.nSamplesPre; event(1).duration = hdr.nSamples; elseif hdr.orig.acq_type==handles.AcqTypeContinuousRaw % the data structure does not contain events, but flank detection on the trigger channel might reveal them % this is done below for all formats end elseif ft_hastoolbox('yokogawa'); % read the dataset header hdr = read_yokogawa_header(filename); % determine the trigger channels (if not specified by the user) if isempty(trigindx) trigindx = find(hdr.orig.channel_info(:,2)==handles.TriggerChannel); end if hdr.orig.acq_type==handles.AcqTypeEvokedRaw % read the trigger id from all trials fid = fopen(filename, 'r'); value = GetMeg160TriggerEventM(fid); fclose(fid); % use the standard FieldTrip header for trial events % make an event for each trial as defined in the header for i=1:hdr.nTrials event(end+1).type = 'trial'; event(end ).sample = (i-1)*hdr.nSamples + 1; event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; if ~isempty(value) event(end ).value = value(i); end end elseif hdr.orig.acq_type==handles.AcqTypeEvokedAve % make an event for the average event(1).type = 'average'; event(1).sample = 1; event(1).offset = -hdr.nSamplesPre; event(1).duration = hdr.nSamples; elseif hdr.orig.acq_type==handles.AcqTypeContinuousRaw % the data structure does not contain events, but flank detection on the trigger channel might reveal them % this is done below for all formats end else error('cannot determine, whether Yokogawa toolbox is present'); end % read the trigger channels and detect the flanks if ~isempty(trigindx) trigger = read_trigger(filename, 'header', hdr, 'denoise', false, 'chanindx', trigindx, 'detectflank', detectflank, 'threshold', threshold); % combine the triggers and the other events event = appendevent(event, trigger); end if isempty(event) warning('no triggers were detected, please specify the "trigindx" option'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.eegchannel_ch_no = []; handles.sqd.eegchannel_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];