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
|
lcnhappe/happe-master
|
ft_platform_supports.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/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
|
lcnhappe/happe-master
|
ft_warning.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/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
|
lcnhappe/happe-master
|
ft_hastoolbox.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/ft_hastoolbox.m
| 24,831 |
utf_8
|
43bae19e25ce108f013f1c401e497630
|
function [status] = ft_hastoolbox(toolbox, autoadd, silent)
% FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally
% it will try to determine the path to the toolbox and install it
% automatically.
%
% Use as
% [status] = ft_hastoolbox(toolbox, autoadd, silent)
%
% autoadd = 0 means that it will not be added
% autoadd = 1 means that give an error if it cannot be added
% autoadd = 2 means that give a warning if it cannot be added
% autoadd = 3 means that it remains silent if it cannot be added
%
% silent = 0 means that it will give some feedback about adding the toolbox
% silent = 1 means that it will not give feedback
% Copyright (C) 2005-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$
% this function is called many times in FieldTrip and associated toolboxes
% use efficient handling if the same toolbox has been investigated before
% persistent previous previouspath
%
% if ~isequal(previouspath, path)
% previous = [];
% end
%
% if isempty(previous)
% previous = struct;
% elseif isfield(previous, fixname(toolbox))
% status = previous.(fixname(toolbox));
% return
% end
if isdeployed
% it is not possible to check the presence of functions or change the path in a compiled application
status = 1;
return
end
% this points the user to the website where he/she can download the toolbox
url = {
'AFNI' 'see http://afni.nimh.nih.gov'
'DSS' 'see http://www.cis.hut.fi/projects/dss'
'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab'
'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox'
'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM12' 'see http://www.fil.ion.ucl.ac.uk/spm'
'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd'
'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com'
'BIOSIG' 'see http://biosig.sourceforge.net'
'EEG' 'see http://eeg.sourceforge.net'
'EEGSF' 'see http://eeg.sourceforge.net' % alternative name
'MRI' 'see http://eeg.sourceforge.net' % alternative name
'NEUROSHARE' 'see http://www.neuroshare.org'
'BESA' 'see http://www.besa.de/downloads/matlab/ and get the "BESA MATLAB Readers"'
'MATLAB2BESA' 'see http://www.besa.de/downloads/matlab/ and get the "MATLAB to BESA Export functions"'
'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde'
'YOKOGAWA' 'this is deprecated, please use YOKOGAWA_MEG_READER instead'
'YOKOGAWA_MEG_READER' 'see http://www.yokogawa.com/me/me-login-en.htm'
'BEOWULF' 'see http://robertoostenveld.nl, or contact Robert Oostenveld'
'MENTAT' 'see http://robertoostenveld.nl, or contact Robert Oostenveld'
'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth'
'4D-VERSION' 'contact Christian Wienbruch'
'COMM' 'see http://www.mathworks.com/products/communications'
'SIGNAL' 'see http://www.mathworks.com/products/signal'
'OPTIM' 'see http://www.mathworks.com/products/optim'
'IMAGE' 'see http://www.mathworks.com/products/image' % Mathworks refers to this as IMAGES
'SPLINES' 'see http://www.mathworks.com/products/splines'
'DISTCOMP' 'see http://www.mathworks.nl/products/parallel-computing/'
'COMPILER' 'see http://www.mathworks.com/products/compiler'
'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica'
'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm'
'FILEIO' 'see http://www.fieldtriptoolbox.org'
'PREPROC' 'see http://www.fieldtriptoolbox.org'
'FORWARD' 'see http://www.fieldtriptoolbox.org'
'INVERSE' 'see http://www.fieldtriptoolbox.org'
'SPECEST' 'see http://www.fieldtriptoolbox.org'
'REALTIME' 'see http://www.fieldtriptoolbox.org'
'PLOTTING' 'see http://www.fieldtriptoolbox.org'
'SPIKE' 'see http://www.fieldtriptoolbox.org'
'CONNECTIVITY' 'see http://www.fieldtriptoolbox.org'
'PEER' 'see http://www.fieldtriptoolbox.org'
'PLOTTING' 'see http://www.fieldtriptoolbox.org'
'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne'
'BCI2000' 'see http://bci2000.org'
'NLXNETCOM' 'see http://www.neuralynx.com'
'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external'
'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php'
'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydesaeter'
'BEMCP' 'contact Christophe Phillips'
'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435'
'PRTOOLS' 'see http://www.prtools.org'
'ITAB' 'contact Stefania Della Penna'
'BSMART' 'see http://www.brain-smart.org'
'PEER' 'see http://www.fieldtriptoolbox.org/development/peer'
'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki'
'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page'
'VGRID' 'see http://www.rheinahrcampus.de/~medsim/vgrid/manual.html'
'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS'
'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti'
'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0'
'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab'
'BCT' 'see http://www.brain-connectivity-toolbox.net/'
'CCA' 'see http://www.imt.liu.se/~magnus/cca or contact Magnus Borga'
'EGI_MFF' 'see http://www.egi.com/ or contact either Phan Luu or Colin Davey at EGI'
'TOOLBOX_GRAPH' 'see http://www.mathworks.com/matlabcentral/fileexchange/5355-toolbox-graph or contact Gabriel Peyre'
'NETCDF' 'see http://www.mathworks.com/matlabcentral/fileexchange/15177'
'MYSQL' 'see http://www.mathworks.com/matlabcentral/fileexchange/8663-mysql-database-connector'
'ISO2MESH' 'see http://iso2mesh.sourceforge.net/cgi-bin/index.cgi?Home or contact Qianqian Fang'
'DATAHASH' 'see http://www.mathworks.com/matlabcentral/fileexchange/31272'
'IBTB' 'see http://www.ibtb.org'
'ICASSO' 'see http://www.cis.hut.fi/projects/ica/icasso'
'XUNIT' 'see http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework'
'PLEXON' 'available from http://www.plexon.com/assets/downloads/sdk/ReadingPLXandDDTfilesinMatlab-mexw.zip'
'MISC' 'various functions that were downloaded from http://www.mathworks.com/matlabcentral/fileexchange and elsewhere'
'35625-INFORMATION-THEORY-TOOLBOX' 'see http://www.mathworks.com/matlabcentral/fileexchange/35625-information-theory-toolbox'
'29046-MUTUAL-INFORMATION' 'see http://www.mathworks.com/matlabcentral/fileexchange/35625-information-theory-toolbox'
'14888-MUTUAL-INFORMATION-COMPUTATION' 'see http://www.mathworks.com/matlabcentral/fileexchange/14888-mutual-information-computation'
'PLOT2SVG' 'see http://www.mathworks.com/matlabcentral/fileexchange/7401-scalable-vector-graphics-svg-export-of-figures'
'BRAINSUITE' 'see http://brainsuite.bmap.ucla.edu/processing/additional-tools/'
'BRAINVISA' 'see http://brainvisa.info'
'FILEEXCHANGE' 'see http://www.mathworks.com/matlabcentral/fileexchange/'
'NEURALYNX_V6' 'see http://neuralynx.com/research_software/file_converters_and_utilities/ and take the version from Neuralynx (windows only)'
'NEURALYNX_V3' 'see http://neuralynx.com/research_software/file_converters_and_utilities/ and take the version from Ueli Rutishauser'
'NPMK' 'see https://github.com/BlackrockMicrosystems/NPMK'
'VIDEOMEG' 'see https://github.com/andreyzhd/VideoMEG'
'WAVEFRONT' 'see http://mathworks.com/matlabcentral/fileexchange/27982-wavefront-obj-toolbox'
'NEURONE' 'see http://www.megaemg.com/support/unrestricted-downloads'
};
if nargin<2
% default is not to add the path automatically
autoadd = 0;
end
if nargin<3
% default is not to be silent
silent = 0;
end
% determine whether the toolbox is installed
toolbox = upper(toolbox);
% In case SPM8 or higher not available, allow to use fallback toolbox
fallback_toolbox='';
switch toolbox
case 'AFNI'
dependency={'BrikLoad', 'BrikInfo'};
case 'DSS'
dependency={'denss', 'dss_create_state'};
case 'EEGLAB'
dependency = 'runica';
case 'NWAY'
dependency = 'parafac';
case 'SPM'
dependency = 'spm'; % any version of SPM is fine
case 'SPM99'
dependency = {'spm', get_spm_version()==99};
case 'SPM2'
dependency = {'spm', get_spm_version()==2};
case 'SPM5'
dependency = {'spm', get_spm_version()==5};
case 'SPM8'
dependency = {'spm', get_spm_version()==8};
case 'SPM8UP' % version 8 or later, but not SPM 9X
dependency = {'spm', get_spm_version()>=8, get_spm_version()<95};
%This is to avoid crashes when trying to add SPM to the path
fallback_toolbox = 'SPM8';
case 'SPM12'
dependency = {'spm', get_spm_version()==12};
case 'MEG-PD'
dependency = {'rawdata', 'channames'};
case 'MEG-CALC'
dependency = {'megmodel', 'megfield', 'megtrans'};
case 'BIOSIG'
dependency = {'sopen', 'sread'};
case 'EEG'
dependency = {'ctf_read_res4', 'ctf_read_meg4'};
case 'EEGSF' % alternative name
dependency = {'ctf_read_res4', 'ctf_read_meg4'};
case 'MRI' % other functions in the mri section
dependency = {'avw_hdr_read', 'avw_img_read'};
case 'NEUROSHARE'
dependency = {'ns_OpenFile', 'ns_SetLibrary', ...
'ns_GetAnalogData'};
case 'ARTINIS'
dependency = {'read_artinis_oxy3'};
case 'BESA'
dependency = {'readBESAavr', 'readBESAelp', 'readBESAswf'};
case 'MATLAB2BESA'
dependency = {'besa_save2Avr', 'besa_save2Elp', 'besa_save2Swf'};
case 'EEPROBE'
dependency = {'read_eep_avr', 'read_eep_cnt'};
case 'YOKOGAWA'
dependency = @()hasyokogawa('16bitBeta6');
case 'YOKOGAWA12BITBETA3'
dependency = @()hasyokogawa('12bitBeta3');
case 'YOKOGAWA16BITBETA3'
dependency = @()hasyokogawa('16bitBeta3');
case 'YOKOGAWA16BITBETA6'
dependency = @()hasyokogawa('16bitBeta6');
case 'YOKOGAWA_MEG_READER'
dependency = @()hasyokogawa('1.4');
case 'BEOWULF'
dependency = {'evalwulf', 'evalwulf', 'evalwulf'};
case 'MENTAT'
dependency = {'pcompile', 'pfor', 'peval'};
case 'SON2'
dependency = {'SONFileHeader', 'SONChanList', 'SONGetChannel'};
case '4D-VERSION'
dependency = {'read4d', 'read4dhdr'};
case {'STATS', 'STATISTICS'}
dependency = has_license('statistics_toolbox'); % check the availability of a toolbox license
case {'OPTIM', 'OPTIMIZATION'}
dependency = has_license('optimization_toolbox'); % check the availability of a toolbox license
case {'SPLINES', 'CURVE_FITTING'}
dependency = has_license('curve_fitting_toolbox'); % check the availability of a toolbox license
case 'COMM'
dependency = {has_license('communication_toolbox'), 'de2bi'}; % also check the availability of a toolbox license
case 'SIGNAL'
dependency = {has_license('signal_toolbox'), 'window'}; % also check the availability of a toolbox license
case 'IMAGE'
dependency = has_license('image_toolbox'); % check the availability of a toolbox license
case {'DCT', 'DISTCOMP'}
dependency = has_license('distrib_computing_toolbox'); % check the availability of a toolbox license
case 'COMPILER'
dependency = has_license('compiler'); % check the availability of a toolbox license
case 'FASTICA'
dependency = 'fpica';
case 'BRAINSTORM'
dependency = 'bem_xfer';
case 'DENOISE'
dependency = {'tsr', 'sns'};
case 'CTF'
dependency = {'getCTFBalanceCoefs', 'getCTFdata'};
case 'BCI2000'
dependency = {'load_bcidat'};
case 'NLXNETCOM'
dependency = {'MatlabNetComClient', 'NlxConnectToServer', ...
'NlxGetNewCSCData'};
case 'DIPOLI'
dependency = {'dipoli.maci', 'file'};
case 'MNE'
dependency = {'fiff_read_meas_info', 'fiff_setup_read_raw'};
case 'TCP_UDP_IP'
dependency = {'pnet', 'pnet_getvar', 'pnet_putvar'};
case 'BEMCP'
dependency = {'bem_Cij_cog', 'bem_Cij_lin', 'bem_Cij_cst'};
case 'OPENMEEG'
dependency = {'om_save_tri'};
case 'PRTOOLS'
dependency = {'prversion', 'dataset', 'svc'};
case 'ITAB'
dependency = {'lcReadHeader', 'lcReadData'};
case 'BSMART'
dependency = 'bsmart';
case 'FREESURFER'
dependency = {'MRIread', 'vox2ras_0to1'};
case 'FNS'
dependency = 'elecsfwd';
case 'SIMBIO'
dependency = {'calc_stiff_matrix_val', 'sb_transfer'};
case 'VGRID'
dependency = 'vgrid';
case 'GIFTI'
dependency = 'gifti';
case 'XML4MAT'
dependency = {'xml2struct', 'xml2whos'};
case 'SQDPROJECT'
dependency = {'sqdread', 'sqdwrite'};
case 'BCT'
dependency = {'macaque71.mat', 'motif4funct_wei'};
case 'CCA'
dependency = {'ccabss'};
case 'EGI_MFF'
dependency = {'mff_getObject', 'mff_getSummaryInfo'};
case 'TOOLBOX_GRAPH'
dependency = 'toolbox_graph';
case 'NETCDF'
dependency = {'netcdf'};
case 'MYSQL'
% not sure if 'which' would work fine here, so use 'exist'
dependency = has_mex('mysql'); % this only consists of a single mex file
case 'ISO2MESH'
dependency = {'vol2surf', 'qmeshcut'};
case 'QSUB'
dependency = {'qsubfeval', 'qsubcellfun'};
case 'ENGINE'
dependency = {'enginefeval', 'enginecellfun'};
case 'DATAHASH'
dependency = {'DataHash'};
case 'IBTB'
dependency = {'make_ibtb','binr'};
case 'ICASSO'
dependency = {'icassoEst'};
case 'XUNIT'
dependency = {'initTestSuite', 'runtests'};
case 'PLEXON'
dependency = {'plx_adchan_gains', 'mexPlex'};
case '35625-INFORMATION-THEORY-TOOLBOX'
dependency = {'conditionalEntropy', 'entropy', 'jointEntropy',...
'mutualInformation' 'nmi' 'nvi' 'relativeEntropy'};
case '29046-MUTUAL-INFORMATION'
dependency = {'MI', 'license.txt'};
case '14888-MUTUAL-INFORMATION-COMPUTATION'
dependency = {'condentropy', 'demo_mi', 'estcondentropy.cpp',...
'estjointentropy.cpp', 'estpa.cpp', ...
'findjointstateab.cpp', 'makeosmex.m',...
'mutualinfo.m', 'condmutualinfo.m',...
'entropy.m', 'estentropy.cpp',...
'estmutualinfo.cpp', 'estpab.cpp',...
'jointentropy.m' 'mergemultivariables.m' };
case 'PLOT2SVG'
dependency = {'plot2svg.m', 'simulink2svg.m'};
case 'BRAINSUITE'
dependency = {'readdfs.m', 'writedfc.m'};
case 'BRAINVISA'
dependency = {'loadmesh.m', 'plotmesh.m', 'savemesh.m'};
case 'NEURALYNX_V6'
dependency = has_mex('Nlx2MatCSC');
case 'NEURALYNX_V3'
dependency = has_mex('Nlx2MatCSC_v3');
case 'NPMK'
dependency = {'OpenNSx' 'OpenNEV'};
case 'VIDEOMEG'
dependency = {'comp_tstamps' 'load_audio0123', 'load_video123'};
case 'WAVEFRONT'
dependency = {'write_wobj' 'read_wobj'};
case 'NEURONE'
dependency = {'readneurone' 'readneuronedata' 'readneuroneevents'};
% the following are FieldTrip modules/toolboxes
case 'FILEIO'
dependency = {'ft_read_header', 'ft_read_data', ...
'ft_read_event', 'ft_read_sens'};
case 'FORWARD'
dependency = {'ft_compute_leadfield', 'ft_prepare_vol_sens'};
case 'PLOTTING'
dependency = {'ft_plot_topo', 'ft_plot_mesh', 'ft_plot_matrix'};
case 'PEER'
dependency = {'peerslave', 'peermaster'};
case 'CONNECTIVITY'
dependency = {'ft_connectivity_corr', 'ft_connectivity_granger'};
case 'SPIKE'
dependency = {'ft_spiketriggeredaverage', 'ft_spiketriggeredspectrum'};
case 'FILEEXCHANGE'
dependency = is_subdir_in_fieldtrip_path('/external/fileexchange');
case {'INVERSE', 'REALTIME', 'SPECEST', 'PREPROC', ...
'COMPAT', 'STATFUN', 'TRIALFUN', 'UTILITIES/COMPAT', ...
'FILEIO/COMPAT', 'PREPROC/COMPAT', 'FORWARD/COMPAT', ...
'PLOTTING/COMPAT', 'TEMPLATE/LAYOUT', 'TEMPLATE/ANATOMY' ,...
'TEMPLATE/HEADMODEL', 'TEMPLATE/ELECTRODE', ...
'TEMPLATE/NEIGHBOURS', 'TEMPLATE/SOURCEMODEL'}
dependency = is_subdir_in_fieldtrip_path(toolbox);
otherwise
if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end
dependency = false;
end
status = is_present(dependency);
if ~status && ~isempty(fallback_toolbox)
% in case of SPM8UP
toolbox = fallback_toolbox;
end
% try to determine the path of the requested toolbox
if autoadd>0 && ~status
% for core FieldTrip modules
prefix = fileparts(which('ft_defaults'));
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for external FieldTrip modules
prefix = fullfile(fileparts(which('ft_defaults')), 'external');
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
licensefile = [lower(toolbox) '_license'];
if status && exist(licensefile, 'file')
% this will execute openmeeg_license and mne_license
% which display the license on screen for three seconds
feval(licensefile);
end
end
% for contributed FieldTrip extensions
prefix = fullfile(fileparts(which('ft_defaults')), 'contrib');
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
licensefile = [lower(toolbox) '_license'];
if status && exist(licensefile, 'file')
% this will execute openmeeg_license and mne_license
% which display the license on screen for three seconds
feval(licensefile);
end
end
% for linux computers in the Donders Centre for Cognitive Neuroimaging
prefix = '/home/common/matlab';
if ~status && isdir(prefix)
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for windows computers in the Donders Centre for Cognitive Neuroimaging
prefix = 'h:\common\matlab';
if ~status && isdir(prefix)
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% use the MATLAB subdirectory in your homedirectory, this works on linux and mac
prefix = fullfile(getenv('HOME'), 'matlab');
if ~status && isdir(prefix)
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
if ~status
% the toolbox is not on the path and cannot be added
sel = find(strcmp(url(:,1), toolbox));
if ~isempty(sel)
msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2});
else
msg = sprintf('the %s toolbox is not installed', toolbox);
end
if autoadd==1
error(msg);
elseif autoadd==2
ft_warning(msg);
else
% fail silently
end
end
end
% this function is called many times in FieldTrip and associated toolboxes
% use efficient handling if the same toolbox has been investigated before
if status
previous.(fixname(toolbox)) = status;
end
% remember the previous path, allows us to determine on the next call
% whether the path has been modified outise of this function
previouspath = path;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = myaddpath(toolbox, silent)
if isdeployed
warning('cannot change path settings for %s in a compiled application', toolbox);
status = 1;
elseif exist(toolbox, 'dir')
if ~silent,
ws = warning('backtrace', 'off');
warning('adding %s toolbox to your MATLAB path', toolbox);
warning(ws); % return to the previous warning level
end
addpath(toolbox);
status = 1;
elseif (~isempty(regexp(toolbox, 'spm5$', 'once')) || ~isempty(regexp(toolbox, 'spm8$', 'once')) || ~isempty(regexp(toolbox, 'spm12$', 'once'))) && exist([toolbox 'b'], 'dir')
status = myaddpath([toolbox 'b'], silent);
else
status = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function path = unixpath(path)
%path(path=='\') = '/'; % replace backward slashes with forward slashes
path = strrep(path,'\','/');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = hasfunction(funname, toolbox)
try
% call the function without any input arguments, which probably is inapropriate
feval(funname);
% it might be that the function without any input already works fine
status = true;
catch
% either the function returned an error, or the function is not available
% availability is influenced by the function being present and by having a
% license for the function, i.e. in a concurrent licensing setting it might
% be that all toolbox licenses are in use
m = lasterror;
if strcmp(m.identifier, 'MATLAB:license:checkouterror')
if nargin>1
warning('the %s toolbox is available, but you don''t have a license for it', toolbox);
else
warning('the function ''%s'' is available, but you don''t have a license for it', funname);
end
status = false;
elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction')
status = false;
else
% the function seems to be available and it gave an unknown error,
% which is to be expected with inappropriate input arguments
status = true;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = is_subdir_in_fieldtrip_path(toolbox_name)
fttrunkpath = unixpath(fileparts(which('ft_defaults')));
fttoolboxpath = fullfile(fttrunkpath, lower(toolbox_name));
needle=[pathsep fttoolboxpath pathsep];
haystack = [pathsep path() pathsep];
status = ~isempty(findstr(needle, haystack));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = has_mex(name)
full_name=[name '.' mexext];
status = (exist(full_name, 'file')==3);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function v = get_spm_version()
if ~is_present('spm')
v=NaN;
return
end
version_str = spm('ver');
token = regexp(version_str,'(\d*)','tokens');
v = str2num([token{:}{:}]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = has_license(toolbox_name)
status = license('checkout', toolbox_name)==1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = is_present(dependency)
if iscell(dependency)
% use recursion
status = all(cellfun(@is_present,dependency));
elseif islogical(dependency)
% boolean
status = all(dependency);
elseif ischar(dependency)
% name of a function
status = is_function_present_in_search_path(dependency);
elseif isa(dependency, 'function_handle')
status = dependency();
else
assert(false,'this should not happen');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = is_function_present_in_search_path(function_name)
w = which(function_name);
% must be in path and not a variable
status = ~isempty(w) && ~isequal(w, 'variable');
|
github
|
lcnhappe/happe-master
|
read_yokogawa_data_new.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_yokogawa_data_new.m
| 5,623 |
utf_8
|
521f307689398a9963b8d12d779650dd
|
function [dat] = read_yokogawa_data_new(filename, hdr, begsample, endsample, chanindx)
% READ_YOKAGAWA_DATA_NEW reads continuous, epoched or averaged MEG data
% that has been generated by the Yokogawa MEG system and software
% and allows that data to be used in combination with FieldTrip.
%
% Use as
% [dat] = read_yokogawa_data_new(filename, hdr, begsample, endsample, chanindx)
%
% This is a wrapper function around the function
% getYkgwData
%
% See also READ_YOKOGAWA_HEADER_NEW, READ_YOKOGAWA_EVENT
% Copyright (C) 2005, Robert Oostenveld and 2010, Tilmann Sander-Thoemmes
%
% 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 ~ft_hastoolbox('yokogawa_meg_reader')
error('cannot determine whether Yokogawa toolbox is present');
end
% hdr = read_yokogawa_header(filename);
hdr = hdr.orig; % use the original Yokogawa header, not the FieldTrip header
% default is to select all channels
if nargin<5
chanindx = 1:hdr.channel_count;
end
handles = definehandles;
switch hdr.acq_type
case handles.AcqTypeEvokedAve
% dat is returned as double
start_sample = begsample - 1; % samples start at 0
sample_length = endsample - begsample + 1;
epoch_count = 1;
start_epoch = 0;
dat = getYkgwData(filename, start_sample, sample_length);
case handles.AcqTypeContinuousRaw
% dat is returned as double
start_sample = begsample - 1; % samples start at 0
sample_length = endsample - begsample + 1;
epoch_count = 1;
start_epoch = 0;
dat = getYkgwData(filename, start_sample, sample_length);
case handles.AcqTypeEvokedRaw
% dat is returned as double
begtrial = ceil(begsample/hdr.sample_count);
endtrial = ceil(endsample/hdr.sample_count);
if begtrial<1
error('cannot read before the begin of the file');
elseif endtrial>hdr.actual_epoch_count
error('cannot read beyond the end of the file');
end
epoch_count = endtrial-begtrial+1;
start_epoch = begtrial-1;
% read all the neccessary trials that contain the desired samples
dat = getYkgwData(filename, start_epoch, epoch_count);
if size(dat,2)~=epoch_count*hdr.sample_count
error('could not read all epochs');
end
rawbegsample = begsample - (begtrial-1)*hdr.sample_count;
rawendsample = endsample - (begtrial-1)*hdr.sample_count;
sample_length = rawendsample - rawbegsample + 1;
% select the desired samples from the complete trials
dat = dat(:,rawbegsample:rawendsample);
otherwise
error('unknown data type');
end
if size(dat,1)~=hdr.channel_count
error('could not read all channels');
elseif size(dat,2)~=(endsample-begsample+1)
error('could not read all samples');
end
% select only the desired channels
dat = dat(chanindx,:);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this defines some usefull constants
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles = definehandles
handles.output = [];
handles.sqd_load_flag = false;
handles.mri_load_flag = false;
handles.NullChannel = 0;
handles.MagnetoMeter = 1;
handles.AxialGradioMeter = 2;
handles.PlannerGradioMeter = 3;
handles.RefferenceChannelMark = hex2dec('0100');
handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter );
handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter );
handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter );
handles.TriggerChannel = -1;
handles.EegChannel = -2;
handles.EcgChannel = -3;
handles.EtcChannel = -4;
handles.NonMegChannelNameLength = 32;
handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length
handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter
handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length
handles.AcqTypeContinuousRaw = 1;
handles.AcqTypeEvokedAve = 2;
handles.AcqTypeEvokedRaw = 3;
handles.sqd = [];
handles.sqd.selected_start = [];
handles.sqd.selected_end = [];
handles.sqd.axialgradiometer_ch_no = [];
handles.sqd.axialgradiometer_ch_info = [];
handles.sqd.axialgradiometer_data = [];
handles.sqd.plannergradiometer_ch_no = [];
handles.sqd.plannergradiometer_ch_info = [];
handles.sqd.plannergradiometer_data = [];
handles.sqd.eegchannel_ch_no = [];
handles.sqd.eegchannel_data = [];
handles.sqd.nullchannel_ch_no = [];
handles.sqd.nullchannel_data = [];
handles.sqd.selected_time = [];
handles.sqd.sample_rate = [];
handles.sqd.sample_count = [];
handles.sqd.pretrigger_length = [];
handles.sqd.matching_info = [];
handles.sqd.source_info = [];
handles.sqd.mri_info = [];
handles.mri = [];
|
github
|
lcnhappe/happe-master
|
read_plexon_nex.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_plexon_nex.m
| 7,574 |
utf_8
|
0034c1c75c81e41e90e48c678ed2ca9e
|
function [varargout] = read_plexon_nex(filename, varargin)
% READ_PLEXON_NEX reads header or data from a Plexon *.nex file, which
% is a file containing action-potential (spike) timestamps and waveforms
% (spike channels), event timestamps (event channels), and continuous
% variable data (continuous A/D channels).
%
% LFP and spike waveform data that is returned by this function is
% expressed in microVolt.
%
% Use as
% [hdr] = read_plexon_nex(filename)
% [dat] = read_plexon_nex(filename, ...)
% [dat1, dat2, dat3, hdr] = read_plexon_nex(filename, ...)
%
% Optional arguments should be specified in key-value pairs and can be
% header structure with header information
% feedback 0 or 1
% tsonly 0 or 1, read only the timestamps and not the waveforms
% channel number, or list of numbers (that will result in multiple outputs)
% begsample number (for continuous only)
% endsample number (for continuous only)
%
% See also READ_PLEXON_PLX, READ_PLEXON_DDT
% Copyright (C) 2007, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.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$
% parse the optional input arguments
hdr = ft_getopt(varargin, 'header');
channel = ft_getopt(varargin, 'channel');
feedback = ft_getopt(varargin, 'feedback', false);
tsonly = ft_getopt(varargin, 'tsonly', false);
begsample = ft_getopt(varargin, 'begsample', 1);
endsample = ft_getopt(varargin, 'endsample', inf);
% start with empty return values and empty data
varargout = {};
% read header info from file, use Matlabs for automatic byte-ordering
fid = fopen(filename, 'r', 'ieee-le');
fseek(fid, 0, 'eof');
siz = ftell(fid);
fseek(fid, 0, 'bof');
if isempty(hdr)
if feedback, fprintf('reading header from %s\n', filename); end
% a NEX file consists of a file header, followed by a number of variable headers
% sizeof(NexFileHeader) = 544
% sizeof(NexVarHeader) = 208
hdr.FileHeader = NexFileHeader(fid);
if hdr.FileHeader.NumVars<1
error('no channels present in file');
end
hdr.VarHeader = NexVarHeader(fid, hdr.FileHeader.NumVars);
end
for i=1:length(channel)
chan = channel(i);
vh = hdr.VarHeader(chan);
clear buf
fseek(fid, vh.DataOffset, 'bof');
switch vh.Type
case 0
% Neurons, only timestamps
buf.ts = fread(fid, [1 vh.Count], 'int32=>int32');
case 1
% Events, only timestamps
buf.ts = fread(fid, [1 vh.Count], 'int32=>int32');
case 2
% Interval variables
buf.begs = fread(fid, [1 vh.Count], 'int32=>int32');
buf.ends = fread(fid, [1 vh.Count], 'int32=>int32');
case 3
% Waveform variables
buf.ts = fread(fid, [1 vh.Count], 'int32=>int32');
if ~tsonly
buf.dat = fread(fid, [vh.NPointsWave vh.Count], 'int16');
% convert the AD values to miliVolt, subsequently convert from miliVolt to microVolt
buf.dat = buf.dat * (vh.ADtoMV * 1000);
end
case 4
% Population vector
error('population vectors are not supported');
case 5
% Continuously recorded variables
buf.ts = fread(fid, [1 vh.Count], 'int32=>int32');
buf.indx = fread(fid, [1 vh.Count], 'int32=>int32');
if vh.Count>1 && (begsample~=1 || endsample~=inf)
error('reading selected samples from multiple AD segments is not supported');
end
if ~tsonly
numsample = min(endsample - begsample + 1, vh.NPointsWave);
fseek(fid, (begsample-1)*2, 'cof');
buf.dat = fread(fid, [1 numsample], 'int16');
% convert the AD values to miliVolt, subsequently convert from miliVolt to microVolt
buf.dat = buf.dat * (vh.ADtoMV * 1000);
end
case 6
% Markers
buf.ts = fread(fid, [1 vh.Count], 'int32=>int32');
for j=1:vh.NMarkers
buf.MarkerNames{j,1} = fread(fid, [1 64], 'uint8=>char');
for k=1:vh.Count
buf.MarkerValues{j,k} = fread(fid, [1 vh.MarkerLength], 'uint8=>char');
end
end
otherwise
error('incorrect channel type');
end % switch channel type
% return the data of this channel
varargout{i} = buf;
end % for channel
% always return the header as last
varargout{end+1} = hdr;
fclose(fid);
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hdr = NexFileHeader(fid)
hdr.NexFileHeader = fread(fid,4,'uint8=>char')'; % string NEX1
hdr.Version = fread(fid,1,'int32');
hdr.Comment = fread(fid,256,'uint8=>char')';
hdr.Frequency = fread(fid,1,'double'); % timestamped freq. - tics per second
hdr.Beg = fread(fid,1,'int32'); % usually 0
hdr.End = fread(fid,1,'int32'); % maximum timestamp + 1
hdr.NumVars = fread(fid,1,'int32'); % number of variables in the first batch
hdr.NextFileHeader = fread(fid,1,'int32'); % position of the next file header in the file, not implemented yet
Padding = fread(fid,256,'uint8=>char')'; % future expansion
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hdr = NexVarHeader(fid, numvar)
for varlop=1:numvar
hdr(varlop).Type = fread(fid,1,'int32'); % 0 - neuron, 1 event, 2- interval, 3 - waveform, 4 - pop. vector, 5 - continuously recorded
hdr(varlop).Version = fread(fid,1,'int32'); % 100
hdr(varlop).Name = fread(fid,64,'uint8=>char')'; % variable name
hdr(varlop).DataOffset = fread(fid,1,'int32'); % where the data array for this variable is located in the file
hdr(varlop).Count = fread(fid,1,'int32'); % number of events, intervals, waveforms or weights
hdr(varlop).WireNumber = fread(fid,1,'int32'); % neuron only, not used now
hdr(varlop).UnitNumber = fread(fid,1,'int32'); % neuron only, not used now
hdr(varlop).Gain = fread(fid,1,'int32'); % neuron only, not used now
hdr(varlop).Filter = fread(fid,1,'int32'); % neuron only, not used now
hdr(varlop).XPos = fread(fid,1,'double'); % neuron only, electrode position in (0,100) range, used in 3D
hdr(varlop).YPos = fread(fid,1,'double'); % neuron only, electrode position in (0,100) range, used in 3D
hdr(varlop).WFrequency = fread(fid,1,'double'); % waveform and continuous vars only, w/f sampling frequency
hdr(varlop).ADtoMV = fread(fid,1,'double'); % waveform continuous vars only, coeff. to convert from A/D values to Millivolts
hdr(varlop).NPointsWave = fread(fid,1,'int32'); % waveform only, number of points in each wave
hdr(varlop).NMarkers = fread(fid,1,'int32'); % how many values are associated with each marker
hdr(varlop).MarkerLength = fread(fid,1,'int32'); % how many characters are in each marker value
Padding = fread(fid,68,'uint8=>char')';
end
|
github
|
lcnhappe/happe-master
|
read_bti_m4d.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_bti_m4d.m
| 5,780 |
utf_8
|
744eebbd1eba1a856943c7ce24600bc4
|
function [msi] = read_bti_m4d(filename)
% READ_BTI_M4D
%
% Use as
% msi = read_bti_m4d(filename)
% Copyright (C) 2007, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.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$
[p, f, x] = fileparts(filename);
if ~strcmp(x, '.m4d')
% add the extension of the header
filename = [filename '.m4d'];
end
fid = fopen(filename, 'r');
if fid==-1
error(sprintf('could not open file %s', filename));
end
% start with an empty header structure
msi = struct;
% these header elements contain strings and should be converted in a cell-array
strlist = {
'MSI.ChannelOrder'
};
% these header elements contain numbers and should be converted in a numeric array
% 'MSI.ChannelScale'
% 'MSI.ChannelGain'
% 'MSI.FileType'
% 'MSI.TotalChannels'
% 'MSI.TotalEpochs'
% 'MSI.SamplePeriod'
% 'MSI.SampleFrequency'
% 'MSI.FirstLatency'
% 'MSI.SlicesPerEpoch'
% the conversion to numeric arrays is implemented in a general fashion
% and all the fields above are automatically converted
numlist = {};
line = '';
msi.grad.label = {};
msi.grad.coilpos = zeros(0,3);
msi.grad.coilori = zeros(0,3);
while ischar(line)
line = cleanline(fgetl(fid));
if isempty(line) || (length(line)==1 && all(line==-1))
continue
end
sep = strfind(line, ':');
if length(sep)==1
key = line(1:(sep-1));
val = line((sep+1):end);
elseif length(sep)>1
% assume that the first separator is the relevant one, and that the
% next ones are part of the value string (e.g. a channel with a ':' in
% its name
sep = sep(1);
key = line(1:(sep-1));
val = line((sep+1):end);
elseif length(sep)<1
% this is not what I would expect
error('unexpected content in m4d file');
end
if ~isempty(strfind(line, 'Begin')) && (~isempty(strfind(line, 'Meg_Position_Information')) || ~isempty(strfind(line, 'Ref_Position_Information')))
% jansch added the second ~isempty() to accommodate for when the
% block is about Eeg_Position_Information, which does not pertain to
% gradiometers, and moreover can be empty (added: Aug 03, 2013)
sep = strfind(key, '.');
sep = sep(end);
key = key(1:(sep-1));
% if the key ends with begin and there is no value, then there is a block
% of numbers following that relates to the magnetometer/gradiometer information.
% All lines in that Begin-End block should be treated separately
val = {};
lab = {};
num = {};
ind = 0;
while isempty(strfind(line, 'End'))
line = cleanline(fgetl(fid));
if isempty(line) || (length(line)==1 && all(line==-1)) || ~isempty(strfind(line, 'End'))
continue
end
ind = ind+1;
% remember the line itself, and also cut it into pieces
val{ind} = line;
% the line is tab-separated and looks like this
% A68 0.0873437 -0.075789 0.0891512 0.471135 -0.815532 0.336098
sep = find(line==9); % the ascii value of a tab is 9
sep = sep(1);
lab{ind} = line(1:(sep-1));
num{ind} = str2num(line((sep+1):end));
end % parsing Begin-End block
val = val(:);
lab = lab(:);
num = num(:);
num = cell2mat(num);
% the following is FieldTrip specific
if size(num,2)==6
msi.grad.label = [msi.grad.label; lab(:)];
% the numbers represent position and orientation of each magnetometer coil
msi.grad.coilpos = [msi.grad.coilpos; num(:,1:3)];
msi.grad.coilori = [msi.grad.coilori; num(:,4:6)];
else
error('unknown gradiometer design')
end
end
% the key looks like 'MSI.fieldname.subfieldname'
fieldname = key(5:end);
% remove spaces from the begin and end of the string
val = strtrim(val);
% try to convert the value string into something more usefull
if ~iscell(val)
% the value can contain a variety of elements, only some of which are decoded here
if ~isempty(strfind(key, 'Index')) || ~isempty(strfind(key, 'Count')) || any(strcmp(key, numlist))
% this contains a single number or a comma-separated list of numbers
val = str2num(val);
elseif ~isempty(strfind(key, 'Names')) || any(strcmp(key, strlist))
% this contains a comma-separated list of strings
val = tokenize(val, ',');
else
tmp = str2num(val);
if ~isempty(tmp)
val = tmp;
end
end
end
% assign this header element to the structure
msi = setsubfield(msi, fieldname, val);
end % while ischar(line)
% each coil weighs with a value of 1 into each channel
msi.grad.tra = eye(size(msi.grad.coilpos,1));
msi.grad.unit = 'm';
fclose(fid);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION to remove spaces from the begin and end
% and to remove comments from the lines
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function line = cleanline(line)
if isempty(line) || (length(line)==1 && all(line==-1))
return
end
comment = findstr(line, '//');
if ~isempty(comment)
line(min(comment):end) = ' ';
end
line = strtrim(line);
|
github
|
lcnhappe/happe-master
|
read_asa.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_asa.m
| 3,803 |
utf_8
|
290f06e1b51f627f99d257a5f1b49465
|
function [val] = read_asa(filename, elem, format, number, token)
% READ_ASA reads a specified element from an ASA file
%
% val = read_asa(filename, element, type, number)
%
% where the element is a string such as
% NumberSlices
% NumberPositions
% Rows
% Columns
% etc.
%
% and format specifies the datatype according to
% %d (integer value)
% %f (floating point value)
% %s (string)
%
% number is optional to specify how many lines of data should be read
% The default is 1 for strings and Inf for numbers.
%
% token is optional to specifiy a character that separates the values from
% anything not wanted.
% Copyright (C) 2002-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$
fid = fopen(filename, 'rt');
if fid==-1
error(sprintf('could not open file %s', filename));
end
if nargin<4
if strcmp(format, '%s')
number = 1;
else
number = Inf;
end
end
if nargin<5
token = '';
end
val = [];
elem = strtrim(lower(elem));
while (1)
line = fgetl(fid);
if ~isempty(line) && isequal(line, -1)
% prematurely reached end of file
fclose(fid);
return
end
line = strtrim(line);
lower_line = lower(line);
if strmatch(elem, lower_line)
data = line((length(elem)+1):end);
break
end
end
while isempty(data)
line = fgetl(fid);
if isequal(line, -1)
% prematurely reached end of file
fclose(fid);
return
end
data = strtrim(line);
end
if strcmp(format, '%s')
if number==1
% interpret the data as a single string, create char-array
val = detoken(strtrim(data), token);
if val(1)=='='
val = val(2:end); % remove the trailing =
end
fclose(fid);
return
end
% interpret the data as a single string, create cell-array
val{1} = detoken(strtrim(data), token);
count = 1;
% read the remaining strings
while count<number
line = fgetl(fid);
if ~isempty(line) && isequal(line, -1)
fclose(fid);
return
end
tmp = sscanf(line, format);
if isempty(tmp)
fclose(fid);
return
else
count = count + 1;
val{count} = detoken(strtrim(line), token);
end
end
else
% interpret the data as numeric, create numeric array
count = 1;
data = sscanf(detoken(data, token), format)';
if isempty(data),
fclose(fid);
return
else
val(count,:) = data;
end
% read remaining numeric data
while count<number
line = fgetl(fid);
if ~isempty(line) && isequal(line, -1)
fclose(fid);
return
end
data = sscanf(detoken(line, token), format)';
if isempty(data)
fclose(fid);
return
else
count = count+1;
val(count,:) = data;
end
end
end
fclose(fid);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [out] = detoken(in, token)
if isempty(token)
out = in;
return;
end
[tok rem] = strtok(in, token);
if isempty(rem)
out = in;
return;
else
out = strtok(rem, token);
return
end
|
github
|
lcnhappe/happe-master
|
ft_checkdata.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/ft_checkdata.m
| 57,523 |
utf_8
|
361ae795581b786433b88af3f624763d
|
function [data] = ft_checkdata(data, varargin)
% FT_CHECKDATA checks the input data of the main FieldTrip functions, e.g. whether
% the type of data strucure corresponds with the required data. If neccessary
% and possible, this function will adjust the data structure to the input
% requirements (e.g. change dimord, average over trials, convert inside from
% index into logical).
%
% If the input data does NOT correspond to the requirements, this function
% is supposed to give a elaborate warning message and if applicable point
% the user to external documentation (link to website).
%
% Use as
% [data] = ft_checkdata(data, ...)
%
% Optional input arguments should be specified as key-value pairs and can include
% feedback = yes, no
% datatype = raw, freq, timelock, comp, spike, source, dip, volume, segmentation, parcellation
% dimord = any combination of time, freq, chan, refchan, rpt, subj, chancmb, rpttap, pos
% senstype = ctf151, ctf275, ctf151_planar, ctf275_planar, neuromag122, neuromag306, bti148, bti248, bti248_planar, magnetometer, electrode
% inside = logical, index
% ismeg = yes, no
% isnirs = yes, no
% hasunit = yes, no
% hascoordsys = yes, no
% hassampleinfo = yes, no, ifmakessense (only applies to raw data)
% hascumtapcnt = yes, no (only applies to freq data)
% hasdim = yes, no
% hasdof = yes, no
% cmbrepresentation = sparse, full (applies to covariance and cross-spectral density)
% fsample = sampling frequency to use to go from SPIKE to RAW representation
% segmentationstyle = indexed, probabilistic (only applies to segmentation)
% parcellationstyle = indexed, probabilistic (only applies to parcellation)
% hasbrain = yes, no (only applies to segmentation)
%
% For some options you can specify multiple values, e.g.
% [data] = ft_checkdata(data, 'senstype', {'ctf151', 'ctf275'}), e.g. in megrealign
% [data] = ft_checkdata(data, 'datatype', {'timelock', 'freq'}), e.g. in sourceanalysis
% Copyright (C) 2007-2015, Robert Oostenveld
% 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$
% in case of an error this function could use dbstack for more detailled
% user feedback
%
% this function should replace/encapsulate
% fixdimord
% fixinside
% fixprecision
% fixvolume
% data2raw
% raw2data
% grid2transform
% transform2grid
% fourier2crsspctrm
% freq2cumtapcnt
% sensortype
% time2offset
% offset2time
% fixsens -> this is kept a separate function because it should also be
% called from other modules
%
% other potential uses for this function:
% time -> offset in freqanalysis
% average over trials
% csd as matrix
% FIXME the following is difficult, if not impossible, to support without knowing the parameter
% FIXME it is presently (dec 2014) not being used anywhere in FT, so can be removed
% hastrials = yes, no
% get the optional input arguments
feedback = ft_getopt(varargin, 'feedback', 'no');
dtype = ft_getopt(varargin, 'datatype'); % should not conflict with the ft_datatype function
dimord = ft_getopt(varargin, 'dimord');
stype = ft_getopt(varargin, 'senstype'); % senstype is a function name which should not be masked
ismeg = ft_getopt(varargin, 'ismeg');
isnirs = ft_getopt(varargin, 'isnirs');
inside = ft_getopt(varargin, 'inside'); % can be 'logical' or 'index'
hastrials = ft_getopt(varargin, 'hastrials');
hasunit = ft_getopt(varargin, 'hasunit', 'no');
hascoordsys = ft_getopt(varargin, 'hascoordsys', 'no');
hassampleinfo = ft_getopt(varargin, 'hassampleinfo', 'ifmakessense');
hasdim = ft_getopt(varargin, 'hasdim');
hascumtapcnt = ft_getopt(varargin, 'hascumtapcnt');
hasdof = ft_getopt(varargin, 'hasdof');
cmbrepresentation = ft_getopt(varargin, 'cmbrepresentation');
channelcmb = ft_getopt(varargin, 'channelcmb');
fsample = ft_getopt(varargin, 'fsample');
segmentationstyle = ft_getopt(varargin, 'segmentationstyle'); % this will be passed on to the corresponding ft_datatype_xxx function
parcellationstyle = ft_getopt(varargin, 'parcellationstyle'); % this will be passed on to the corresponding ft_datatype_xxx function
hasbrain = ft_getopt(varargin, 'hasbrain');
% check whether people are using deprecated stuff
depHastrialdef = ft_getopt(varargin, 'hastrialdef');
if (~isempty(depHastrialdef))
ft_warning('ft_checkdata option ''hastrialdef'' is deprecated; use ''hassampleinfo'' instead');
hassampleinfo = depHastrialdef;
end
% determine the type of input data
% this can be raw, freq, timelock, comp, spike, source, volume, dip
israw = ft_datatype(data, 'raw');
isfreq = ft_datatype(data, 'freq');
istimelock = ft_datatype(data, 'timelock');
iscomp = ft_datatype(data, 'comp');
isspike = ft_datatype(data, 'spike');
isvolume = ft_datatype(data, 'volume');
issegmentation = ft_datatype(data, 'segmentation');
isparcellation = ft_datatype(data, 'parcellation');
issource = ft_datatype(data, 'source');
isdip = ft_datatype(data, 'dip');
ismvar = ft_datatype(data, 'mvar');
isfreqmvar = ft_datatype(data, 'freqmvar');
ischan = ft_datatype(data, 'chan');
ismesh = ft_datatype(data, 'mesh');
% FIXME use the istrue function on ismeg and hasxxx options
if ~isequal(feedback, 'no')
if iscomp
% it can be comp and raw/timelock/freq at the same time, therefore this has to go first
nchan = size(data.topo,1);
ncomp = size(data.topo,2);
fprintf('the input is component data with %d components and %d original channels\n', ncomp, nchan);
end
if israw
nchan = length(data.label);
ntrial = length(data.trial);
fprintf('the input is raw data with %d channels and %d trials\n', nchan, ntrial);
elseif istimelock
nchan = length(data.label);
ntime = length(data.time);
fprintf('the input is timelock data with %d channels and %d timebins\n', nchan, ntime);
elseif isfreq
if isfield(data, 'label')
nchan = length(data.label);
nfreq = length(data.freq);
if isfield(data, 'time'), ntime = num2str(length(data.time)); else ntime = 'no'; end
fprintf('the input is freq data with %d channels, %d frequencybins and %s timebins\n', nchan, nfreq, ntime);
elseif isfield(data, 'labelcmb')
nchan = length(data.labelcmb);
nfreq = length(data.freq);
if isfield(data, 'time'), ntime = num2str(length(data.time)); else ntime = 'no'; end
fprintf('the input is freq data with %d channel combinations, %d frequencybins and %s timebins\n', nchan, nfreq, ntime);
else
error('cannot infer freq dimensions');
end
elseif isspike
nchan = length(data.label);
fprintf('the input is spike data with %d channels\n', nchan);
elseif isvolume
if issegmentation
subtype = 'segmented volume';
else
subtype = 'volume';
end
fprintf('the input is %s data with dimensions [%d %d %d]\n', subtype, data.dim(1), data.dim(2), data.dim(3));
clear subtype
elseif issource
data = fixpos(data); % ensure that positions are in pos, not in pnt
nsource = size(data.pos, 1);
if isparcellation
subtype = 'parcellated source';
else
subtype = 'source';
end
if isfield(data, 'dim')
fprintf('the input is %s data with %d brainordinates on a [%d %d %d] grid\n', subtype, nsource, data.dim(1), data.dim(2), data.dim(3));
elseif isfield(data, 'tri')
fprintf('the input is %s data with %d vertex positions and %d triangles\n', subtype, nsource, size(data.tri, 1));
else
fprintf('the input is %s data with %d brainordinates\n', subtype, nsource);
end
clear subtype
elseif isdip
fprintf('the input is dipole data\n');
elseif ismvar
fprintf('the input is mvar data\n');
elseif isfreqmvar
fprintf('the input is freqmvar data\n');
elseif ischan
nchan = length(data.label);
if isfield(data, 'brainordinate')
fprintf('the input is parcellated data with %d parcels\n', nchan);
else
fprintf('the input is chan data with %d channels\n', nchan);
end
end
elseif ismesh
data = fixpos(data);
if numel(data)==1
if isfield(data,'tri')
fprintf('the input is mesh data with %d vertices and %d triangles\n', size(data.pos,1), size(data.tri,1));
elseif isfield(data,'hex')
fprintf('the input is mesh data with %d vertices and %d hexahedrons\n', size(data.pos,1), size(data.hex,1));
elseif isfield(data,'tet')
fprintf('the input is mesh data with %d vertices and %d tetrahedrons\n', size(data.pos,1), size(data.tet,1));
else
fprintf('the input is mesh data with %d vertices', size(data.pos,1));
end
else
fprintf('the input is mesh data multiple surfaces\n');
end
end % give feedback
if issource && isvolume
% it should be either one or the other: the choice here is to represent it as volume description since that is simpler to handle
% the conversion is done by removing the grid positions
data = rmfield(data, 'pos');
issource = false;
end
% the ft_datatype_XXX functions ensures the consistency of the XXX datatype
% and provides a detailed description of the dataformat and its history
if iscomp % this should go before israw/istimelock/isfreq
data = ft_datatype_comp(data, 'hassampleinfo', hassampleinfo);
elseif israw
data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo);
elseif istimelock
data = ft_datatype_timelock(data);
elseif isfreq
data = ft_datatype_freq(data);
elseif isspike
data = ft_datatype_spike(data);
elseif issegmentation % this should go before isvolume
data = ft_datatype_segmentation(data, 'segmentationstyle', segmentationstyle, 'hasbrain', hasbrain);
elseif isvolume
data = ft_datatype_volume(data);
elseif isparcellation % this should go before issource
data = ft_datatype_parcellation(data, 'parcellationstyle', parcellationstyle);
elseif issource
data = ft_datatype_source(data);
elseif isdip
data = ft_datatype_dip(data);
elseif ismvar || isfreqmvar
data = ft_datatype_mvar(data);
end
if ~isempty(dtype)
if ~isa(dtype, 'cell')
dtype = {dtype};
end
okflag = 0;
for i=1:length(dtype)
% check that the data matches with one or more of the required ft_datatypes
switch dtype{i}
case 'raw+comp'
okflag = okflag + (israw & iscomp);
case 'freq+comp'
okflag = okflag + (isfreq & iscomp);
case 'timelock+comp'
okflag = okflag + (istimelock & iscomp);
case 'raw'
okflag = okflag + (israw & ~iscomp);
case 'freq'
okflag = okflag + (isfreq & ~iscomp);
case 'timelock'
okflag = okflag + (istimelock & ~iscomp);
case 'comp'
okflag = okflag + (iscomp & ~(israw | istimelock | isfreq));
case 'spike'
okflag = okflag + isspike;
case 'volume'
okflag = okflag + isvolume;
case 'source'
okflag = okflag + issource;
case 'dip'
okflag = okflag + isdip;
case 'mvar'
okflag = okflag + ismvar;
case 'freqmvar'
okflag = okflag + isfreqmvar;
case 'chan'
okflag = okflag + ischan;
case 'segmentation'
okflag = okflag + issegmentation;
case 'parcellation'
okflag = okflag + isparcellation;
case 'mesh'
okflag = okflag + ismesh;
end % switch dtype
end % for dtype
% try to convert the data if needed
for iCell = 1:length(dtype)
if okflag
% the requested datatype is specified in descending order of
% preference (if there is a preference at all), so don't bother
% checking the rest of the requested data types if we already
% succeeded in converting
break;
end
if isequal(dtype(iCell), {'parcellation'}) && issegmentation
data = volume2source(data); % segmentation=volume, parcellation=source
data = ft_datatype_parcellation(data);
issegmentation = 0;
isvolume = 0;
isparcellation = 1;
issource = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'segmentation'}) && isparcellation
data = source2volume(data); % segmentation=volume, parcellation=source
data = ft_datatype_segmentation(data);
isparcellation = 0;
issource = 0;
issegmentation = 1;
isvolume = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'source'}) && isvolume
data = volume2source(data);
data = ft_datatype_source(data);
isvolume = 0;
issource = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'volume'}) && (ischan || istimelock || isfreq)
data = parcellated2source(data);
data = ft_datatype_volume(data);
ischan = 0;
isvolume = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'source'}) && (ischan || istimelock || isfreq)
data = parcellated2source(data);
data = ft_datatype_source(data);
ischan = 0;
issource = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'volume'}) && issource
data = source2volume(data);
data = ft_datatype_volume(data);
isvolume = 1;
issource = 0;
okflag = 1;
elseif isequal(dtype(iCell), {'raw+comp'}) && istimelock && iscomp
data = timelock2raw(data);
data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo);
istimelock = 0;
iscomp = 1;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && issource
data = source2raw(data);
data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo);
issource = 0;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && istimelock
if iscomp
data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired
iscomp = 0;
end
data = timelock2raw(data);
data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo);
istimelock = 0;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'comp'}) && israw
data = keepfields(data, {'label', 'topo', 'topolabel', 'unmixing', 'elec', 'grad', 'cfg'}); % these are the only relevant fields
data = ft_datatype_comp(data);
israw = 0;
iscomp = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'comp'}) && istimelock
data = keepfields(data, {'label', 'topo', 'topolabel', 'unmixing', 'elec', 'grad', 'cfg'}); % these are the only relevant fields
data = ft_datatype_comp(data);
istimelock = 0;
iscomp = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'comp'}) && isfreq
data = keepfields(data, {'label', 'topo', 'topolabel', 'unmixing', 'elec', 'grad', 'cfg'}); % these are the only relevant fields
data = ft_datatype_comp(data);
isfreq = 0;
iscomp = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && israw
if iscomp
data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired
iscomp = 0;
end
data = ft_datatype_raw(data);
okflag = 1;
elseif isequal(dtype(iCell), {'timelock'}) && istimelock
if iscomp
data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired
iscomp = 0;
end
data = ft_datatype_timelock(data);
okflag = 1;
elseif isequal(dtype(iCell), {'freq'}) && isfreq
if iscomp
data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired
iscomp = 0;
end
data = ft_datatype_freq(data);
okflag = 1;
elseif isequal(dtype(iCell), {'timelock'}) && israw
if iscomp
data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired
iscomp = 0;
end
data = raw2timelock(data);
data = ft_datatype_timelock(data);
israw = 0;
istimelock = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && isfreq
if iscomp
data = removefields(data, {'topo', 'topolabel', 'unmixing'}); % these fields are not desired
iscomp = 0;
end
data = freq2raw(data);
data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo);
isfreq = 0;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && ischan
data = chan2timelock(data);
data = timelock2raw(data);
data = ft_datatype_raw(data);
ischan = 0;
israw = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'timelock'}) && ischan
data = chan2timelock(data);
data = ft_datatype_timelock(data);
ischan = 0;
istimelock = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'freq'}) && ischan
data = chan2freq(data);
data = ft_datatype_freq(data);
ischan = 0;
isfreq = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'spike'}) && israw
data = raw2spike(data);
data = ft_datatype_spike(data);
israw = 0;
isspike = 1;
okflag = 1;
elseif isequal(dtype(iCell), {'raw'}) && isspike
data = spike2raw(data,fsample);
data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo);
isspike = 0;
israw = 1;
okflag = 1;
end
end % for iCell
if ~okflag
% construct an error message
if length(dtype)>1
str = sprintf('%s, ', dtype{1:(end-2)});
str = sprintf('%s%s or %s', str, dtype{end-1}, dtype{end});
else
str = dtype{1};
end
error('This function requires %s data as input.', str);
end % if okflag
end
if ~isempty(dimord)
if ~isa(dimord, 'cell')
dimord = {dimord};
end
if isfield(data, 'dimord')
okflag = any(strcmp(data.dimord, dimord));
else
okflag = 0;
end
if ~okflag
% construct an error message
if length(dimord)>1
str = sprintf('%s, ', dimord{1:(end-2)});
str = sprintf('%s%s or %s', str, dimord{end-1}, dimord{end});
else
str = dimord{1};
end
error('This function requires data with a dimord of %s.', str);
end % if okflag
end
if ~isempty(stype)
if ~isa(stype, 'cell')
stype = {stype};
end
if isfield(data, 'grad') || isfield(data, 'elec') || isfield(data, 'opto')
if any(strcmp(ft_senstype(data), stype))
okflag = 1;
elseif any(cellfun(@ft_senstype, repmat({data}, size(stype)), stype))
% this is required to detect more general types, such as "meg" or "ctf" rather than "ctf275"
okflag = 1;
else
okflag = 0;
end
end
if ~okflag
% construct an error message
if length(stype)>1
str = sprintf('%s, ', stype{1:(end-2)});
str = sprintf('%s%s or %s', str, stype{end-1}, stype{end});
else
str = stype{1};
end
error('This function requires %s data as input, but you are giving %s data.', str, ft_senstype(data));
end % if okflag
end
if ~isempty(ismeg)
if isequal(ismeg, 'yes')
okflag = isfield(data, 'grad');
elseif isequal(ismeg, 'no')
okflag = ~isfield(data, 'grad');
end
if ~okflag && isequal(ismeg, 'yes')
error('This function requires MEG data with a ''grad'' field');
elseif ~okflag && isequal(ismeg, 'no')
error('This function should not be given MEG data with a ''grad'' field');
end % if okflag
end
if ~isempty(isnirs)
if isequal(isnirs, 'yes')
okflag = isfield(data, 'opto');
elseif isequal(isnirs, 'no')
okflag = ~isfield(data, 'opto');
end
if ~okflag && isequal(isnirs, 'yes')
error('This function requires NIRS data with an ''opto'' field');
elseif ~okflag && isequal(isnirs, 'no')
error('This function should not be given NIRS data with an ''opto'' field');
end % if okflag
end
if ~isempty(inside)
if strcmp(inside, 'index')
warning('the indexed representation of inside/outside source locations is deprecated');
end
% TODO absorb the fixinside function into this code
data = fixinside(data, inside);
okflag = isfield(data, 'inside');
if ~okflag
% construct an error message
error('This function requires data with an ''inside'' field.');
end % if okflag
end
if istrue(hasunit) && ~isfield(data, 'unit')
% calling convert_units with only the input data adds the units without converting
data = ft_convert_units(data);
end % if hasunit
if istrue(hascoordsys) && ~isfield(data, 'coordsys')
data = ft_determine_coordsys(data);
end % if hascoordsys
if isequal(hastrials, 'yes')
okflag = isfield(data, 'trial');
if ~okflag && isfield(data, 'dimord')
% instead look in the dimord for rpt or subj
okflag = ~isempty(strfind(data.dimord, 'rpt')) || ...
~isempty(strfind(data.dimord, 'rpttap')) || ...
~isempty(strfind(data.dimord, 'subj'));
end
if ~okflag
error('This function requires data with a ''trial'' field');
end % if okflag
end
if strcmp(hasdim, 'yes') && ~isfield(data, 'dim')
data.dim = pos2dim(data.pos);
elseif strcmp(hasdim, 'no') && isfield(data, 'dim')
data = rmfield(data, 'dim');
end % if hasdim
if strcmp(hascumtapcnt, 'yes') && ~isfield(data, 'cumtapcnt')
error('This function requires data with a ''cumtapcnt'' field');
elseif strcmp(hascumtapcnt, 'no') && isfield(data, 'cumtapcnt')
data = rmfield(data, 'cumtapcnt');
end % if hascumtapcnt
if strcmp(hasdof, 'yes') && ~isfield(data, 'dof')
error('This function requires data with a ''dof'' field');
elseif strcmp(hasdof, 'no') && isfield(data, 'dof')
data = rmfield(data, 'dof');
end % if hasdof
if ~isempty(cmbrepresentation)
if istimelock
data = fixcov(data, cmbrepresentation);
elseif isfreq
data = fixcsd(data, cmbrepresentation, channelcmb);
elseif isfreqmvar
data = fixcsd(data, cmbrepresentation, channelcmb);
else
error('This function requires data with a covariance, coherence or cross-spectrum');
end
end % cmbrepresentation
if isfield(data, 'grad')
% ensure that the gradiometer structure is up to date
data.grad = ft_datatype_sens(data.grad);
end
if isfield(data, 'elec')
% ensure that the electrode structure is up to date
data.elec = ft_datatype_sens(data.elec);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% represent the covariance matrix in a particular manner
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = fixcov(data, desired)
if any(isfield(data, {'cov', 'corr'}))
if ~isfield(data, 'labelcmb')
current = 'full';
else
current = 'sparse';
end
else
error('Could not determine the current representation of the covariance matrix');
end
if isequal(current, desired)
% nothing to do
elseif strcmp(current, 'full') && strcmp(desired, 'sparse')
% FIXME should be implemented
error('not yet implemented');
elseif strcmp(current, 'sparse') && strcmp(desired, 'full')
% FIXME should be implemented
error('not yet implemented');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% represent the cross-spectral density matrix in a particular manner
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = fixcsd(data, desired, channelcmb)
% FIXCSD converts univariate frequency domain data (fourierspctrm) into a bivariate
% representation (crsspctrm), or changes the representation of bivariate frequency
% domain data (sparse/full/sparsewithpow, sparsewithpow only works for crsspctrm or
% fourierspctrm)
% Copyright (C) 2010, Jan-Mathijs Schoffelen, Robert Oostenveld
if isfield(data, 'crsspctrm') && isfield(data, 'powspctrm')
current = 'sparsewithpow';
elseif isfield(data, 'powspctrm')
current = 'sparsewithpow';
elseif isfield(data, 'fourierspctrm') && ~isfield(data, 'labelcmb')
current = 'fourier';
elseif ~isfield(data, 'labelcmb')
current = 'full';
elseif isfield(data, 'labelcmb')
current = 'sparse';
else
error('Could not determine the current representation of the %s matrix', param);
end
% first go from univariate fourier to the required bivariate representation
if isequal(current, desired)
% nothing to do
elseif strcmp(current, 'fourier') && strcmp(desired, 'sparsewithpow')
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpttap', dimtok)),
nrpt = size(data.cumtapcnt,1);
flag = 0;
else
nrpt = 1;
end
if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end
fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1));
flag = nrpt==1; % needed to truncate the singleton dimension upfront
%create auto-spectra
nchan = length(data.label);
if fastflag
% all trials have the same amount of tapers
powspctrm = zeros(nrpt,nchan,nfrq,ntim);
ntap = data.cumtapcnt(1);
for p = 1:ntap
powspctrm = powspctrm + abs(data.fourierspctrm(p:ntap:end,:,:,:,:)).^2;
end
powspctrm = powspctrm./ntap;
else
% different amount of tapers
powspctrm = zeros(nrpt,nchan,nfrq,ntim)+i.*zeros(nrpt,nchan,nfrq,ntim);
sumtapcnt = [0;cumsum(data.cumtapcnt(:))];
for p = 1:nrpt
indx = (sumtapcnt(p)+1):sumtapcnt(p+1);
tmpdat = data.fourierspctrm(indx,:,:,:);
powspctrm(p,:,:,:) = (sum(tmpdat.*conj(tmpdat),1))./data.cumtapcnt(p);
end
end
%create cross-spectra
if ~isempty(channelcmb),
ncmb = size(channelcmb,1);
cmbindx = zeros(ncmb,2);
labelcmb = cell(ncmb,2);
for k = 1:ncmb
ch1 = find(strcmp(data.label, channelcmb(k,1)));
ch2 = find(strcmp(data.label, channelcmb(k,2)));
if ~isempty(ch1) && ~isempty(ch2),
cmbindx(k,:) = [ch1 ch2];
labelcmb(k,:) = data.label([ch1 ch2])';
end
end
crsspctrm = zeros(nrpt,ncmb,nfrq,ntim)+i.*zeros(nrpt,ncmb,nfrq,ntim);
if fastflag
for p = 1:ntap
tmpdat1 = data.fourierspctrm(p:ntap:end,cmbindx(:,1),:,:,:);
tmpdat2 = data.fourierspctrm(p:ntap:end,cmbindx(:,2),:,:,:);
crsspctrm = crsspctrm + tmpdat1.*conj(tmpdat2);
end
crsspctrm = crsspctrm./ntap;
else
for p = 1:nrpt
indx = (sumtapcnt(p)+1):sumtapcnt(p+1);
tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:);
tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:);
crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p);
end
end
data.crsspctrm = crsspctrm;
data.labelcmb = labelcmb;
end
data.powspctrm = powspctrm;
data = rmfield(data, 'fourierspctrm');
if ntim>1,
data.dimord = 'chan_freq_time';
else
data.dimord = 'chan_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
if flag,
siz = size(data.powspctrm);
data.powspctrm = reshape(data.powspctrm, [siz(2:end) 1]);
if isfield(data, 'crsspctrm')
siz = size(data.crsspctrm);
data.crsspctrm = reshape(data.crsspctrm, [siz(2:end) 1]);
end
end
elseif strcmp(current, 'fourier') && strcmp(desired, 'sparse')
if isempty(channelcmb), error('no channel combinations are specified'); end
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpttap', dimtok)),
nrpt = size(data.cumtapcnt,1);
flag = 0;
else
nrpt = 1;
end
if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end
flag = nrpt==1; % flag needed to squeeze first dimension if singleton
ncmb = size(channelcmb,1);
cmbindx = zeros(ncmb,2);
labelcmb = cell(ncmb,2);
for k = 1:ncmb
ch1 = find(strcmp(data.label, channelcmb(k,1)));
ch2 = find(strcmp(data.label, channelcmb(k,2)));
if ~isempty(ch1) && ~isempty(ch2),
cmbindx(k,:) = [ch1 ch2];
labelcmb(k,:) = data.label([ch1 ch2])';
end
end
sumtapcnt = [0;cumsum(data.cumtapcnt(:))];
fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1));
if fastflag && nrpt>1
ntap = data.cumtapcnt(1);
% compute running sum across tapers
siz = [size(data.fourierspctrm) 1];
for p = 1:ntap
indx = p:ntap:nrpt*ntap;
if p==1.
tmpc = zeros(numel(indx), size(cmbindx,1), siz(3), siz(4)) + ...
1i.*zeros(numel(indx), size(cmbindx,1), siz(3), siz(4));
end
for k = 1:size(cmbindx,1)
tmpc(:,k,:,:) = data.fourierspctrm(indx,cmbindx(k,1),:,:).* ...
conj(data.fourierspctrm(indx,cmbindx(k,2),:,:));
end
if p==1
crsspctrm = tmpc;
else
crsspctrm = tmpc + crsspctrm;
end
end
crsspctrm = crsspctrm./ntap;
else
crsspctrm = zeros(nrpt, ncmb, nfrq, ntim);
for p = 1:nrpt
indx = (sumtapcnt(p)+1):sumtapcnt(p+1);
tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:);
tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:);
crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p);
end
end
data.crsspctrm = crsspctrm;
data.labelcmb = labelcmb;
data = rmfield(data, 'fourierspctrm');
data = rmfield(data, 'label');
if ntim>1,
data.dimord = 'chancmb_freq_time';
else
data.dimord = 'chancmb_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
if flag,
% deal with the singleton 'rpt', i.e. remove it
siz = size(data.powspctrm);
data.powspctrm = reshape(data.powspctrm, [siz(2:end) 1]);
if isfield(data,'crsspctrm')
% this conditional statement is needed in case there's a single channel
siz = size(data.crsspctrm);
data.crsspctrm = reshape(data.crsspctrm, [siz(2:end) 1]);
end
end
elseif strcmp(current, 'fourier') && strcmp(desired, 'full')
% this is how it is currently and the desired functionality of prepare_freq_matrices
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpttap', dimtok)),
nrpt = size(data.cumtapcnt, 1);
flag = 0;
else
nrpt = 1;
flag = 1;
end
if ~isempty(strmatch('rpttap',dimtok)), nrpt=size(data.cumtapcnt, 1); else nrpt = 1; end
if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end
if any(data.cumtapcnt(1,:) ~= data.cumtapcnt(1,1)), error('this only works when all frequencies have the same number of tapers'); end
nchan = length(data.label);
crsspctrm = zeros(nrpt,nchan,nchan,nfrq,ntim);
sumtapcnt = [0;cumsum(data.cumtapcnt(:,1))];
for k = 1:ntim
for m = 1:nfrq
for p = 1:nrpt
%FIXME speed this up in the case that all trials have equal number of tapers
indx = (sumtapcnt(p)+1):sumtapcnt(p+1);
tmpdat = transpose(data.fourierspctrm(indx,:,m,k));
crsspctrm(p,:,:,m,k) = (tmpdat*tmpdat')./data.cumtapcnt(p);
clear tmpdat;
end
end
end
data.crsspctrm = crsspctrm;
data = rmfield(data, 'fourierspctrm');
if ntim>1,
data.dimord = 'chan_chan_freq_time';
else
data.dimord = 'chan_chan_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
% remove first singleton dimension
if flag || nrpt==1, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end
elseif strcmp(current, 'fourier') && strcmp(desired, 'fullfast'),
dimtok = tokenize(data.dimord, '_');
nrpt = size(data.fourierspctrm, 1);
nchn = numel(data.label);
nfrq = numel(data.freq);
if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end
data.fourierspctrm = reshape(data.fourierspctrm, [nrpt nchn nfrq*ntim]);
data.fourierspctrm(~isfinite(data.fourierspctrm)) = 0;
crsspctrm = complex(zeros(nchn,nchn,nfrq*ntim));
for k = 1:nfrq*ntim
tmp = transpose(data.fourierspctrm(:,:,k));
n = sum(tmp~=0,2);
crsspctrm(:,:,k) = tmp*tmp'./n(1);
end
data = rmfield(data, 'fourierspctrm');
data.crsspctrm = reshape(crsspctrm, [nchn nchn nfrq ntim]);
if isfield(data, 'time'),
data.dimord = 'chan_chan_freq_time';
else
data.dimord = 'chan_chan_freq';
end
if isfield(data, 'trialinfo'), data = rmfield(data, 'trialinfo'); end;
if isfield(data, 'sampleinfo'), data = rmfield(data, 'sampleinfo'); end;
if isfield(data, 'cumsumcnt'), data = rmfield(data, 'cumsumcnt'); end;
if isfield(data, 'cumtapcnt'), data = rmfield(data, 'cumtapcnt'); end;
end % convert to the requested bivariate representation
% from one bivariate representation to another
if isequal(current, desired)
% nothing to do
elseif (strcmp(current, 'full') && strcmp(desired, 'fourier')) || ...
(strcmp(current, 'sparse') && strcmp(desired, 'fourier')) || ...
(strcmp(current, 'sparsewithpow') && strcmp(desired, 'fourier'))
% this is not possible
error('converting the cross-spectrum into a Fourier representation is not possible');
elseif strcmp(current, 'full') && strcmp(desired, 'sparsewithpow')
error('not yet implemented');
elseif strcmp(current, 'sparse') && strcmp(desired, 'sparsewithpow')
% convert back to crsspctrm/powspctrm representation: useful for plotting functions etc
indx = labelcmb2indx(data.labelcmb);
autoindx = indx(indx(:,1)==indx(:,2), 1);
cmbindx = setdiff([1:size(indx,1)]', autoindx);
if strcmp(data.dimord(1:3), 'rpt')
data.powspctrm = data.crsspctrm(:, autoindx, :, :);
data.crsspctrm = data.crsspctrm(:, cmbindx, :, :);
else
data.powspctrm = data.crsspctrm(autoindx, :, :);
data.crsspctrm = data.crsspctrm(cmbindx, :, :);
end
data.label = data.labelcmb(autoindx,1);
data.labelcmb = data.labelcmb(cmbindx, :);
if isempty(cmbindx)
data = rmfield(data, 'crsspctrm');
data = rmfield(data, 'labelcmb');
end
elseif strcmp(current, 'full') && strcmp(desired, 'sparse')
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end
if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end
nchan = length(data.label);
ncmb = nchan*nchan;
labelcmb = cell(ncmb, 2);
cmbindx = zeros(nchan, nchan);
k = 1;
for j=1:nchan
for m=1:nchan
labelcmb{k, 1} = data.label{m};
labelcmb{k, 2} = data.label{j};
cmbindx(m,j) = k;
k = k+1;
end
end
% reshape all possible fields
fn = fieldnames(data);
for ii=1:numel(fn)
if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim;
if nrpt>1,
data.(fn{ii}) = reshape(data.(fn{ii}), nrpt, ncmb, nfrq, ntim);
else
data.(fn{ii}) = reshape(data.(fn{ii}), ncmb, nfrq, ntim);
end
end
end
% remove obsolete fields
data = rmfield(data, 'label');
try data = rmfield(data, 'dof'); end
% replace updated fields
data.labelcmb = labelcmb;
if ntim>1,
data.dimord = 'chancmb_freq_time';
else
data.dimord = 'chancmb_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
elseif strcmp(current, 'sparsewithpow') && strcmp(desired, 'sparse')
% this representation for sparse data contains autospectra as e.g. {'A' 'A'} in labelcmb
if isfield(data, 'crsspctrm'),
dimtok = tokenize(data.dimord, '_');
catdim = match_str(dimtok, {'chan' 'chancmb'});
data.crsspctrm = cat(catdim, data.powspctrm, data.crsspctrm);
data.labelcmb = [data.label(:) data.label(:); data.labelcmb];
data = rmfield(data, 'powspctrm');
data.dimord = strrep(data.dimord, 'chan_', 'chancmb_');
else
data.crsspctrm = data.powspctrm;
data.labelcmb = [data.label(:) data.label(:)];
data = rmfield(data, 'powspctrm');
data.dimord = strrep(data.dimord, 'chan_', 'chancmb_');
end
data = rmfield(data, 'label');
elseif strcmp(current, 'sparse') && strcmp(desired, 'full')
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end
if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end
if ~isfield(data, 'label')
% ensure that the bivariate spectral factorization results can be
% processed. FIXME this is experimental and will not work if the user
% did something weird before
for k = 1:numel(data.labelcmb)
tmp = tokenize(data.labelcmb{k}, '[');
data.labelcmb{k} = tmp{1};
end
data.label = unique(data.labelcmb(:));
end
nchan = length(data.label);
ncmb = size(data.labelcmb,1);
cmbindx = zeros(nchan,nchan);
for k = 1:size(data.labelcmb,1)
ch1 = find(strcmp(data.label, data.labelcmb(k,1)));
ch2 = find(strcmp(data.label, data.labelcmb(k,2)));
if ~isempty(ch1) && ~isempty(ch2),
cmbindx(ch1,ch2) = k;
end
end
complete = all(cmbindx(:)~=0);
% remove obsolete fields
try data = rmfield(data, 'powspctrm'); end
try data = rmfield(data, 'labelcmb'); end
try data = rmfield(data, 'dof'); end
fn = fieldnames(data);
for ii=1:numel(fn)
if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim;
if nrpt==1,
data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]);
end
tmpall = nan(nrpt,nchan,nchan,nfrq,ntim);
for j = 1:nrpt
for k = 1:ntim
for m = 1:nfrq
tmpdat = nan(nchan,nchan);
indx = find(cmbindx);
if ~complete
% this realizes the missing combinations to be represented as the
% conjugate of the corresponding combination across the diagonal
tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]);
tmpdat = ctranspose(tmpdat);
end
tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]);
tmpall(j,:,:,m,k) = tmpdat;
end % for m
end % for k
end % for j
% replace the data in the old representation with the new representation
if nrpt>1,
data.(fn{ii}) = tmpall;
else
data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]);
end
end % if numel
end % for ii
if ntim>1,
data.dimord = 'chan_chan_freq_time';
else
data.dimord = 'chan_chan_freq';
end
if nrpt>1,
data.dimord = ['rpt_',data.dimord];
end
elseif strcmp(current, 'sparse') && strcmp(desired, 'fullfast')
dimtok = tokenize(data.dimord, '_');
if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end
if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end
if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end
if ~isfield(data, 'label')
data.label = unique(data.labelcmb(:));
end
nchan = length(data.label);
ncmb = size(data.labelcmb,1);
cmbindx = zeros(nchan,nchan);
for k = 1:size(data.labelcmb,1)
ch1 = find(strcmp(data.label, data.labelcmb(k,1)));
ch2 = find(strcmp(data.label, data.labelcmb(k,2)));
if ~isempty(ch1) && ~isempty(ch2),
cmbindx(ch1,ch2) = k;
end
end
complete = all(cmbindx(:)~=0);
fn = fieldnames(data);
for ii=1:numel(fn)
if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim;
if nrpt==1,
data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]);
end
tmpall = nan(nchan,nchan,nfrq,ntim);
for k = 1:ntim
for m = 1:nfrq
tmpdat = nan(nchan,nchan);
indx = find(cmbindx);
if ~complete
% this realizes the missing combinations to be represented as the
% conjugate of the corresponding combination across the diagonal
tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]);
tmpdat = ctranspose(tmpdat);
end
tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]);
tmpall(:,:,m,k) = tmpdat;
end % for m
end % for k
% replace the data in the old representation with the new representation
if nrpt>1,
data.(fn{ii}) = tmpall;
else
data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]);
end
end % if numel
end % for ii
% remove obsolete fields
try data = rmfield(data, 'powspctrm'); end
try data = rmfield(data, 'labelcmb'); end
try data = rmfield(data, 'dof'); end
if ntim>1,
data.dimord = 'chan_chan_freq_time';
else
data.dimord = 'chan_chan_freq';
end
elseif strcmp(current, 'sparsewithpow') && any(strcmp(desired, {'full', 'fullfast'}))
% recursively call ft_checkdata, but ensure channel order to be the same
% as the original input.
origlabelorder = data.label; % keep track of the original order of the channels
data = ft_checkdata(data, 'cmbrepresentation', 'sparse');
data.label = origlabelorder; % this avoids the labels to be alphabetized in the next call
data = ft_checkdata(data, 'cmbrepresentation', 'full');
end % convert from one to another bivariate representation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [source] = parcellated2source(data)
if ~isfield(data, 'brainordinate')
error('projecting parcellated data onto the full brain model geometry requires the specification of brainordinates');
end
% the main structure contains the functional data on the parcels
% the brainordinate sub-structure contains the original geometrical model
source = data.brainordinate;
data = rmfield(data, 'brainordinate');
if isfield(data, 'cfg')
source.cfg = data.cfg;
end
fn = fieldnames(data);
fn = setdiff(fn, {'label', 'time', 'freq', 'hdr', 'cfg', 'grad', 'elec', 'dimord', 'unit'}); % remove irrelevant fields
fn(~cellfun(@isempty, regexp(fn, 'dimord$'))) = []; % remove irrelevant (dimord) fields
sel = false(size(fn));
for i=1:numel(fn)
try
sel(i) = ismember(getdimord(data, fn{i}), {'chan', 'chan_time', 'chan_freq', 'chan_freq_time', 'chan_chan'});
end
end
parameter = fn(sel);
fn = fieldnames(source);
sel = false(size(fn));
for i=1:numel(fn)
tmp = source.(fn{i});
sel(i) = iscell(tmp) && isequal(tmp(:), data.label(:));
end
parcelparam = fn(sel);
if numel(parcelparam)~=1
error('cannot determine which parcellation to use');
else
parcelparam = parcelparam{1}(1:(end-5)); % minus the 'label'
end
for i=1:numel(parameter)
source.(parameter{i}) = unparcellate(data, source, parameter{i}, parcelparam);
end
% copy over fields (these are necessary for visualising the data in ft_sourceplot)
source = copyfields(data, source, {'time', 'freq'});
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = volume2source(data)
if isfield(data, 'dimord')
% it is a modern source description
else
% it is an old-fashioned source description
xgrid = 1:data.dim(1);
ygrid = 1:data.dim(2);
zgrid = 1:data.dim(3);
[x y z] = ndgrid(xgrid, ygrid, zgrid);
data.pos = ft_warp_apply(data.transform, [x(:) y(:) z(:)]);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = source2volume(data)
if isfield(data, 'dimord')
% it is a modern source description
%this part depends on the assumption that the list of positions is describing a full 3D volume in
%an ordered way which allows for the extraction of a transformation matrix
%i.e. slice by slice
try
if isfield(data, 'dim'),
data.dim = pos2dim(data.pos, data.dim);
else
data.dim = pos2dim(data);
end
catch
end
end
if isfield(data, 'dim') && length(data.dim)>=3,
data.transform = pos2transform(data.pos, data.dim);
end
% remove the unwanted fields
data = removefields(data, {'pos', 'xgrid', 'ygrid', 'zgrid', 'tri', 'tet', 'hex'});
% make inside a volume
data = fixinside(data, 'logical');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = freq2raw(freq)
if isfield(freq, 'powspctrm')
param = 'powspctrm';
elseif isfield(freq, 'fourierspctrm')
param = 'fourierspctrm';
else
error('not supported for this data representation');
end
if strcmp(freq.dimord, 'rpt_chan_freq_time') || strcmp(freq.dimord, 'rpttap_chan_freq_time')
dat = freq.(param);
elseif strcmp(freq.dimord, 'chan_freq_time')
dat = freq.(param);
dat = reshape(dat, [1 size(dat)]); % add a singleton dimension
else
error('not supported for dimord %s', freq.dimord);
end
nrpt = size(dat,1);
nchan = size(dat,2);
nfreq = size(dat,3);
ntime = size(dat,4);
data = [];
% create the channel labels like "MLP11@12Hz""
k = 0;
for i=1:nfreq
for j=1:nchan
k = k+1;
data.label{k} = sprintf('%s@%dHz', freq.label{j}, freq.freq(i));
end
end
% reshape and copy the data as if it were timecourses only
for i=1:nrpt
data.time{i} = freq.time;
data.trial{i} = reshape(dat(i,:,:,:), nchan*nfreq, ntime);
if any(isnan(data.trial{i}(1,:))),
tmp = data.trial{i}(1,:);
begsmp = find(isfinite(tmp),1, 'first');
endsmp = find(isfinite(tmp),1, 'last' );
data.trial{i} = data.trial{i}(:, begsmp:endsmp);
data.time{i} = data.time{i}(begsmp:endsmp);
end
end
if isfield(freq, 'trialinfo'), data.trialinfo = freq.trialinfo; end;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = raw2timelock(data)
nsmp = cellfun('size',data.time,2);
data = ft_checkdata(data, 'hassampleinfo', 'yes');
ntrial = numel(data.trial);
nchan = numel(data.label);
if ntrial==1
data.time = data.time{1};
data.avg = data.trial{1};
data = rmfield(data, 'trial');
data.dimord = 'chan_time';
else
% code below tries to construct a general time-axis where samples of all trials can fall on
% find earliest beginning and latest ending
begtime = min(cellfun(@min,data.time));
endtime = max(cellfun(@max,data.time));
% find 'common' sampling rate
fsample = 1./mean(cellfun(@mean,cellfun(@diff,data.time,'uniformoutput',false)));
% estimate number of samples
nsmp = round((endtime-begtime)*fsample) + 1; % numerical round-off issues should be dealt with by this round, as they will/should never cause an extra sample to appear
% construct general time-axis
time = linspace(begtime,endtime,nsmp);
% concatenate all trials
tmptrial = nan(ntrial, nchan, length(time));
begsmp = nan(ntrial, 1);
endsmp = nan(ntrial, 1);
for i=1:ntrial
begsmp(i) = nearest(time, data.time{i}(1));
endsmp(i) = nearest(time, data.time{i}(end));
tmptrial(i,:,begsmp(i):endsmp(i)) = data.trial{i};
end
% update the sampleinfo
begpad = begsmp - min(begsmp);
endpad = max(endsmp) - endsmp;
if isfield(data, 'sampleinfo')
data.sampleinfo = data.sampleinfo + [-begpad(:) endpad(:)];
end
% construct the output timelocked data
% data.avg = reshape(nanmean(tmptrial, 1), nchan, length(tmptime));
% data.var = reshape(nanvar (tmptrial, [], 1), nchan, length(tmptime))
% data.dof = reshape(sum(~isnan(tmptrial), 1), nchan, length(tmptime));
data.trial = tmptrial;
data.time = time;
data.dimord = 'rpt_chan_time';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = timelock2raw(data)
switch data.dimord
case 'chan_time'
data.trial{1} = data.avg;
data.time = {data.time};
data = rmfield(data, 'avg');
case 'rpt_chan_time'
tmptrial = {};
tmptime = {};
ntrial = size(data.trial,1);
nchan = size(data.trial,2);
ntime = size(data.trial,3);
for i=1:ntrial
tmptrial{i} = reshape(data.trial(i,:,:), [nchan, ntime]);
tmptime{i} = data.time;
end
data = rmfield(data, 'trial');
data.trial = tmptrial;
data.time = tmptime;
case 'subj_chan_time'
tmptrial = {};
tmptime = {};
ntrial = size(data.individual,1);
nchan = size(data.individual,2);
ntime = size(data.individual,3);
for i=1:ntrial
tmptrial{i} = reshape(data.individual(i,:,:), [nchan, ntime]);
tmptime{i} = data.time;
end
data = rmfield(data, 'individual');
data.trial = tmptrial;
data.time = tmptime;
otherwise
error('unsupported dimord');
end
% remove the unwanted fields
if isfield(data, 'avg'), data = rmfield(data, 'avg'); end
if isfield(data, 'var'), data = rmfield(data, 'var'); end
if isfield(data, 'cov'), data = rmfield(data, 'cov'); end
if isfield(data, 'dimord'), data = rmfield(data, 'dimord'); end
if isfield(data, 'numsamples'), data = rmfield(data, 'numsamples'); end
if isfield(data, 'dof'), data = rmfield(data, 'dof'); end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = chan2freq(data)
data.dimord = [data.dimord '_freq'];
data.freq = 0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = chan2timelock(data)
data.dimord = [data.dimord '_time'];
data.time = 0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [spike] = raw2spike(data)
fprintf('converting raw data into spike data\n');
nTrials = length(data.trial);
[spikelabel] = detectspikechan(data);
spikesel = match_str(data.label, spikelabel);
nUnits = length(spikesel);
if nUnits==0
error('cannot convert raw data to spike format since the raw data structure does not contain spike channels');
end
trialTimes = zeros(nTrials,2);
for iUnit = 1:nUnits
unitIndx = spikesel(iUnit);
spikeTimes = []; % we dont know how large it will be, so use concatenation inside loop
trialInds = [];
for iTrial = 1:nTrials
% read in the spike times
[spikeTimesTrial] = getspiketimes(data, iTrial, unitIndx);
nSpikes = length(spikeTimesTrial);
spikeTimes = [spikeTimes; spikeTimesTrial(:)];
trialInds = [trialInds; ones(nSpikes,1)*iTrial];
% get the begs and ends of trials
hasNum = find(~isnan(data.time{iTrial}));
if iUnit==1, trialTimes(iTrial,:) = data.time{iTrial}([hasNum(1) hasNum(end)]); end
end
spike.label{iUnit} = data.label{unitIndx};
spike.waveform{iUnit} = [];
spike.time{iUnit} = spikeTimes(:)';
spike.trial{iUnit} = trialInds(:)';
if iUnit==1, spike.trialtime = trialTimes; end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = spike2raw(spike, fsample)
if nargin<2 || isempty(fsample)
timeDiff = abs(diff(sort([spike.time{:}])));
fsample = 1/min(timeDiff(timeDiff>0));
warning('Desired sampling rate for spike data not specified, automatically resampled to %f', fsample);
end
% get some sizes
nUnits = length(spike.label);
nTrials = size(spike.trialtime,1);
% preallocate
data.trial(1:nTrials) = {[]};
data.time(1:nTrials) = {[]};
for iTrial = 1:nTrials
% make bins: note that the spike.time is already within spike.trialtime
x = [spike.trialtime(iTrial,1):(1/fsample):spike.trialtime(iTrial,2)];
timeBins = [x x(end)+1/fsample] - (0.5/fsample);
time = (spike.trialtime(iTrial,1):(1/fsample):spike.trialtime(iTrial,2));
% convert to continuous
trialData = zeros(nUnits,length(time));
for iUnit = 1:nUnits
% get the timestamps and only select those timestamps that are in the trial
ts = spike.time{iUnit};
hasTrial = spike.trial{iUnit}==iTrial;
ts = ts(hasTrial);
N = histc(ts,timeBins);
if isempty(N)
N = zeros(1,length(timeBins)-1);
else
N(end) = [];
end
% store it in a matrix
trialData(iUnit,:) = N;
end
data.trial{iTrial} = trialData;
data.time{iTrial} = time;
end % for all trials
% create the associated labels and other aspects of data such as the header
data.label = spike.label;
data.fsample = fsample;
if isfield(spike,'hdr'), data.hdr = spike.hdr; end
if isfield(spike,'cfg'), data.cfg = spike.cfg; end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert between datatypes
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [data] = source2raw(source)
fn = fieldnames(source);
fn = setdiff(fn, {'pos', 'dim', 'transform', 'time', 'freq', 'cfg'});
for i=1:length(fn)
dimord{i} = getdimord(source, fn{i});
end
sel = strcmp(dimord, 'pos_time');
assert(sum(sel)>0, 'the source structure does not contain a suitable field to represent as raw channel-level data');
assert(sum(sel)<2, 'the source structure contains multiple fields that can be represented as raw channel-level data');
fn = fn{sel};
dimord = dimord{sel};
switch dimord
case 'pos_time'
% add fake raw channel data to the original data structure
data.trial{1} = source.(fn);
data.time{1} = source.time;
% add fake channel labels
data.label = {};
for i=1:size(source.pos,1)
data.label{i} = sprintf('source%d', i);
end
data.label = data.label(:);
data.cfg = source.cfg;
otherwise
% FIXME other formats could be implemented as well
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION for detection of channels
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [spikelabel, eeglabel] = detectspikechan(data)
maxRate = 2000; % default on what we still consider a neuronal signal: this firing rate should never be exceeded
% 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);
T = nansum(diff(data.time{i}),2); % total time
fr = nansum(data.trial{i}(j,:),2) ./ T;
spikechan(j) = spikechan(j) + double(hasAllInts & hasAllPosInts & fr<=maxRate);
end
end
spikechan = (spikechan==ntrial);
spikelabel = data.label(spikechan);
eeglabel = data.label(~spikechan);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [spikeTimes] = getspiketimes(data, trial, unit)
spikeIndx = logical(data.trial{trial}(unit,:));
spikeCount = data.trial{trial}(unit,spikeIndx);
spikeTimes = data.time{trial}(spikeIndx);
if isempty(spikeTimes), return; end
multiSpikes = find(spikeCount>1);
% get the additional samples and spike times, we need only loop through the bins
[addSamples, addTimes] = deal([]);
for iBin = multiSpikes(:)' % looping over row vector
addTimes = [addTimes ones(1,spikeCount(iBin))*spikeTimes(iBin)];
addSamples = [addSamples ones(1,spikeCount(iBin))*spikeIndx(iBin)];
end
% before adding these times, first remove the old ones
spikeTimes(multiSpikes) = [];
spikeTimes = sort([spikeTimes(:); addTimes(:)]);
|
github
|
lcnhappe/happe-master
|
read_yokogawa_data.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_yokogawa_data.m
| 10,974 |
utf_8
|
493fda2552516eab52e525c3387a7397
|
function [dat] = read_yokogawa_data(filename, hdr, begsample, endsample, chanindx)
% READ_YOKAGAWA_DATA reads continuous, epoched or averaged MEG data
% that has been generated by the Yokogawa MEG system and software
% and allows that data to be used in combination with FieldTrip.
%
% Use as
% [dat] = read_yokogawa_data(filename, hdr, begsample, endsample, chanindx)
%
% This is a wrapper function around the functions
% GetMeg160ContinuousRawDataM
% GetMeg160EvokedAverageDataM
% GetMeg160EvokedRawDataM
%
% See also READ_YOKOGAWA_HEADER, READ_YOKOGAWA_EVENT
% Copyright (C) 2005, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.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 ~ft_hastoolbox('yokogawa')
error('cannot determine whether Yokogawa toolbox is present');
end
% hdr = read_yokogawa_header(filename);
hdr = hdr.orig; % use the original Yokogawa header, not the FieldTrip header
% default is to select all channels
if nargin<5
chanindx = 1:hdr.channel_count;
end
handles = definehandles;
fid = fopen(filename, 'rb', 'ieee-le');
switch hdr.acq_type
case handles.AcqTypeEvokedAve
% Data is returned by double.
start_sample = begsample - 1; % samples start at 0
sample_length = endsample - begsample + 1;
epoch_count = 1;
start_epoch = 0;
dat = double(GetMeg160EvokedAverageDataM( fid, start_sample, sample_length ));
% the first extra sample is the channel number
channum = dat(:,1);
dat = dat(:,2:end);
case handles.AcqTypeContinuousRaw
% Data is returned by int16.
start_sample = begsample - 1; % samples start at 0
sample_length = endsample - begsample + 1;
epoch_count = 1;
start_epoch = 0;
dat = double(GetMeg160ContinuousRawDataM( fid, start_sample, sample_length ));
% the first extra sample is the channel number
channum = dat(:,1);
dat = dat(:,2:end);
case handles.AcqTypeEvokedRaw
% Data is returned by int16.
begtrial = ceil(begsample/hdr.sample_count);
endtrial = ceil(endsample/hdr.sample_count);
if begtrial<1
error('cannot read before the begin of the file');
elseif endtrial>hdr.actual_epoch_count
error('cannot read beyond the end of the file');
end
epoch_count = endtrial-begtrial+1;
start_epoch = begtrial-1;
% read all the neccessary trials that contain the desired samples
dat = double(GetMeg160EvokedRawDataM( fid, start_epoch, epoch_count ));
% the first extra sample is the channel number
channum = dat(:,1);
dat = dat(:,2:end);
if size(dat,2)~=epoch_count*hdr.sample_count
error('could not read all epochs');
end
rawbegsample = begsample - (begtrial-1)*hdr.sample_count;
rawendsample = endsample - (begtrial-1)*hdr.sample_count;
sample_length = rawendsample - rawbegsample + 1;
% select the desired samples from the complete trials
dat = dat(:,rawbegsample:rawendsample);
otherwise
error('unknown data type');
end
fclose(fid);
if size(dat,1)~=hdr.channel_count
error('could not read all channels');
elseif size(dat,2)~=(endsample-begsample+1)
error('could not read all samples');
end
% Count of AxialGradioMeter
ch_type = hdr.channel_info(:,2);
index = find(ch_type==[handles.AxialGradioMeter]);
axialgradiometer_index_tmp = index;
axialgradiometer_ch_count = length(index);
% Count of PlannerGradioMeter
ch_type = hdr.channel_info(:,2);
index = find(ch_type==[handles.PlannerGradioMeter]);
plannergradiometer_index_tmp = index;
plannergradiometer_ch_count = length(index);
% Count of EegChannel
ch_type = hdr.channel_info(:,2);
index = find(ch_type==[handles.EegChannel]);
eegchannel_index_tmp = index;
eegchannel_ch_count = length(index);
% Count of NullChannel
ch_type = hdr.channel_info(:,2);
index = find(ch_type==[handles.NullChannel]);
nullchannel_index_tmp = index;
nullchannel_ch_count = length(index);
%%% Pulling out AxialGradioMeter and value conversion to physical units.
if ~isempty(axialgradiometer_index_tmp)
% Acquisition of channel information
axialgradiometer_index = axialgradiometer_index_tmp;
ch_info = hdr.channel_info;
axialgradiometer_ch_info = ch_info(axialgradiometer_index, :);
% Value conversion
% B = ( ADValue * VoltRange / ADRange - Offset ) * Sensitivity / FLLGain
calib = hdr.calib_info;
amp_gain = hdr.amp_gain(1);
tmp_ch_no = channum(axialgradiometer_index, 1);
tmp_data = dat(axialgradiometer_index, 1:sample_length);
tmp_offset = calib(axialgradiometer_index, 3) * ones(1,sample_length);
ad_range = 5/2^(hdr.ad_bit-1);
tmp_data = ( tmp_data * ad_range - tmp_offset );
clear tmp_offset;
tmp_gain = calib(axialgradiometer_index, 2) * ones(1,sample_length);
tmp_data = tmp_data .* tmp_gain / amp_gain;
dat(axialgradiometer_index, 1:sample_length) = tmp_data;
clear tmp_gain;
% Deletion of Inf row
index = find(axialgradiometer_ch_info(1,:) == Inf);
axialgradiometer_ch_info(:,index) = [];
% Deletion of channel_type row
axialgradiometer_ch_info(:,2) = [];
% Outputs to the global variable
handles.sqd.axialgradiometer_ch_info = axialgradiometer_ch_info;
handles.sqd.axialgradiometer_ch_no = tmp_ch_no;
handles.sqd.axialgradiometer_data = [ tmp_ch_no tmp_data];
clear tmp_data;
end
%%% Pulling out PlannerGradioMeter and value conversion to physical units.
if ~isempty(plannergradiometer_index_tmp)
% Acquisition of channel information
plannergradiometer_index = plannergradiometer_index_tmp;
ch_info = hdr.channel_info;
plannergradiometer_ch_info = ch_info(plannergradiometer_index, :);
% Value conversion
% B = ( ADValue * VoltRange / ADRange - Offset ) * Sensitivity / FLLGain
calib = hdr.calib_info;
amp_gain = hdr.amp_gain(1);
tmp_ch_no = channum(plannergradiometer_index, 1);
tmp_data = dat(plannergradiometer_index, 1:sample_length);
tmp_offset = calib(plannergradiometer_index, 3) * ones(1,sample_length);
ad_range = 5/2^(hdr.ad_bit-1);
tmp_data = ( tmp_data * ad_range - tmp_offset );
clear tmp_offset;
tmp_gain = calib(plannergradiometer_index, 2) * ones(1,sample_length);
tmp_data = tmp_data .* tmp_gain / amp_gain;
dat(plannergradiometer_index, 1:sample_length) = tmp_data;
clear tmp_gain;
% Deletion of Inf row
index = find(plannergradiometer_ch_info(1,:) == Inf);
plannergradiometer_ch_info(:,index) = [];
% Deletion of channel_type row
plannergradiometer_ch_info(:,2) = [];
% Outputs to the global variable
handles.sqd.plannergradiometer_ch_info = plannergradiometer_ch_info;
handles.sqd.plannergradiometer_ch_no = tmp_ch_no;
handles.sqd.plannergradiometer_data = [ tmp_ch_no tmp_data];
clear tmp_data;
end
%%% Pulling out EegChannel Channel and value conversion to Volt units.
if ~isempty(eegchannel_index_tmp)
% Acquisition of channel information
eegchannel_index = eegchannel_index_tmp;
% Value conversion
% B = ADValue * VoltRange / ADRange
tmp_ch_no = channum(eegchannel_index, 1);
tmp_data = dat(eegchannel_index, 1:sample_length);
ad_range = 5/2^(hdr.ad_bit-1);
tmp_data = tmp_data * ad_range;
dat(eegchannel_index, 1:sample_length) = tmp_data;
% Outputs to the global variable
handles.sqd.eegchannel_ch_no = tmp_ch_no;
handles.sqd.eegchannel_data = [ tmp_ch_no tmp_data];
clear tmp_data;
end
%%% Pulling out Null Channel and value conversion to Volt units.
if ~isempty(nullchannel_index_tmp)
% Acquisition of channel information
nullchannel_index = nullchannel_index_tmp;
% Value conversion
% B = ADValue * VoltRange / ADRange
tmp_ch_no = channum(nullchannel_index, 1);
tmp_data = dat(nullchannel_index, 1:sample_length);
ad_range = 5/2^(hdr.ad_bit-1);
tmp_data = tmp_data * ad_range;
dat(nullchannel_index, 1:sample_length) = tmp_data;
% Outputs to the global variable
handles.sqd.nullchannel_ch_no = tmp_ch_no;
handles.sqd.nullchannel_data = [ tmp_ch_no tmp_data];
clear tmp_data;
end
% select only the desired channels
dat = dat(chanindx,:);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this defines some usefull constants
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles = definehandles
handles.output = [];
handles.sqd_load_flag = false;
handles.mri_load_flag = false;
handles.NullChannel = 0;
handles.MagnetoMeter = 1;
handles.AxialGradioMeter = 2;
handles.PlannerGradioMeter = 3;
handles.RefferenceChannelMark = hex2dec('0100');
handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter );
handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter );
handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter );
handles.TriggerChannel = -1;
handles.EegChannel = -2;
handles.EcgChannel = -3;
handles.EtcChannel = -4;
handles.NonMegChannelNameLength = 32;
handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length
handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter
handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length
handles.AcqTypeContinuousRaw = 1;
handles.AcqTypeEvokedAve = 2;
handles.AcqTypeEvokedRaw = 3;
handles.sqd = [];
handles.sqd.selected_start = [];
handles.sqd.selected_end = [];
handles.sqd.axialgradiometer_ch_no = [];
handles.sqd.axialgradiometer_ch_info = [];
handles.sqd.axialgradiometer_data = [];
handles.sqd.plannergradiometer_ch_no = [];
handles.sqd.plannergradiometer_ch_info = [];
handles.sqd.plannergradiometer_data = [];
handles.sqd.eegchannel_ch_no = [];
handles.sqd.eegchannel_data = [];
handles.sqd.nullchannel_ch_no = [];
handles.sqd.nullchannel_data = [];
handles.sqd.selected_time = [];
handles.sqd.sample_rate = [];
handles.sqd.sample_count = [];
handles.sqd.pretrigger_length = [];
handles.sqd.matching_info = [];
handles.sqd.source_info = [];
handles.sqd.mri_info = [];
handles.mri = [];
|
github
|
lcnhappe/happe-master
|
decode_fif.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/decode_fif.m
| 5,978 |
utf_8
|
d33206202f4aa5a18ba3ada03de48664
|
function [info] = decode_fif(orig)
% DECODE_FIF is a helper function for real-time processing of Neuromag data. This
% function is used to decode the content of the optional neuromag_fif chunk(s).
%
% See also DECODE_RES4, DECODE_NIFTI1, SAP2MATLAB
% Copyright (C) 2013 Arjen Stolk & 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 that the required low-level toolbox is available
ft_hastoolbox('mne', 1);
global FIFF
if isempty(FIFF)
FIFF = fiff_define_constants();
end
if isfield(orig, 'neuromag_header')
% The binary blob was created on the little-endian Intel Linux acquisition
% computer, whereas the default for fiff files is that they are stored in
% big-endian byte order. MATLAB is able to swap the bytes on the fly by specifying
% 'le" or "be" to fopen. The normal MNE fiff_open function assumes that it is big
% endian, hence here we have to open it as little endian.
filename = tempname;
% write the binary blob to disk, byte-by-byte to avoid any swapping between little and big-endian content
F = fopen(filename, 'w');
fwrite(F, orig.neuromag_header, 'uint8');
fclose(F);
% read the content of the file using the standard reading functions
[info, meas] = read_header(filename);
% clean up the temporary file
delete(filename);
end
% Typically, at the end of acquisition, the isotrak and hpiresult information
% is stored in the neuromag fiff container which can then (offline) be read by
% fiff_read_meas_info. However, for the purpose of head position monitoring
% (see Stolk et al., Neuroimage 2013) during acquisition, this crucial
% information requires to be accessible online. read_isotrak and read_hpiresult
% can extract information from the additionally chunked (neuromag2ft) files.
if isfield(orig, 'neuromag_isotrak')
filename = tempname;
% write the binary blob to disk, byte-by-byte to avoid any swapping between little and big-endian content
F = fopen(filename, 'w');
fwrite(F, orig.neuromag_isotrak, 'uint8');
fclose(F);
% read the content of the file using the standard reading functions
[info.dig] = read_isotrak(filename);
% clean up the temporary file
delete(filename);
end
if isfield(orig, 'neuromag_hpiresult')
filename = tempname;
% write the binary blob to disk, byte-by-byte to avoid any swapping between little and big-endian content
F = fopen(filename, 'w');
fwrite(F, orig.neuromag_hpiresult, 'uint8');
fclose(F);
% read the content of the file using the standard reading functions
[info.dev_head_t, info.ctf_head_t] = read_hpiresult(filename);
% clean up the temporary file
delete(filename);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [info, meas] = read_header(filename)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% open and read the file as little endian
[fid, tree] = fiff_open_le(filename); % open as little endian
[info, meas] = fiff_read_meas_info(fid, tree);
fclose(fid);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dig] = read_isotrak(filename)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
global FIFF
% open the isotrak file (big endian)
% (typically stored in meas_info dir during acquisition, no fif extension required)
[fid, tree] = fiff_open(filename);
% locate the Polhemus data
isotrak = fiff_dir_tree_find(tree,FIFF.FIFFB_ISOTRAK);
dig=struct('kind',{},'ident',{},'r',{},'coord_frame',{});
coord_frame = FIFF.FIFFV_COORD_HEAD;
if length(isotrak) == 1
p = 0;
for k = 1:isotrak.nent
kind = isotrak.dir(k).kind;
pos = isotrak.dir(k).pos;
if kind == FIFF.FIFF_DIG_POINT
p = p + 1;
tag = fiff_read_tag(fid,pos);
dig(p) = tag.data;
else
if kind == FIFF.FIFF_MNE_COORD_FRAME
tag = fiff_read_tag(fid,pos);
coord_frame = tag.data;
elseif kind == FIFF.FIFF_COORD_TRANS
tag = fiff_read_tag(fid,pos);
dig_trans = tag.data;
end
end
end
end
for k = 1:length(dig)
dig(k).coord_frame = coord_frame;
end
if exist('dig_trans','var')
if (dig_trans.from ~= coord_frame && dig_trans.to ~= coord_frame)
clear('dig_trans');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [dev_head_t, ctf_head_t] = read_hpiresult(filename)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
global FIFF
% open the hpiresult file (big endian)
% (typically stored in meas_info dir during acquisition, no fif extension required)
[fid, tree] = fiff_open(filename);
% locate the transformation matrix
dev_head_t=[];
ctf_head_t=[];
hpi_result = fiff_dir_tree_find(tree,FIFF.FIFFB_HPI_RESULT);
if length(hpi_result) == 1
for k = 1:hpi_result.nent
kind = hpi_result.dir(k).kind;
pos = hpi_result.dir(k).pos;
if kind == FIFF.FIFF_COORD_TRANS
tag = fiff_read_tag(fid,pos);
cand = tag.data;
if cand.from == FIFF.FIFFV_COORD_DEVICE && ...
cand.to == FIFF.FIFFV_COORD_HEAD
dev_head_t = cand;
elseif cand.from == FIFF.FIFFV_MNE_COORD_CTF_HEAD && ...
cand.to == FIFF.FIFFV_COORD_HEAD
ctf_head_t = cand;
end
end
end
end
|
github
|
lcnhappe/happe-master
|
read_biff.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_biff.m
| 5,799 |
utf_8
|
78a82ce91f8383fd0f478b921280d6bb
|
function [this] = read_biff(filename, opt)
% READ_BIFF reads data and header information from a BIFF file
%
% This is a attemt for a reference implementation to read the BIFF
% file format as defined by the Clinical Neurophysiology department of
% the University Medical Centre, Nijmegen.
%
% read all data and information
% [data] = read_biff(filename)
% or read a selected top-level chunk
% [chunk] = read_biff(filename, chunkID)
%
% known top-level chunk id's are
% data : measured data (matrix)
% dati : information on data (struct)
% expi : information on experiment (struct)
% pati : information on patient (struct)
% evnt : event markers (struct)
% Copyright (C) 2000, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.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$
define_biff;
this = [];
fid = fopen(filename, 'r');
fseek(fid,0,'eof');
eof = ftell(fid);
fseek(fid,0,'bof');
[id, siz] = chunk_header(fid);
switch id
case 'SEMG'
child = subtree(BIFF, id);
this = read_biff_chunk(fid, id, siz, child);
case 'LIST'
fprintf('skipping unimplemented chunk id="%s" size=%4d\n', id, siz);
case 'CAT '
fprintf('skipping unimplemented chunk id="%s" size=%4d\n', id, siz);
otherwise
fprintf('skipping unrecognized chunk id="%s" size=%4d\n', id, siz);
fseek(fid, siz, 'cof');
end % switch
fclose(fid); % close file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION read_biff_chunk
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function this = read_biff_chunk(fid, id, siz, chunk)
% start with empty structure
this = [];
if strcmp(id, 'null') % this is an empty chunk
fprintf('skipping empty chunk id="%s" size=%4d\n', id, siz);
assert(~feof(fid));
fseek(fid, siz, 'cof');
elseif isempty(chunk) % this is an unrecognized chunk
fprintf('skipping unrecognized chunk id="%s" size=%4d\n', id, siz);
assert(~feof(fid));
fseek(fid, siz, 'cof');
else
eoc = ftell(fid) + siz;
name = char(chunk.desc(2));
type = char(chunk.desc(3));
fprintf('reading chunk id= "%s" size=%4d name="%s"\n', id, siz, name);
switch type
case 'group'
while ~feof(fid) & ftell(fid)<eoc
% read all subchunks
[id, siz] = chunk_header(fid);
child = subtree(chunk, id);
if ~isempty(child)
% read data and add subchunk data to chunk structure
name = char(child.desc(2));
val = read_biff_chunk(fid, id, siz, child);
this = setfield(this, name, val);
else
fprintf('skipping unrecognized chunk id="%s" size=%4d\n', id, siz);
fseek(fid, siz, 'cof');
end
end % while
case 'string'
this = char(fread(fid, siz, 'uchar')');
case {'char', 'uchar', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'float32', 'float64'}
this = fread(fid, 1, type);
case {'char', 'uchar', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'float32', 'float64'}
this = fread(fid, 1, type);
case {'int8vec', 'int16vec', 'int32vec', 'int64vec', 'uint8vec', 'uint16vec', 'uint32vec', 'float32vec', 'float64vec'}
ncol = fread(fid, 1, 'uint32');
this = fread(fid, ncol, type(1:(length(type)-3)));
case {'int8mat', 'int16mat', 'int32mat', 'int64mat', 'uint8mat', 'uint16mat', 'uint32mat', 'float32mat', 'float64mat'}
nrow = fread(fid, 1, 'uint32');
ncol = fread(fid, 1, 'uint32');
this = fread(fid, [nrow, ncol], type(1:(length(type)-3)));
otherwise
fseek(fid, siz, 'cof'); % skip this chunk
sprintf('unimplemented data type "%s" in chunk "%s"', type, id);
% warning(ans);
end % switch chunk type
end % else
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION subtree
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function child = subtree(parent, id)
blank = findstr(id, ' ');
while ~isempty(blank)
id(blank) = '_';
blank = findstr(id, ' ');
end
elem = fieldnames(parent); % list of all subitems
num = find(strcmp(elem, id)); % number in parent tree
if size(num) == [1,1]
child = getfield(parent, char(elem(num))); % child subtree
else
child = [];
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION chunk_header
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [id, siz] = chunk_header(fid)
id = char(fread(fid, 4, 'uchar')'); % read chunk ID
siz = fread(fid, 1, 'uint32'); % read chunk size
if strcmp(id, 'GRP ') | strcmp(id, 'BIFF')
id = char(fread(fid, 4, 'uchar')'); % read real chunk ID
siz = siz - 4; % reduce size by 4
end
|
github
|
lcnhappe/happe-master
|
read_eeglabheader.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_eeglabheader.m
| 2,267 |
utf_8
|
f76d1bbb9aa657b05643502ef19fdb10
|
% read_eeglabheader() - import EEGLAB dataset files
%
% Usage:
% >> header = read_eeglabheader(filename);
%
% Inputs:
% filename - [string] file name
%
% Outputs:
% header - FILEIO toolbox type structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2008-
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function header = read_eeglabheader(filename)
if nargin < 1
help read_eeglabheader;
return;
end;
if ~isstruct(filename)
load('-mat', filename);
else
EEG = filename;
end;
header.Fs = EEG.srate;
header.nChans = EEG.nbchan;
header.nSamples = EEG.pnts;
header.nSamplesPre = -EEG.xmin*EEG.srate;
header.nTrials = EEG.trials;
try
header.label = { EEG.chanlocs.labels }';
catch
warning('creating default channel names');
for i=1:header.nChans
header.label{i} = sprintf('chan%03d', i);
end
end
ind = 1;
for i = 1:length( EEG.chanlocs )
if isfield(EEG.chanlocs(i), 'X') && ~isempty(EEG.chanlocs(i).X)
header.elec.label{ind, 1} = EEG.chanlocs(i).labels;
% this channel has a position
header.elec.elecpos(ind,1) = EEG.chanlocs(i).X;
header.elec.elecpos(ind,2) = EEG.chanlocs(i).Y;
header.elec.elecpos(ind,3) = EEG.chanlocs(i).Z;
ind = ind+1;
end;
end;
% remove data
% -----------
%if isfield(EEG, 'datfile')
% if ~isempty(EEG.datfile)
% EEG.data = EEG.datfile;
% end;
%else
% EEG.data = 'in set file';
%end;
EEG.icaact = [];
header.orig = EEG;
|
github
|
lcnhappe/happe-master
|
read_ctf_svl.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_ctf_svl.m
| 3,812 |
utf_8
|
d3442d0a013cf5e0a8d4277d99e45206
|
% [data, hdr] = opensvl(filename)
%
% Reads a CTF SAM (.svl) file.
function [data, hdr] = read_ctf_svl(filename)
fid = fopen(filename, 'rb', 'ieee-be', 'ISO-8859-1');
if fid <= 0
error('Could not open SAM file: %s\n', filename);
end
% ----------------------------------------------------------------------
% Read header.
hdr.identity = fread(fid, 8, '*char')'; % 'SAMIMAGE'
hdr.version = fread(fid, 1, 'int32'); % SAM file version.
hdr.setName = fread(fid, 256, '*char')'; % Dataset name.
hdr.numChans = fread(fid, 1, 'int32');
hdr.numWeights = fread(fid, 1, 'int32'); % 0 for static image.
if(hdr.numWeights ~= 0)
warning('hdr.numWeights ~= 0');
end
fread(fid,1,'int32'); % Padding to next 8 byte boundary.
hdr.xmin = fread(fid, 1, 'double'); % Bounding box coordinates (m).
hdr.xmax = fread(fid, 1, 'double');
hdr.ymin = fread(fid, 1, 'double');
hdr.ymax = fread(fid, 1, 'double');
hdr.zmin = fread(fid, 1, 'double');
hdr.zmax = fread(fid, 1, 'double');
hdr.stepSize = fread(fid, 1, 'double'); % m
hdr.hpFreq = fread(fid, 1, 'double'); % High pass filtering frequency (Hz).
hdr.lpFreq = fread(fid, 1, 'double'); % Low pass.
hdr.bwFreq = fread(fid, 1, 'double'); % Bandwidth
hdr.meanNoise = fread(fid, 1, 'double'); % Sensor noise (T).
hdr.mriName = fread(fid, 256, '*char')';
hdr.fiducial.mri.nas = fread(fid, 3, 'int32'); % CTF MRI voxel coordinates?
hdr.fiducial.mri.rpa = fread(fid, 3, 'int32');
hdr.fiducial.mri.lpa = fread(fid, 3, 'int32');
hdr.SAMType = fread(fid, 1, 'int32'); % 0: image, 1: weights array, 2: weights list.
hdr.SAMUnit = fread(fid, 1, 'int32');
% Possible values: 0 coefficients Am/T, 1 moment Am, 2 power (Am)^2, 3 Z,
% 4 F, 5 T, 6 probability, 7 MUSIC.
fread(fid, 1, 'int32'); % Padding to next 8 byte boundary.
if hdr.version > 1
% Version 2 has extra fields.
hdr.fiducial.head.nas = fread(fid, 3, 'double'); % CTF head coordinates?
hdr.fiducial.head.rpa = fread(fid, 3, 'double');
hdr.fiducial.head.lpa = fread(fid, 3, 'double');
hdr.SAMUnitName = fread(fid, 32, '*char')';
% Possible values: 'Am/T' SAM coefficients, 'Am' source strength,
% '(Am)^2' source power, ('Z', 'F', 'T') statistics, 'P' probability.
end
% ----------------------------------------------------------------------
% Read image data.
data = fread(fid, inf, 'double');
fclose(fid);
% Raw image data is ordered as a C array with indices: [x][y][z], meaning
% z changes fastest and x slowest. These x, y, z axes point to ALS
% (anterior, left, superior) respectively in real world coordinates,
% which means the voxels are in SLA order.
% ----------------------------------------------------------------------
% Post processing.
% Change from m to mm.
hdr.xmin = hdr.xmin * 1000;
hdr.ymin = hdr.ymin * 1000;
hdr.zmin = hdr.zmin * 1000;
hdr.xmax = hdr.xmax * 1000;
hdr.ymax = hdr.ymax * 1000;
hdr.zmax = hdr.zmax * 1000;
hdr.stepSize = hdr.stepSize * 1000;
% Number of voxels in each dimension.
hdr.dim = [round((hdr.xmax - hdr.xmin)/hdr.stepSize) + 1, ...
round((hdr.ymax - hdr.ymin)/hdr.stepSize) + 1, ...
round((hdr.zmax - hdr.zmin)/hdr.stepSize) + 1];
data = reshape(data, hdr.dim([3, 2, 1]));
% Build transformation matrix from raw voxel coordinates (indexed from 1)
% to head coordinates in mm. Note that the bounding box is given in
% these coordinates (in m, but converted above).
% Apply scaling.
hdr.transform = diag([hdr.stepSize * ones(1, 3), 1]);
% Reorder directions.
hdr.transform = hdr.transform(:, [3, 2, 1, 4]);
% Apply translation.
hdr.transform(1:3, 4) = [hdr.xmin; hdr.ymin; hdr.zmin] - hdr.stepSize;
% -step is needed since voxels are indexed from 1.
end
|
github
|
lcnhappe/happe-master
|
read_erplabevent.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_erplabevent.m
| 1,786 |
utf_8
|
40ece49ff6bd2afd6024b46f210e65fa
|
% read_erplabevent() - import ERPLAB dataset events
%
% Usage:
% >> event = read_erplabevent(filename, ...);
%
% Inputs:
% filename - [string] file name
%
% Optional inputs:
% 'header' - FILEIO structure header
%
% Outputs:
% event - FILEIO toolbox event structure
%
% Modified from read_eeglabevent
%123456789012345678901234567890123456789012345678901234567890123456789012
%
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function event = read_erplabevent(filename, varargin)
if nargin < 1
help read_erplabheader;
return;
end;
hdr = ft_getopt(varargin, 'header');
if isempty(hdr)
hdr = read_erplabheader(filename);
end
event = []; % these will be the output in FieldTrip format
oldevent = hdr.orig.bindescr; % these are in ERPLAB format
for index = 1:length(oldevent)
event(end+1).type = 'trial';
event(end ).sample = (index-1)*hdr.nSamples + 1;
event(end ).value = oldevent{index};
event(end ).offset = -hdr.nSamplesPre;
event(end ).duration = hdr.nSamples;
end;
|
github
|
lcnhappe/happe-master
|
read_yokogawa_header_new.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_yokogawa_header_new.m
| 8,887 |
utf_8
|
70f6185e29007e7790efc5a8cb91bf23
|
function hdr = read_yokogawa_header_new(filename)
% READ_YOKOGAWA_HEADER_NEW reads the header information from continuous,
% epoched or averaged MEG data that has been generated by the Yokogawa
% MEG system and software and allows that data to be used in combination
% with FieldTrip.
%
% Use as
% [hdr] = read_yokogawa_header_new(filename)
%
% This is a wrapper function around the functions
% getYkgwHdrSystem
% getYkgwHdrChannel
% getYkgwHdrAcqCond
% getYkgwHdrCoregist
% getYkgwHdrDigitize
% getYkgwHdrSource
%
% See also READ_YOKOGAWA_DATA_NEW, READ_YOKOGAWA_EVENT
% **
% Copyright (C) 2005, Robert Oostenveld and 2010, Tilmann Sander-Thoemmes
%
% 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$
% FIXED
% txt -> m
% fopen iee-le
if ~ft_hastoolbox('yokogawa_meg_reader')
error('cannot determine whether Yokogawa toolbox is present');
end
handles = definehandles;
sys_info = getYkgwHdrSystem(filename);
id = sys_info.system_id;
ver = sys_info.version;
rev = sys_info.revision;
sys_name = sys_info.system_name;
model_name = sys_info.model_name;
clear('sys_info'); % remove structure as local variables are collected in the end
channel_info = getYkgwHdrChannel(filename);
channel_count = channel_info.channel_count;
acq_cond = getYkgwHdrAcqCond(filename);
acq_type = acq_cond.acq_type;
% these depend on the data type
sample_rate = [];
sample_count = [];
pretrigger_length = [];
averaged_count = [];
actual_epoch_count = [];
switch acq_type
case handles.AcqTypeContinuousRaw
sample_rate = acq_cond.sample_rate;
sample_count = acq_cond.sample_count;
if isempty(sample_rate) | isempty(sample_count)
error('invalid sample rate or sample count in ', filename);
return;
end
pretrigger_length = 0;
averaged_count = 1;
case handles.AcqTypeEvokedAve
sample_rate = acq_cond.sample_rate;
sample_count = acq_cond.frame_length;
pretrigger_length = acq_cond.pretrigger_length;
averaged_count = acq_cond.average_count;
if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(averaged_count)
error('invalid sample rate or sample count or pretrigger length or average count in ', filename);
return;
end
if acq_cond.multi_trigger.enable
error('multi trigger mode not supported for ', filename);
return;
end
case handles.AcqTypeEvokedRaw
sample_rate = acq_cond.sample_rate;
sample_count = acq_cond.frame_length;
pretrigger_length = acq_cond.pretrigger_length;
actual_epoch_count = acq_cond.average_count;
if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(actual_epoch_count)
error('invalid sample rate or sample count or pretrigger length or epoch count in ', filename);
return;
end
if acq_cond.multi_trigger.enable
error('multi trigger mode not supported for ', filename);
return;
end
otherwise
error('unknown data type');
end
clear('acq_cond'); % remove structure as local variables are collected in the end
coregist = getYkgwHdrCoregist(filename);
digitize = getYkgwHdrDigitize(filename);
source = getYkgwHdrSource(filename);
% put all local variables into a structure, this is a bit unusual matlab programming style
tmp = whos;
orig = [];
for i=1:length(tmp)
if isempty(strmatch(tmp(i).name, {'tmp', 'ans', 'handles'}))
orig = setfield(orig, tmp(i).name, eval(tmp(i).name));
end
end
% convert the original header information into something that FieldTrip understands
hdr = [];
hdr.orig = orig; % also store the original full header information
hdr.Fs = orig.sample_rate; % sampling frequency
hdr.nChans = orig.channel_count; % number of channels
hdr.nSamples = []; % number of samples per trial
hdr.nSamplesPre = []; % number of pre-trigger samples in each trial
hdr.nTrials = []; % number of trials
switch orig.acq_type
case handles.AcqTypeEvokedAve
hdr.nSamples = orig.sample_count;
hdr.nSamplesPre = orig.pretrigger_length;
hdr.nTrials = 1; % only the average, which can be considered as a single trial
case handles.AcqTypeContinuousRaw
hdr.nSamples = orig.sample_count;
hdr.nSamplesPre = 0; % there is no fixed relation between triggers and data
hdr.nTrials = 1; % the continuous data can be considered as a single very long trial
case handles.AcqTypeEvokedRaw
hdr.nSamples = orig.sample_count;
hdr.nSamplesPre = orig.pretrigger_length;
hdr.nTrials = orig.actual_epoch_count;
otherwise
error('unknown acquisition type');
end
% construct a cell-array with labels of each channel
for i=1:hdr.nChans
% this should be consistent with the predefined list in ft_senslabel,
% with yokogawa2grad_new and with ft_channelselection
if hdr.orig.channel_info.channel(i).type == handles.NullChannel
prefix = '';
elseif hdr.orig.channel_info.channel(i).type == handles.MagnetoMeter
prefix = 'M';
elseif hdr.orig.channel_info.channel(i).type == handles.AxialGradioMeter
prefix = 'AG';
elseif hdr.orig.channel_info.channel(i).type == handles.PlannerGradioMeter
prefix = 'PG';
elseif hdr.orig.channel_info.channel(i).type == handles.RefferenceMagnetoMeter
prefix = 'RM';
elseif hdr.orig.channel_info.channel(i).type == handles.RefferenceAxialGradioMeter
prefix = 'RAG';
elseif hdr.orig.channel_info.channel(i).type == handles.RefferencePlannerGradioMeter
prefix = 'RPG';
elseif hdr.orig.channel_info.channel(i).type == handles.TriggerChannel
prefix = 'TRIG';
elseif hdr.orig.channel_info.channel(i).type == handles.EegChannel
prefix = 'EEG';
elseif hdr.orig.channel_info.channel(i).type == handles.EcgChannel
prefix = 'ECG';
elseif hdr.orig.channel_info.channel(i).type == handles.EtcChannel
prefix = 'ETC';
end
hdr.label{i} = sprintf('%s%03d', prefix, i);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this defines some usefull constants
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles = definehandles
handles.output = [];
handles.sqd_load_flag = false;
handles.mri_load_flag = false;
handles.NullChannel = 0;
handles.MagnetoMeter = 1;
handles.AxialGradioMeter = 2;
handles.PlannerGradioMeter = 3;
handles.RefferenceChannelMark = hex2dec('0100');
handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter );
handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter );
handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter );
handles.TriggerChannel = -1;
handles.EegChannel = -2;
handles.EcgChannel = -3;
handles.EtcChannel = -4;
handles.NonMegChannelNameLength = 32;
handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length
handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter
handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length
handles.AcqTypeContinuousRaw = 1;
handles.AcqTypeEvokedAve = 2;
handles.AcqTypeEvokedRaw = 3;
handles.sqd = [];
handles.sqd.selected_start = [];
handles.sqd.selected_end = [];
handles.sqd.axialgradiometer_ch_no = [];
handles.sqd.axialgradiometer_ch_info = [];
handles.sqd.axialgradiometer_data = [];
handles.sqd.plannergradiometer_ch_no = [];
handles.sqd.plannergradiometer_ch_info = [];
handles.sqd.plannergradiometer_data = [];
handles.sqd.eegchannel_ch_no = [];
handles.sqd.eegchannel_data = [];
handles.sqd.nullchannel_ch_no = [];
handles.sqd.nullchannel_data = [];
handles.sqd.selected_time = [];
handles.sqd.sample_rate = [];
handles.sqd.sample_count = [];
handles.sqd.pretrigger_length = [];
handles.sqd.matching_info = [];
handles.sqd.source_info = [];
handles.sqd.mri_info = [];
handles.mri = [];
|
github
|
lcnhappe/happe-master
|
ft_datatype_raw.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/ft_datatype_raw.m
| 11,070 |
utf_8
|
aff8ada66bf72bd5975e10ea4d2a3648
|
function [data] = ft_datatype_raw(data, varargin)
% FT_DATATYPE_RAW describes the FieldTrip MATLAB structure for raw data
%
% The raw datatype represents sensor-level time-domain data typically
% obtained after calling FT_DEFINETRIAL and FT_PREPROCESSING. It contains
% one or multiple segments of data, each represented as Nchan X Ntime
% arrays.
%
% An example of a raw data structure with 151 MEG channels is
%
% label: {151x1 cell} the channel labels (e.g. 'MRC13')
% time: {1x266 cell} the timeaxis [1*Ntime double] per trial
% trial: {1x266 cell} the numeric data [151*Ntime double] per trial
% sampleinfo: [266x2 double] the begin and endsample of each trial relative to the recording on disk
% trialinfo: [266x1 double] optional trigger or condition codes for each trial
% hdr: [1x1 struct] the full header information of the original dataset on disk
% grad: [1x1 struct] information about the sensor array (for EEG it is called elec)
% cfg: [1x1 struct] the configuration used by the function that generated this data structure
%
% Required fields:
% - time, trial, label
%
% Optional fields:
% - sampleinfo, trialinfo, grad, elec, hdr, cfg
%
% Deprecated fields:
% - fsample
%
% Obsoleted fields:
% - offset
%
% Historical fields:
% - cfg, elec, fsample, grad, hdr, label, offset, sampleinfo, time,
% trial, trialdef, see bug2513
%
% Revision history:
%
% (2011/latest) The description of the sensors has changed, see FT_DATATYPE_SENS
% for further information.
%
% (2010v2) The trialdef field has been replaced by the sampleinfo and
% trialinfo fields. The sampleinfo corresponds to trl(:,1:2), the trialinfo
% to trl(4:end).
%
% (2010v1) In 2010/Q3 it shortly contained the trialdef field which was a copy
% of the trial definition (trl) is generated by FT_DEFINETRIAL.
%
% (2007) It used to contain the offset field, which correcponds to trl(:,3).
% Since the offset field is redundant with the time axis, the offset field is
% from now on not present any more. It can be recreated if needed.
%
% (2003) The initial version was defined
%
% See also FT_DATATYPE, FT_DATATYPE_COMP, FT_DATATYPE_TIMELOCK, FT_DATATYPE_FREQ,
% FT_DATATYPE_SPIKE, FT_DATATYPE_SENS
% Copyright (C) 2011, 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 input arguments, which should be specified as key-value pairs
version = ft_getopt(varargin, 'version', 'latest');
hassampleinfo = ft_getopt(varargin, 'hassampleinfo', 'ifmakessense'); % can be yes/no/ifmakessense
hastrialinfo = ft_getopt(varargin, 'hastrialinfo', 'ifmakessense'); % can be yes/no/ifmakessense
% do some sanity checks
assert(isfield(data, 'trial') && isfield(data, 'time') && isfield(data, 'label'), 'inconsistent raw data structure, some field is missing');
assert(length(data.trial)==length(data.time), 'inconsistent number of trials in raw data structure');
for i=1:length(data.trial)
assert(size(data.trial{i},2)==length(data.time{i}), 'inconsistent number of samples in trial %d', i);
assert(size(data.trial{i},1)==length(data.label), 'inconsistent number of channels in trial %d', i);
end
if isequal(hassampleinfo, 'ifmakessense')
hassampleinfo = 'no'; % default to not adding it
if isfield(data, 'sampleinfo') && size(data.sampleinfo,1)~=numel(data.trial)
% it does not make sense, so don't keep it
hassampleinfo = 'no';
end
if isfield(data, 'sampleinfo')
hassampleinfo = 'yes'; % if it's already there, consider keeping it
numsmp = data.sampleinfo(:,2)-data.sampleinfo(:,1)+1;
for i=1:length(data.trial)
if size(data.trial{i},2)~=numsmp(i);
% it does not make sense, so don't keep it
hassampleinfo = 'no';
% the actual removal will be done further down
warning('removing inconsistent sampleinfo');
break;
end
end
end
end
if isequal(hastrialinfo, 'ifmakessense')
hastrialinfo = 'no';
if isfield(data, 'trialinfo')
hastrialinfo = 'yes';
if size(data.trialinfo,1)~=numel(data.trial)
% it does not make sense, so don't keep it
hastrialinfo = 'no';
warning('removing inconsistent trialinfo');
end
end
end
% convert it into true/false
hassampleinfo = istrue(hassampleinfo);
hastrialinfo = istrue(hastrialinfo);
if strcmp(version, 'latest')
version = '2011';
end
if isempty(data)
return;
end
switch version
case '2011'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isfield(data, 'grad')
% ensure that the gradiometer structure is up to date
data.grad = ft_datatype_sens(data.grad);
end
if isfield(data, 'elec')
% ensure that the electrode structure is up to date
data.elec = ft_datatype_sens(data.elec);
end
if ~isfield(data, 'fsample')
for i=1:length(data.time)
if length(data.time{i})>1
data.fsample = 1/mean(diff(data.time{i}));
break
else
data.fsample = nan;
end
end
if isnan(data.fsample)
warning('cannot determine sampling frequency');
end
end
if isfield(data, 'offset')
data = rmfield(data, 'offset');
end
% the trialdef field should be renamed into sampleinfo
if isfield(data, 'trialdef')
data.sampleinfo = data.trialdef;
data = rmfield(data, 'trialdef');
end
if (hassampleinfo && ~isfield(data, 'sampleinfo')) || (hastrialinfo && ~isfield(data, 'trialinfo'))
% try to reconstruct the sampleinfo and trialinfo
data = fixsampleinfo(data);
end
if ~hassampleinfo && isfield(data, 'sampleinfo')
data = rmfield(data, 'sampleinfo');
end
if ~hastrialinfo && isfield(data, 'trialinfo')
data = rmfield(data, 'trialinfo');
end
case '2010v2'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(data, 'fsample')
data.fsample = 1/mean(diff(data.time{1}));
end
if isfield(data, 'offset')
data = rmfield(data, 'offset');
end
% the trialdef field should be renamed into sampleinfo
if isfield(data, 'trialdef')
data.sampleinfo = data.trialdef;
data = rmfield(data, 'trialdef');
end
if (hassampleinfo && ~isfield(data, 'sampleinfo')) || (hastrialinfo && ~isfield(data, 'trialinfo'))
% try to reconstruct the sampleinfo and trialinfo
data = fixsampleinfo(data);
end
if ~hassampleinfo && isfield(data, 'sampleinfo')
data = rmfield(data, 'sampleinfo');
end
if ~hastrialinfo && isfield(data, 'trialinfo')
data = rmfield(data, 'trialinfo');
end
case {'2010v1' '2010'}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(data, 'fsample')
data.fsample = 1/mean(diff(data.time{1}));
end
if isfield(data, 'offset')
data = rmfield(data, 'offset');
end
if ~isfield(data, 'trialdef') && hascfg
% try to find it in the nested configuration history
data.trialdef = ft_findcfg(data.cfg, 'trl');
end
case '2007'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(data, 'fsample')
data.fsample = 1/mean(diff(data.time{1}));
end
if isfield(data, 'offset')
data = rmfield(data, 'offset');
end
case '2003'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isfield(data, 'fsample')
data.fsample = 1/mean(diff(data.time{1}));
end
if ~isfield(data, 'offset')
data.offset = zeros(length(data.time),1);
for i=1:length(data.time);
data.offset(i) = round(data.time{i}(1)*data.fsample);
end
end
otherwise
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
error('unsupported version "%s" for raw datatype', version);
end
% Numerical inaccuracies in the binary representations of floating point
% values may accumulate. The following code corrects for small inaccuracies
% in the time axes of the trials. See http://bugzilla.fcdonders.nl/show_bug.cgi?id=1390
data = fixtimeaxes(data);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function data = fixtimeaxes(data)
if ~isfield(data, 'fsample')
fsample = 1/mean(diff(data.time{1}));
else
fsample = data.fsample;
end
begtime = zeros(1, length(data.time));
endtime = zeros(1, length(data.time));
numsample = zeros(1, length(data.time));
for i=1:length(data.time)
begtime(i) = data.time{i}(1);
endtime(i) = data.time{i}(end);
numsample(i) = length(data.time{i});
end
% compute the differences over trials and the tolerance
tolerance = 0.01*(1/fsample);
begdifference = abs(begtime-begtime(1));
enddifference = abs(endtime-endtime(1));
% check whether begin and/or end are identical, or close to identical
begidentical = all(begdifference==0);
endidentical = all(enddifference==0);
begsimilar = all(begdifference < tolerance);
endsimilar = all(enddifference < tolerance);
% Compute the offset of each trial relative to the first trial, and express
% that in samples. Non-integer numbers indicate that there is a slight skew
% in the time over trials. This works in case of variable length trials.
offset = fsample * (begtime-begtime(1));
skew = abs(offset - round(offset));
% try to determine all cases where a correction is needed
% note that this does not yet address all possible cases where a fix might be needed
needfix = false;
needfix = needfix || ~begidentical && begsimilar;
needfix = needfix || ~endidentical && endsimilar;
needfix = needfix || ~all(skew==0) && all(skew<0.01);
% if the skew is less than 1% it will be corrected
if needfix
ft_warning('correcting numerical inaccuracy in the time axes');
for i=1:length(data.time)
% reconstruct the time axis of each trial, using the begin latency of
% the first trial and the integer offset in samples of each trial
data.time{i} = begtime(1) + ((1:numsample(i)) - 1 + round(offset(i)))/fsample;
end
end
|
github
|
lcnhappe/happe-master
|
getdimsiz.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/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
|
lcnhappe/happe-master
|
read_yokogawa_header.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_yokogawa_header.m
| 8,273 |
utf_8
|
ce0d6dbecc09597da7bbb311519c6c84
|
function hdr = read_yokogawa_header(filename)
% READ_YOKOGAWA_HEADER reads the header information from continuous,
% epoched or averaged MEG data that has been generated by the Yokogawa
% MEG system and software and allows that data to be used in combination
% with FieldTrip.
%
% Use as
% [hdr] = read_yokogawa_header(filename)
%
% This is a wrapper function around the functions
% GetMeg160SystemInfoM
% GetMeg160ChannelCountM
% GetMeg160ChannelInfoM
% GetMeg160CalibInfoM
% GetMeg160AmpGainM
% GetMeg160DataAcqTypeM
% GetMeg160ContinuousAcqCondM
% GetMeg160EvokedAcqCondM
%
% See also READ_YOKOGAWA_DATA, READ_YOKOGAWA_EVENT
% this function also calls
% GetMeg160MriInfoM
% GetMeg160MatchingInfoM
% GetMeg160SourceInfoM
% but I don't know whether to use the information provided by those
% Copyright (C) 2005, Robert Oostenveld
%
% This file is part of FieldTrip, see http://www.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$
% FIXED
% txt -> m
% fopen iee-le
if ~ft_hastoolbox('yokogawa')
error('cannot determine whether Yokogawa toolbox is present');
end
handles = definehandles;
fid = fopen(filename, 'rb', 'ieee-le');
% these are always present
[id ver rev sys_name] = GetMeg160SystemInfoM(fid);
channel_count = GetMeg160ChannelCountM(fid);
channel_info = GetMeg160ChannelInfoM(fid);
calib_info = GetMeg160CalibInfoM(fid);
amp_gain = GetMeg160AmpGainM(fid);
acq_type = GetMeg160DataAcqTypeM(fid);
ad_bit = GetMeg160ADbitInfoM(fid);
% these depend on the data type
sample_rate = [];
sample_count = [];
pretrigger_length = [];
averaged_count = [];
actual_epoch_count = [];
switch acq_type
case handles.AcqTypeContinuousRaw
[sample_rate, sample_count] = GetMeg160ContinuousAcqCondM(fid);
if isempty(sample_rate) | isempty(sample_count)
fclose(fid);
return;
end
pretrigger_length = 0;
averaged_count = 1;
case handles.AcqTypeEvokedAve
[sample_rate, sample_count, pretrigger_length, averaged_count] = GetMeg160EvokedAcqCondM( fid );
if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(averaged_count)
fclose(fid);
return;
end
case handles.AcqTypeEvokedRaw
[sample_rate, sample_count, pretrigger_length, actual_epoch_count] = GetMeg160EvokedAcqCondM( fid );
if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(actual_epoch_count)
fclose(fid);
return;
end
otherwise
error('unknown data type');
end
% these are always present
mri_info = GetMeg160MriInfoM(fid);
matching_info = GetMeg160MatchingInfoM(fid);
source_info = GetMeg160SourceInfoM(fid);
fclose(fid);
% put all local variables into a structure, this is a bit unusual matlab programming style
tmp = whos;
orig = [];
for i=1:length(tmp)
if isempty(strmatch(tmp(i).name, {'tmp', 'fid', 'ans', 'handles'}))
orig = setfield(orig, tmp(i).name, eval(tmp(i).name));
end
end
% convert the original header information into something that FieldTrip understands
hdr = [];
hdr.orig = orig; % also store the original full header information
hdr.Fs = orig.sample_rate; % sampling frequency
hdr.nChans = orig.channel_count; % number of channels
hdr.nSamples = []; % number of samples per trial
hdr.nSamplesPre = []; % number of pre-trigger samples in each trial
hdr.nTrials = []; % number of trials
switch orig.acq_type
case handles.AcqTypeEvokedAve
hdr.nSamples = orig.sample_count;
hdr.nSamplesPre = orig.pretrigger_length;
hdr.nTrials = 1; % only the average, which can be considered as a single trial
case handles.AcqTypeContinuousRaw
hdr.nSamples = orig.sample_count;
hdr.nSamplesPre = 0; % there is no fixed relation between triggers and data
hdr.nTrials = 1; % the continuous data can be considered as a single very long trial
case handles.AcqTypeEvokedRaw
hdr.nSamples = orig.sample_count;
hdr.nSamplesPre = orig.pretrigger_length;
hdr.nTrials = orig.actual_epoch_count;
otherwise
error('unknown acquisition type');
end
% construct a cell-array with labels of each channel
for i=1:hdr.nChans
% this should be consistent with the predefined list in ft_senslabel,
% with yokogawa2grad and with ft_channelselection
if hdr.orig.channel_info(i, 2) == handles.NullChannel
prefix = '';
elseif hdr.orig.channel_info(i, 2) == handles.MagnetoMeter
prefix = 'M';
elseif hdr.orig.channel_info(i, 2) == handles.AxialGradioMeter
prefix = 'AG';
elseif hdr.orig.channel_info(i, 2) == handles.PlannerGradioMeter
prefix = 'PG';
elseif hdr.orig.channel_info(i, 2) == handles.RefferenceMagnetoMeter
prefix = 'RM';
elseif hdr.orig.channel_info(i, 2) == handles.RefferenceAxialGradioMeter
prefix = 'RAG';
elseif hdr.orig.channel_info(i, 2) == handles.RefferencePlannerGradioMeter
prefix = 'RPG';
elseif hdr.orig.channel_info(i, 2) == handles.TriggerChannel
prefix = 'TRIG';
elseif hdr.orig.channel_info(i, 2) == handles.EegChannel
prefix = 'EEG';
elseif hdr.orig.channel_info(i, 2) == handles.EcgChannel
prefix = 'ECG';
elseif hdr.orig.channel_info(i, 2) == handles.EtcChannel
prefix = 'ETC';
end
hdr.label{i} = sprintf('%s%03d', prefix, i);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this defines some usefull constants
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function handles = definehandles
handles.output = [];
handles.sqd_load_flag = false;
handles.mri_load_flag = false;
handles.NullChannel = 0;
handles.MagnetoMeter = 1;
handles.AxialGradioMeter = 2;
handles.PlannerGradioMeter = 3;
handles.RefferenceChannelMark = hex2dec('0100');
handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter );
handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter );
handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter );
handles.TriggerChannel = -1;
handles.EegChannel = -2;
handles.EcgChannel = -3;
handles.EtcChannel = -4;
handles.NonMegChannelNameLength = 32;
handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length
handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter
handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length
handles.AcqTypeContinuousRaw = 1;
handles.AcqTypeEvokedAve = 2;
handles.AcqTypeEvokedRaw = 3;
handles.sqd = [];
handles.sqd.selected_start = [];
handles.sqd.selected_end = [];
handles.sqd.axialgradiometer_ch_no = [];
handles.sqd.axialgradiometer_ch_info = [];
handles.sqd.axialgradiometer_data = [];
handles.sqd.plannergradiometer_ch_no = [];
handles.sqd.plannergradiometer_ch_info = [];
handles.sqd.plannergradiometer_data = [];
handles.sqd.eegchannel_ch_no = [];
handles.sqd.eegchannel_data = [];
handles.sqd.nullchannel_ch_no = [];
handles.sqd.nullchannel_data = [];
handles.sqd.selected_time = [];
handles.sqd.sample_rate = [];
handles.sqd.sample_count = [];
handles.sqd.pretrigger_length = [];
handles.sqd.matching_info = [];
handles.sqd.source_info = [];
handles.sqd.mri_info = [];
handles.mri = [];
|
github
|
lcnhappe/happe-master
|
encode_nifti1.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/encode_nifti1.m
| 4,870 |
utf_8
|
9cf92a03587c511a5cec2c8c76a3c2c3
|
function blob = encode_nifti1(H)
%function blob = encode_nifti1(H)
%
% Encodes a NIFTI-1 header (=> raw 348 bytes (uint8)) from a Matlab structure
% that matches the C struct defined in nifti1.h.
%
% WARNING: This function currently ignores endianness !!!
% (C) 2010 S.Klanke
blob = uint8(zeros(1,348));
if ~isstruct(H)
error 'Input must be a structure';
end
% see nift1.h for information on structure
sizeof_hdr = int32(348);
blob(1:4) = typecast(sizeof_hdr, 'uint8');
blob = setString(blob, 5, 14, H, 'data_type');
blob = setString(blob, 15, 32, H, 'db_name');
blob = setInt32( blob, 33, 36, H, 'extents');
blob = setInt16( blob, 37, 38, H, 'session_error');
blob = setInt8( blob, 39, 39, H, 'regular');
blob = setInt8( blob, 40, 40, H, 'dim_info');
dim = int16(H.dim(:)');
ndim = numel(dim);
if ndim<1 || ndim>7
error 'Field "dim" must have 1..7 elements';
end
dim = [int16(ndim) dim];
blob(41:(42+2*ndim)) = typecast(dim,'uint8');
blob = setSingle(blob, 57, 60, H, 'intent_p1');
blob = setSingle(blob, 61, 64, H, 'intent_p2');
blob = setSingle(blob, 65, 68, H, 'intent_p3');
blob = setInt16( blob, 69, 70, H, 'intent_code');
blob = setInt16( blob, 71, 72, H, 'datatype');
blob = setInt16( blob, 73, 74, H, 'bitpix');
blob = setInt16( blob, 75, 76, H, 'slice_start');
blob = setSingle(blob, 77, 80, H, 'qfac');
if isfield(H,'pixdim')
pixdim = single(H.pixdim(:)');
ndim = numel(pixdim);
if ndim<1 || ndim>7
error 'Field "pixdim" must have 1..7 elements';
end
blob(81:(80+4*ndim)) = typecast(pixdim,'uint8');
end
blob = setSingle(blob, 109, 112, H, 'vox_offset');
blob = setSingle(blob, 113, 116, H, 'scl_scope');
blob = setSingle(blob, 117, 120, H, 'scl_inter');
blob = setInt16( blob, 121, 122, H, 'slice_end');
blob = setInt8( blob, 123, 123, H, 'slice_code');
blob = setInt8( blob, 124, 124, H, 'xyzt_units');
blob = setSingle(blob, 125, 128, H, 'cal_max');
blob = setSingle(blob, 129, 132, H, 'cal_min');
blob = setSingle(blob, 133, 136, H, 'slice_duration');
blob = setSingle(blob, 137, 140, H, 'toffset');
blob = setInt32( blob, 141, 144, H, 'glmax');
blob = setInt32( blob, 145, 148, H, 'glmin');
blob = setString(blob, 149, 228, H, 'descrip');
blob = setString(blob, 229, 252, H, 'aux_file');
blob = setInt16( blob, 253, 254, H, 'qform_code');
blob = setInt16( blob, 255, 256, H, 'sform_code');
blob = setSingle(blob, 257, 260, H, 'quatern_b');
blob = setSingle(blob, 261, 264, H, 'quatern_c');
blob = setSingle(blob, 265, 268, H, 'quatern_d');
blob = setSingle(blob, 269, 272, H, 'quatern_x');
blob = setSingle(blob, 273, 276, H, 'quatern_y');
blob = setSingle(blob, 277, 280, H, 'quatern_z');
blob = setSingle(blob, 281, 296, H, 'srow_x');
blob = setSingle(blob, 297, 312, H, 'srow_y');
blob = setSingle(blob, 313, 328, H, 'srow_z');
blob = setString(blob, 329, 344, H, 'intent_name');
if ~isfield(H,'magic')
blob(345:347) = uint8('ni1');
else
blob = setString(blob, 345, 347, H, 'magic');
end
function blob = setString(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = getfield(H, fieldname);
ne = numel(F);
mx = endidx - begidx +1;
if ne > 0
if ~ischar(F) || ne > mx
errmsg = sprintf('Field "data_type" must be a string of maximally %i characters.', mx);
error(errmsg);
end
blob(begidx:(begidx+ne-1)) = uint8(F(:)');
end
% set 32-bit integers (check #elements)
function blob = setInt32(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = int32(getfield(H, fieldname));
ne = numel(F);
sp = (endidx - begidx +1) / 4;
if ne~=sp
errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp);
error(errmsg);
end
blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8');
% set 16-bit integers (check #elements)
function blob = setInt16(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = int16(getfield(H, fieldname));
ne = numel(F);
sp = (endidx - begidx +1) / 2;
if ne~=sp
errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp);
error(errmsg);
end
blob(begidx:(begidx+2*ne-1)) = typecast(F(:)', 'uint8');
% just 8-bit integers (check #elements)
function blob = setInt8(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = int8(getfield(H, fieldname));
ne = numel(F);
sp = (endidx - begidx +1);
if ne~=sp
errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp);
error(errmsg);
end
blob(begidx:(begidx+ne-1)) = typecast(F(:)', 'uint8');
% single precision floats
function blob = setSingle(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = single(getfield(H, fieldname));
ne = numel(F);
sp = (endidx - begidx +1) / 4;
if ne~=sp
errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp);
error(errmsg);
end
blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8');
|
github
|
lcnhappe/happe-master
|
read_nervus_header.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_nervus_header.m
| 30,014 |
utf_8
|
a7e8259eae22c5af14fb48467f95f2b7
|
function output = read_nervus_header(filename)
% read_nervus_header Returns header information from Nicolet file.
%
% FILENAME is the file name of a file in the Natus/Nicolet/Nervus(TM)
% format (originally designed by Taugagreining HF in Iceland)
%
% Based on ieeg-portal/Nicolet-Reader
% at https://github.com/ieeg-portal/Nicolet-Reader
%
% Copyright (C) 2016, Jan Brogger and Joost Wagenaar
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
% FieldTrip is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% FieldTrip is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: $
%--Constants--
LABELSIZE = 32;
TSLABELSIZE = 64;
UNITSIZE = 16;
ITEMNAMESIZE = 64;
% ---------------- Opening File------------------
h = fopen(filename,'rb','ieee-le');
if h==-1
error('Can''t open Nervus EEG file')
end
nrvHdr = struct();
nrvHdr.filename = filename;
nrvHdr.misc1 = fread(h,5, 'uint32');
nrvHdr.unknown = fread(h,1,'uint32');
nrvHdr.indexIdx = fread(h,1,'uint32');
[nrvHdr.NrStaticPackets, nrvHdr.StaticPackets] = read_nervus_header_staticpackets(h);
nrvHdr.QIIndex = read_nervus_header_Qi(h, nrvHdr.NrStaticPackets);
nrvHdr.QIIndex2 = read_nervus_header_Qi2(h, nrvHdr.QIIndex);
nrvHdr.MainIndex = read_nervus_header_main(h, nrvHdr.indexIdx, nrvHdr.QIIndex.nrEntries);
nrvHdr.allIndexIDs = [nrvHdr.MainIndex.sectionIdx];
nrvHdr.infoGuids = read_nervus_header_infoGuids(h, nrvHdr.StaticPackets, nrvHdr.MainIndex);
nrvHdr.DynamicPackets = read_nervus_header_dynamicpackets(h, nrvHdr.StaticPackets, nrvHdr.MainIndex);
nrvHdr.PatientInfo = read_nervus_header_patient(h, nrvHdr.StaticPackets, nrvHdr.MainIndex);
nrvHdr.SigInfo = read_nervus_header_SignalInfo(h, nrvHdr.StaticPackets, nrvHdr.MainIndex, ITEMNAMESIZE, LABELSIZE, UNITSIZE);
nrvHdr.ChannelInfo = read_nervus_header_ChannelInfo(h, nrvHdr.StaticPackets, nrvHdr.MainIndex, ITEMNAMESIZE, LABELSIZE);
nrvHdr.TSInfo = read_nervus_header_TSInfo(h, nrvHdr.DynamicPackets, nrvHdr.MainIndex, ITEMNAMESIZE, TSLABELSIZE, LABELSIZE);
nrvHdr.Segments = read_nervus_header_Segments(h, nrvHdr.StaticPackets, nrvHdr.MainIndex, nrvHdr.TSInfo);
nrvHdr.Events = read_nervus_header_events(h, nrvHdr.StaticPackets, nrvHdr.MainIndex);
nrvHdr.MontageInfo = read_nervus_header_montage(h, nrvHdr.StaticPackets, nrvHdr.MainIndex);
reference = unique(nrvHdr.Segments(1).refName(cellfun(@length, [nrvHdr.Segments(1).refName])>0));
if strcmp(reference, 'REF')
nrvHdr.reference = 'common';
else
nrvHdr.reference = 'unknown';
end
fclose(h);
%Calculate sample count across segments
% - some channels have lower sampling rates, so we for each segments we
% choose the channel with the highest sampling rate
totalNSamples = 0;
for i=1:size(nrvHdr.Segments,2)
totalNSamples = totalNSamples + max(nrvHdr.Segments(i).samplingRate*nrvHdr.Segments(i).duration);
end
output = struct();
output.Fs = max([nrvHdr.Segments.samplingRate]);
output.nChans = size([nrvHdr.Segments(1).chName],2);
output.label = nrvHdr.Segments(1).chName;
output.nSamples = totalNSamples;
output.nSamplesPre = 0;
output.nTrials = 1; %size(nrvHdr.Segments,2);
output.reference = nrvHdr.reference;
output.filename = nrvHdr.filename;
output.orig = nrvHdr;
end
function [NrStaticPackets, StaticPackets] = read_nervus_header_staticpackets(h)
% Get StaticPackets structure and Channel IDS
fseek(h, 172,'bof');
NrStaticPackets = fread(h,1, 'uint32');
StaticPackets = struct();
for i = 1:NrStaticPackets
StaticPackets(i).tag = deblank(cast(fread(h, 40, 'uint16'),'char')');
StaticPackets(i).index = fread(h,1,'uint32');
switch StaticPackets(i).tag
case 'ExtraDataStaticPackets'
StaticPackets(i).IDStr = 'ExtraDataStaticPackets';
case 'SegmentStream'
StaticPackets(i).IDStr = 'SegmentStream';
case 'DataStream'
StaticPackets(i).IDStr = 'DataStream';
case 'InfoChangeStream'
StaticPackets(i).IDStr = 'InfoChangeStream';
case 'InfoGuids'
StaticPackets(i).IDStr = 'InfoGuids';
case '{A271CCCB-515D-4590-B6A1-DC170C8D6EE2}'
StaticPackets(i).IDStr = 'TSGUID';
case '{8A19AA48-BEA0-40D5-B89F-667FC578D635}'
StaticPackets(i).IDStr = 'DERIVATIONGUID';
case '{F824D60C-995E-4D94-9578-893C755ECB99}'
StaticPackets(i).IDStr = 'FILTERGUID';
case '{02950361-35BB-4A22-9F0B-C78AAA5DB094}'
StaticPackets(i).IDStr = 'DISPLAYGUID';
case '{8E9421-70F5-11D3-8F72-00105A9AFD56}'
StaticPackets(i).IDStr = 'FILEINFOGUID';
case '{E4138BC0-7733-11D3-8685-0050044DAAB1}'
StaticPackets(i).IDStr = 'SRINFOGUID';
case '{C728E565-E5A0-4419-93D2-F6CFC69F3B8F}'
StaticPackets(i).IDStr = 'EVENTTYPEINFOGUID';
case '{D01B34A0-9DBD-11D3-93D3-00500400C148}'
StaticPackets(i).IDStr = 'AUDIOINFOGUID';
case '{BF7C95EF-6C3B-4E70-9E11-779BFFF58EA7}'
StaticPackets(i).IDStr = 'CHANNELGUID';
case '{2DEB82A1-D15F-4770-A4A4-CF03815F52DE}'
StaticPackets(i).IDStr = 'INPUTGUID';
case '{5B036022-2EDC-465F-86EC-C0A4AB1A7A91}'
StaticPackets(i).IDStr = 'INPUTSETTINGSGUID';
case '{99A636F2-51F7-4B9D-9569-C7D45058431A}'
StaticPackets(i).IDStr = 'PHOTICGUID';
case '{55C5E044-5541-4594-9E35-5B3004EF7647}'
StaticPackets(i).IDStr = 'ERRORGUID';
case '{223A3CA0-B5AC-43FB-B0A8-74CF8752BDBE}'
StaticPackets(i).IDStr = 'VIDEOGUID';
case '{0623B545-38BE-4939-B9D0-55F5E241278D}'
StaticPackets(i).IDStr = 'DETECTIONPARAMSGUID';
case '{CE06297D-D9D6-4E4B-8EAC-305EA1243EAB}'
StaticPackets(i).IDStr = 'PAGEGUID';
case '{782B34E8-8E51-4BB9-9701-3227BB882A23}'
StaticPackets(i).IDStr = 'ACCINFOGUID';
case '{3A6E8546-D144-4B55-A2C7-40DF579ED11E}'
StaticPackets(i).IDStr = 'RECCTRLGUID';
case '{D046F2B0-5130-41B1-ABD7-38C12B32FAC3}'
StaticPackets(i).IDStr = 'GUID TRENDINFOGUID';
case '{CBEBA8E6-1CDA-4509-B6C2-6AC2EA7DB8F8}'
StaticPackets(i).IDStr = 'HWINFOGUID';
case '{E11C4CBA-0753-4655-A1E9-2B2309D1545B}'
StaticPackets(i).IDStr = 'VIDEOSYNCGUID';
case '{B9344241-7AC1-42B5-BE9B-B7AFA16CBFA5}'
StaticPackets(i).IDStr = 'SLEEPSCOREINFOGUID';
case '{15B41C32-0294-440E-ADFF-DD8B61C8B5AE}'
StaticPackets(i).IDStr = 'FOURIERSETTINGSGUID';
case '{024FA81F-6A83-43C8-8C82-241A5501F0A1}'
StaticPackets(i).IDStr = 'SPECTRUMGUID';
case '{8032E68A-EA3E-42E8-893E-6E93C59ED515}'
StaticPackets(i).IDStr = 'SIGNALINFOGUID';
case '{30950D98-C39C-4352-AF3E-CB17D5B93DED}'
StaticPackets(i).IDStr = 'SENSORINFOGUID';
case '{F5D39CD3-A340-4172-A1A3-78B2CDBCCB9F}'
StaticPackets(i).IDStr = 'DERIVEDSIGNALINFOGUID';
case '{969FBB89-EE8E-4501-AD40-FB5A448BC4F9}'
StaticPackets(i).IDStr = 'ARTIFACTINFOGUID';
case '{02948284-17EC-4538-A7FA-8E18BD65E167}'
StaticPackets(i).IDStr = 'STUDYINFOGUID';
case '{D0B3FD0B-49D9-4BF0-8929-296DE5A55910}'
StaticPackets(i).IDStr = 'PATIENTINFOGUID';
case '{7842FEF5-A686-459D-8196-769FC0AD99B3}'
StaticPackets(i).IDStr = 'DOCUMENTINFOGUID';
case '{BCDAEE87-2496-4DF4-B07C-8B4E31E3C495}'
StaticPackets(i).IDStr = 'USERSINFOGUID';
case '{B799F680-72A4-11D3-93D3-00500400C148}'
StaticPackets(i).IDStr = 'EVENTGUID';
case '{AF2B3281-7FCE-11D2-B2DE-00104B6FC652}'
StaticPackets(i).IDStr = 'SHORTSAMPLESGUID';
case '{89A091B3-972E-4DA2-9266-261B186302A9}'
StaticPackets(i).IDStr = 'DELAYLINESAMPLESGUID';
case '{291E2381-B3B4-44D1-BB77-8CF5C24420D7}'
StaticPackets(i).IDStr = 'GENERALSAMPLESGUID';
case '{5F11C628-FCCC-4FDD-B429-5EC94CB3AFEB}'
StaticPackets(i).IDStr = 'FILTERSAMPLESGUID';
case '{728087F8-73E1-44D1-8882-C770976478A2}'
StaticPackets(i).IDStr = 'DATEXDATAGUID';
case '{35F356D9-0F1C-4DFE-8286-D3DB3346FD75}'
StaticPackets(i).IDStr = 'TESTINFOGUID';
otherwise
if isstrprop(StaticPackets(i).tag, 'digit')
StaticPackets(i).IDStr = num2str(StaticPackets(i).tag);
else
StaticPackets(i).IDStr = 'UNKNOWN';
end
end
end
end
function QIIndex = read_nervus_header_Qi(h, nrStaticPackets)
%% QI index
fseek(h, 172208,'bof');
QIIndex =struct();
QIIndex.nrEntries = fread(h,1,'uint32');
QIIndex.misc1 = fread(h,1,'uint32');
QIIndex.indexIdx = fread(h,1,'uint32');
QIIndex.misc3 = fread(h,1,'uint32');
QIIndex.LQi = fread(h,1,'uint64')';
QIIndex.firstIdx = fread(h,nrStaticPackets,'uint64');
end
function QIIndex2 = read_nervus_header_Qi2(h, QIIndex)
fseek(h, 188664,'bof');
QIIndex2 = struct();
for i = 1:QIIndex.LQi
QIIndex2(i).ftel = ftell(h);
QIIndex2(i).index = fread(h,2,'uint16')'; %4
QIIndex2(i).misc1 = fread(h,1,'uint32'); %8
QIIndex2(i).indexIdx = fread(h,1,'uint32'); %12
QIIndex2(i).misc2 = fread(h,3,'uint32')'; %24
QIIndex2(i).sectionIdx = fread(h,1,'uint32');%28
QIIndex2(i).misc3 = fread(h,1,'uint32'); %32
QIIndex2(i).offset = fread(h,1,'uint64'); % 40
QIIndex2(i).blockL = fread(h,1,'uint32');%44
QIIndex2(i).dataL = fread(h,1,'uint32')';%48
end
end
function MainIndex = read_nervus_header_main(h, indexIdx, nrEntries)
%% Get Main Index:
% Index consists of multiple blocks, after each block is the pointer
% to the next block. Total number of entries is in obj.Qi.nrEntries
MainIndex = struct();
curIdx = 0;
nextIndexPointer = indexIdx;
curIdx2 = 1;
while curIdx < nrEntries
fseek(h, nextIndexPointer, 'bof');
nrIdx = fread(h,1, 'uint64');
MainIndex(curIdx + nrIdx).sectionIdx = 0; % Preallocate next set of indices
var = fread(h,3*nrIdx, 'uint64');
for i = 1: nrIdx
MainIndex(curIdx + i).sectionIdx = var(3*(i-1)+1);
MainIndex(curIdx + i).offset = var(3*(i-1)+2);
MainIndex(curIdx + i).blockL = mod(var(3*(i-1)+3),2^32);
MainIndex(curIdx + i).sectionL = round(var(3*(i-1)+3)/2^32);
end
nextIndexPointer = fread(h,1, 'uint64');
curIdx = curIdx + i;
curIdx2=curIdx2+1;
end
end
function infoGuids = read_nervus_header_infoGuids(h, StaticPackets, MainIndex)
infoIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'InfoGuids'),1)).index;
indexInstance = MainIndex(find([MainIndex.sectionIdx]==infoIdx,1));
nrInfoGuids = indexInstance.sectionL/16;
infoGuids = struct();
fseek(h, indexInstance.offset,'bof');
for i = 1:nrInfoGuids
guidmixed = fread(h,16, 'uint8')';
guidnonmixed = [guidmixed(04), guidmixed(03), guidmixed(02), guidmixed(01), ...
guidmixed(06), guidmixed(05), guidmixed(08), guidmixed(07), ...
guidmixed(09), guidmixed(10), guidmixed(11), guidmixed(12), ...
guidmixed(13), guidmixed(15), guidmixed(15), guidmixed(16)];
infoGuids(i).guid = num2str(guidnonmixed,'%02X');
end
end
function dynamicPackets = read_nervus_header_dynamicpackets(h, StaticPackets, MainIndex)
dynamicPackets = struct();
indexIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'InfoChangeStream'),1)).index;
offset = MainIndex(indexIdx).offset;
nrDynamicPackets = MainIndex(indexIdx).sectionL / 48;
fseek(h, offset, 'bof');
%Read first only the dynamic packets structure without actual data
for i = 1: nrDynamicPackets
dynamicPackets(i).offset = offset+i*48;
guidmixed = fread(h,16, 'uint8')';
guidnonmixed = [guidmixed(04), guidmixed(03), guidmixed(02), guidmixed(01), ...
guidmixed(06), guidmixed(05), guidmixed(08), guidmixed(07), ...
guidmixed(09), guidmixed(10), guidmixed(11), guidmixed(12), ...
guidmixed(13), guidmixed(14), guidmixed(15), guidmixed(16)];
dynamicPackets(i).guid = num2str(guidnonmixed, '%02X');
dynamicPackets(i).guidAsStr = sprintf('{%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X}', guidnonmixed);
dynamicPackets(i).date = datenum(1899,12,31) + fread(h,1,'double');
dynamicPackets(i).datefrac = fread(h,1,'double');
dynamicPackets(i).internalOffsetStart = fread(h,1, 'uint64')';
dynamicPackets(i).packetSize = fread(h,1, 'uint64')';
dynamicPackets(i).data = zeros(0, 1,'uint8');
switch dynamicPackets(i).guid
case 'BF7C95EF6C3B4E709E11779BFFF58EA7'
dynamicPackets(i).IDStr = 'CHANNELGUID';
case '8A19AA48BEA040D5B89F667FC578D635'
dynamicPackets(i).IDStr = 'DERIVATIONGUID';
case 'F824D60C995E4D949578893C755ECB99'
dynamicPackets(i).IDStr = 'FILTERGUID';
case '0295036135BB4A229F0BC78AAA5DB094'
dynamicPackets(i).IDStr = 'DISPLAYGUID';
case '782B34E88E514BB997013227BB882A23'
dynamicPackets(i).IDStr = 'ACCINFOGUID';
case 'A271CCCB515D4590B6A1DC170C8D6EE2'
dynamicPackets(i).IDStr = 'TSGUID';
case 'D01B34A09DBD11D393D300500400C148'
dynamicPackets(i).IDStr = 'AUDIOINFOGUID';
otherwise
dynamicPackets(i).IDStr = 'UNKNOWN';
end
end
%Then read the actual data from the pointers above
for i = 1: nrDynamicPackets
%Look up the GUID of this dynamic packet in the static packets
% to find the section index
infoIdx = StaticPackets(find(strcmp({StaticPackets.tag},dynamicPackets(i).guidAsStr),1)).index;
%Matching index segments
indexInstances = MainIndex([MainIndex.sectionIdx] == infoIdx);
%Then, treat all these sections as one contiguous memory block
% and grab this packet across these instances
internalOffset = 0;
remainingDataToRead = dynamicPackets(i).packetSize;
%disp(['Target packet ' dynamicPackets(i).IDStr ' : ' num2str(dynamicPackets(i).internalOffsetStart) ' to ' num2str(dynamicPackets(i).internalOffsetStart+dynamicPackets(i).packetSize) ' target read length ' num2str(remainingDataToRead)]);
currentTargetStart = dynamicPackets(i).internalOffsetStart;
for j = 1: size(indexInstances,2)
currentInstance = indexInstances(j);
%hitInThisSegment = '';
if (internalOffset <= currentTargetStart) && (internalOffset+currentInstance.sectionL) >= currentTargetStart
startAt = currentTargetStart;
stopAt = min(startAt+remainingDataToRead, internalOffset+currentInstance.sectionL);
readLength = stopAt-startAt;
filePosStart = currentInstance.offset+startAt-internalOffset;
fseek(h,filePosStart, 'bof');
dataPart = fread(h,readLength,'uint8=>uint8');
dynamicPackets(i).data = cat(1, dynamicPackets(i).data, dataPart);
%hitInThisSegment = ['HIT at ' num2str(startAt) ' to ' num2str(stopAt)];
%if (readLength < remainingDataToRead)
% hitInThisSegment = [hitInThisSegment ' (partial ' num2str(readLength) ' )'];
%else
% hitInThisSegment = [hitInThisSegment ' (finished - this segment contributed ' num2str(readLength) ' )'];
%end
%hitInThisSegment = [hitInThisSegment ' abs file pos ' num2str(filePosStart) ' - ' num2str(filePosStart+readLength)];
remainingDataToRead = remainingDataToRead-readLength;
currentTargetStart = currentTargetStart + readLength;
end
%disp([' Index ' num2str(j) ' Offset: ' num2str(internalOffset) ' to ' num2str(internalOffset+currentInstance.sectionL) ' ' num2str(hitInThisSegment)]);
internalOffset = internalOffset + currentInstance.sectionL;
end
end
end
function PatientInfo = read_nervus_header_patient(h, StaticPackets, Index)
%% Get PatientGUID
PatientInfo = struct();
infoProps = { 'patientID', 'firstName','middleName','lastName',...
'altID','mothersMaidenName','DOB','DOD','street','sexID','phone',...
'notes','dominance','siteID','suffix','prefix','degree','apartment',...
'city','state','country','language','height','weight','race','religion',...
'maritalStatus'};
infoIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'PATIENTINFOGUID'),1)).index;
indexInstance = Index(find([Index.sectionIdx]==infoIdx,1));
fseek(h, indexInstance.offset,'bof');
guid = fread(h, 16, 'uint8');
lSection = fread(h, 1, 'uint64');
% reserved = fread(h, 3, 'uint16');
nrValues = fread(h,1,'uint64');
nrBstr = fread(h,1,'uint64');
for i = 1:nrValues
id = fread(h,1,'uint64');
switch id
case {7,8}
unix_time = (fread(h,1, 'double')*(3600*24)) - 2209161600;% 2208988800; %8
obj.segments(i).dateStr = datestr(unix_time/86400 + datenum(1970,1,1));
value = datevec( obj.segments(i).dateStr );
value = value([3 2 1]);
case {23,24}
value = fread(h,1,'double');
otherwise
value = 0;
end
PatientInfo.(infoProps{id}) = value;
end
strSetup = fread(h,nrBstr*2,'uint64');
for i=1:2:(nrBstr*2)
id = strSetup(i);
value = deblank(cast(fread(h, strSetup(i+1) + 1, 'uint16'),'char')');
info.(infoProps{id}) = value;
end
end
function sigInfo = read_nervus_header_SignalInfo(h, StaticPackets, Index, ITEMNAMESIZE, LABELSIZE, UNITSIZE)
infoIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'InfoGuids'),1)).index;
indexInstance = Index(find([Index.sectionIdx]==infoIdx,1));
fseek(h, indexInstance.offset,'bof');
sigInfo = struct();
SIG_struct = struct();
sensorIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'SIGNALINFOGUID'),1)).index;
indexInstance = Index(find([Index.sectionIdx]==sensorIdx,1));
fseek(h, indexInstance.offset,'bof');
SIG_struct.guid = fread(h, 16, 'uint8');
SIG_struct.name = fread(h, ITEMNAMESIZE, '*char');
unkown = fread(h, 152, '*char'); %#ok<NASGU>
fseek(h, 512, 'cof');
nrIdx = fread(h,1, 'uint16'); %783
misc1 = fread(h,3, 'uint16'); %#ok<NASGU>
for i = 1: nrIdx
sigInfo(i).sensorName = deblank(cast(fread(h, LABELSIZE, 'uint16'),'char')');
sigInfo(i).transducer = deblank(cast(fread(h, UNITSIZE, 'uint16'),'char')');
sigInfo(i).guid = fread(h, 16, '*uint8');
sigInfo(i).bBiPolar = logical(fread(h, 1 ,'uint32'));
sigInfo(i).bAC = logical(fread(h, 1 ,'uint32'));
sigInfo(i).bHighFilter = logical(fread(h, 1 ,'uint32'));
sigInfo(i).color = fread(h, 1 ,'uint32');
reserved = fread(h, 256, '*char'); %#ok<NASGU>
end
end
function channelInfo = read_nervus_header_ChannelInfo(h, StaticPackets, Index, ITEMNAMESIZE, LABELSIZE)
%% Get CHANNELINFO (CHANNELGUID)
CH_struct = struct();
sensorIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'CHANNELGUID'),1)).index;
indexInstance = Index(find([Index.sectionIdx]==sensorIdx,1));
fseek(h, indexInstance.offset,'bof');
CH_struct.guid = fread(h, 16, 'uint8');
CH_struct.name = fread(h, ITEMNAMESIZE, '*char');
fseek(h, 152, 'cof');
CH_struct.reserved = fread(h, 16, 'uint8');
CH_struct.deviceID = fread(h, 16, 'uint8');
fseek(h, 488, 'cof');
nrIdx = fread(h,2, 'uint32'); %783
channelInfo = struct();
for i = 1: nrIdx(2)
channelInfo(i).sensor = deblank(cast(fread(h, LABELSIZE, 'uint16'),'char')');
channelInfo(i).samplingRate = fread(h,1,'double');
channelInfo(i).bOn = logical(fread(h, 1 ,'uint32'));
channelInfo(i).lInputID = fread(h, 1 ,'uint32');
channelInfo(i).lInputSettingID = fread(h,1,'uint32');
channelInfo(i).reserved = fread(h,4,'char');
fseek(h, 128, 'cof');
end
curIdx = 0;
for i = 1: length(channelInfo)
if channelInfo(i).bOn
channelInfo(i).indexID = curIdx;
curIdx = curIdx+1;
else
channelInfo(i).indexID = -1;
end
end
end
function [TSInfo] = read_nervus_header_TSInfo(h, DynamicPackets, Index, ITEMNAMESIZE, TSLABELSIZE, LABELSIZE)
tsPackets = DynamicPackets(strcmp({DynamicPackets.IDStr},'TSGUID'));
if length(tsPackets) > 1
warning(['Multiple TSinfo packets detected; using first instance ' ...
' ac for all segments. See documentation for info.']);
elseif isempty(tsPackets)
warning(['No TSINFO found']);
else
tsPacket = tsPackets(1);
TSInfo = struct();
elems = typecast(tsPacket.data(753:756),'uint32');
alloc = typecast(tsPacket.data(757:760),'uint32');
offset = 761;
for i = 1:elems
internalOffset = 0;
TSInfo(i).label = deblank(char(typecast(tsPacket.data(offset:(offset+TSLABELSIZE-1))','uint16')));
internalOffset = internalOffset + TSLABELSIZE*2;
TSInfo(i).activeSensor = deblank(char(typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+LABELSIZE))','uint16')));
internalOffset = internalOffset + TSLABELSIZE;
TSInfo(i).refSensor = deblank(char(typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+8))','uint16')));
internalOffset = internalOffset + 8;
internalOffset = internalOffset + 56;
TSInfo(i).lowcut = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+8))','double');
internalOffset = internalOffset + 8;
TSInfo(i).hiCut = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+8))','double');
internalOffset = internalOffset + 8;
TSInfo(i).samplingRate = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+8))','double');
internalOffset = internalOffset + 8;
TSInfo(i).resolution = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+8))','double');
internalOffset = internalOffset + 8;
TSInfo(i).specialMark = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+2))','uint16');
internalOffset = internalOffset + 2;
TSInfo(i).notch = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+2))','uint16');
internalOffset = internalOffset + 2;
TSInfo(i).eeg_offset = typecast(tsPacket.data(offset+internalOffset:(offset+internalOffset-1+8))','double');
offset = offset + 552;
%disp([num2str(i) ' : ' TSInfo(i).label ' : ' TSInfo(i).activeSensor ' : ' TSInfo(i).refSensor ' : ' num2str(TSInfo(i).samplingRate)]);
end
end
end
function [segments] = read_nervus_header_Segments(h, StaticPackets, Index, TSInfo)
%% Get Segment Start Times
segmentIdx = StaticPackets(find(strcmp({StaticPackets.IDStr}, 'SegmentStream'),1)).index;
indexIdx = find([Index.sectionIdx] == segmentIdx, 1);
segmentInstance = Index(indexIdx);
nrSegments = segmentInstance.sectionL/152;
fseek(h, segmentInstance.offset,'bof');
segments = struct();
for i = 1: nrSegments
dateOLE = fread(h,1, 'double');
segments(i).dateOLE = dateOLE;
unix_time = (dateOLE*(3600*24)) - 2209161600;% 2208988800; %8
segments(i).dateStr = datestr(unix_time/86400 + datenum(1970,1,1));
datev = datevec( segments(i).dateStr );
segments(i).startDate = datev(1:3);
segments(i).startTime = datev(4:6);
fseek(h, 8 , 'cof'); %16
segments(i).duration = fread(h,1, 'double');%24
fseek(h, 128 , 'cof'); %152
end
% Get nrValues per segment and channel
for iSeg = 1:length(segments)
% Add Channel Names to segments
segments(iSeg).chName = {TSInfo.label};
segments(iSeg).refName = {TSInfo.refSensor};
segments(iSeg).samplingRate = [TSInfo.samplingRate];
segments(iSeg).scale = [TSInfo.resolution];
segments(iSeg).sampleCount = max(segments(iSeg).samplingRate*segments(iSeg).duration);
end
end
function [eventMarkers] = read_nervus_header_events(h, StaticPackets, Index)
%% Get events - Andrei Barborica, Dec 2015
% Find sequence of events, that are stored in the section tagged 'Events'
eventsSection = strcmp({StaticPackets.tag}, 'Events');
idxSection = find(eventsSection);
indexIdx = find([Index.sectionIdx] == StaticPackets(idxSection).index);
offset = Index(indexIdx).offset;
ePktLen = 272; % Event packet length, see EVENTPACKET definition
eMrkLen = 240; % Event marker length, see EVENTMARKER definition
evtPktGUID = hex2dec({'80', 'F6', '99', 'B7', 'A4', '72', 'D3', '11', '93', 'D3', '00', '50', '04', '00', 'C1', '48'}); % GUID for event packet header
HCEVENT_ANNOTATION = '{A5A95612-A7F8-11CF-831A-0800091B5BDA}';
HCEVENT_SEIZURE = '{A5A95646-A7F8-11CF-831A-0800091B5BDA}';
HCEVENT_FORMATCHANGE = '{08784382-C765-11D3-90CE-00104B6F4F70}';
HCEVENT_PHOTIC = '{6FF394DA-D1B8-46DA-B78F-866C67CF02AF}';
HCEVENT_POSTHYPERVENT = '{481DFC97-013C-4BC5-A203-871B0375A519}';
HCEVENT_REVIEWPROGRESS = '{725798BF-CD1C-4909-B793-6C7864C27AB7}';
HCEVENT_EXAMSTART = '{96315D79-5C24-4A65-B334-E31A95088D55}';
HCEVENT_HYPERVENTILATION = '{A5A95608-A7F8-11CF-831A-0800091B5BDA}';
HCEVENT_IMPEDANCE = '{A5A95617-A7F8-11CF-831A-0800091B5BDA}';
DAYSECS = 86400.0; % From nrvdate.h
fseek(h,offset,'bof');
pktGUID = fread(h,16,'uint8');
pktLen = fread(h,1,'uint64');
eventMarkers = struct();
i = 0; % Event counter
while (pktGUID == evtPktGUID)
i = i + 1;
% Please refer to EVENTMARKER structure in the Nervus file documentation
fseek(h,8,'cof'); % Skip eventID, not used
evtDate = fread(h,1,'double');
evtDateFraction = fread(h,1,'double');
eventMarkers(i).dateOLE = evtDate;
eventMarkers(i).dateFraction = evtDateFraction;
evtPOSIXTime = evtDate*DAYSECS + evtDateFraction - 2209161600;% 2208988800; %8
eventMarkers(i).dateStr = datestr(evtPOSIXTime/DAYSECS + datenum(1970,1,1),'dd-mmmm-yyyy HH:MM:SS.FFF'); % Save fractions of seconds, as well
eventMarkers(i).duration = fread(h,1,'double');
fseek(h,48,'cof');
evtUser = fread(h,12,'uint16');
eventMarkers(i).user = deblank(char(evtUser).');
evtTextLen = fread(h,1,'uint64');
evtGUID = fread(h,16,'uint8');
eventMarkers(i).GUID = sprintf('{%.2X%.2X%.2X%.2X-%.2X%.2X-%.2X%.2X-%.2X%.2X-%.2X%.2X%.2X%.2X%.2X%.2X}',evtGUID([4 3 2 1 6 5 8 7 9:16]));
fseek(h,16,'cof'); % Skip Reserved4 array
evtLabel = fread(h,32,'uint16'); % LABELSIZE = 32;
evtLabel = deblank(char(evtLabel).'); % Not used
eventMarkers(i).label = evtLabel;
% Only a subset of all event types are dealt with
switch eventMarkers(i).GUID
case HCEVENT_SEIZURE
eventMarkers(i).IDStr = 'Seizure';
%disp(' Seizure event');
case HCEVENT_ANNOTATION
eventMarkers(i).IDStr = 'Annotation';
fseek(h,32,'cof'); % Skip Reserved5 array
evtAnnotation = fread(h,evtTextLen,'uint16');
eventMarkers(i).annotation = deblank(char(evtAnnotation).');
%disp(sprintf(' Annotation:%s',evtAnnotation));
case HCEVENT_FORMATCHANGE
eventMarkers(i).IDStr = 'Format change';
case HCEVENT_PHOTIC
eventMarkers(i).IDStr = 'Photic';
case HCEVENT_POSTHYPERVENT
eventMarkers(i).IDStr = 'Posthyperventilation';
case HCEVENT_REVIEWPROGRESS
eventMarkers(i).IDStr = 'Review progress';
case HCEVENT_EXAMSTART
eventMarkers(i).IDStr = 'Exam start';
case HCEVENT_HYPERVENTILATION
eventMarkers(i).IDStr = 'Hyperventilation';
case HCEVENT_IMPEDANCE
eventMarkers(i).IDStr = 'Impedance';
otherwise
eventMarkers(i).IDStr = 'UNKNOWN';
end
% Next packet
offset = offset + pktLen;
fseek(h,offset,'bof');
pktGUID = fread(h,16,'uint8');
pktLen = fread(h,1,'uint64');
end
end
function [montage] = read_nervus_header_montage(h, StaticPackets, Index)
%% Get montage - Andrei Barborica, Dec 2015
% Derivation (montage)
mtgIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'DERIVATIONGUID'),1)).index;
indexIdx = find([Index.sectionIdx]==mtgIdx,1);
fseek(h,Index(indexIdx(1)).offset + 40,'bof'); % Beginning of current montage name
mtgName = deblank(char(fread(h,32,'uint16')).');
fseek(h,640,'cof'); % Number of traces in the montage
numDerivations = fread(h,1,'uint32');
numDerivations2 = fread(h,1,'uint32');
montage = struct();
for i = 1:numDerivations
montage(i).derivationName = deblank(char(fread(h,64,'uint16')).');
montage(i).signalName1 = deblank(char(fread(h,32,'uint16')).');
montage(i).signalName2 = deblank(char(fread(h,32,'uint16')).');
fseek(h,264,'cof'); % Skip additional info
end
% Display properties
dispIdx = StaticPackets(find(strcmp({StaticPackets.IDStr},'DISPLAYGUID'),1)).index;
indexIdx = find([Index.sectionIdx]==dispIdx,1);
fseek(h,Index(indexIdx(1)).offset + 40,'bof'); % Beginning of current montage name
displayName = deblank(char(fread(h,32,'uint16')).');
fseek(h,640,'cof'); % Number of traces in the montage
numTraces = fread(h,1,'uint32');
numTraces2 = fread(h,1,'uint32');
if (numTraces == numDerivations)
for i = 1:numTraces
fseek(h,32,'cof');
montage(i).color = fread(h,1,'uint32'); % Use typecast(uint32(montage(i).color),'uint8') to convert to RGB array
fseek(h,136-4,'cof');
end
else
disp('Could not match montage derivations with display color table');
end
end
|
github
|
lcnhappe/happe-master
|
avw_hdr_read.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/avw_hdr_read.m
| 16,654 |
utf_8
|
f63f3dbd244a89c6108eff59453680c3
|
function [ avw, machine ] = avw_hdr_read(fileprefix, machine, verbose)
% avw_hdr_read - read Analyze format data header (*.hdr)
%
% [ avw, machine ] = avw_hdr_read(fileprefix, [machine], [verbose])
%
% fileprefix - string filename (without .hdr); the file name
% can be given as a full path or relative to the
% current directory.
%
% machine - a string, see machineformat in fread for details.
% The default here is 'ieee-le' but the routine
% will automatically switch between little and big
% endian to read any such Analyze header. It
% reports the appropriate machine format and can
% return the machine value.
%
% avw.hdr - a struct, all fields returned from the header.
% For details, find a good description on the web
% or see the Analyze File Format pdf in the
% mri_toolbox doc folder or read this .m file.
%
% verbose - the default is to output processing information to the command
% window. If verbose = 0, this will not happen.
%
% This function is called by avw_img_read
%
% See also avw_hdr_write, avw_hdr_make, avw_view_hdr, avw_view
%
% $Revision$ $Date: 2009/01/14 09:24:45 $
% Licence: GNU GPL, no express or implied warranties
% History: 05/2002, [email protected]
% The Analyze format and c code below is copyright
% (c) Copyright, 1986-1995
% Biomedical Imaging Resource, Mayo Foundation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~exist('verbose','var'), verbose = 1; end
if verbose,
version = '[$Revision$]';
fprintf('\nAVW_HDR_READ [v%s]\n',version(12:16)); tic;
end
if ~exist('fileprefix','var'),
msg = sprintf('...no input fileprefix - see help avw_hdr_read\n\n');
error(msg);
end
if ~exist('machine','var'), machine = 'ieee-le'; end
if findstr('.hdr',fileprefix),
% fprintf('...removing .hdr extension from ''%s''\n',fileprefix);
fileprefix = strrep(fileprefix,'.hdr','');
end
if findstr('.img',fileprefix),
% fprintf('...removing .img extension from ''%s''\n',fileprefix);
fileprefix = strrep(fileprefix,'.img','');
end
file = sprintf('%s.hdr',fileprefix);
if exist(file),
if verbose,
fprintf('...reading %s Analyze format',machine);
end
fid = fopen(file,'r',machine);
avw.hdr = read_header(fid,verbose);
avw.fileprefix = fileprefix;
fclose(fid);
if ~isequal(avw.hdr.hk.sizeof_hdr,348),
if verbose, fprintf('...failed.\n'); end
% first try reading the opposite endian to 'machine'
switch machine,
case 'ieee-le', machine = 'ieee-be';
case 'ieee-be', machine = 'ieee-le';
end
if verbose, fprintf('...reading %s Analyze format',machine); end
fid = fopen(file,'r',machine);
avw.hdr = read_header(fid,verbose);
avw.fileprefix = fileprefix;
fclose(fid);
end
if ~isequal(avw.hdr.hk.sizeof_hdr,348),
% Now throw an error
if verbose, fprintf('...failed.\n'); end
msg = sprintf('...size of header not equal to 348 bytes!\n\n');
error(msg);
end
else
msg = sprintf('...cannot find file %s.hdr\n\n',file);
error(msg);
end
if verbose,
t=toc; fprintf('...done (%5.2f sec).\n',t);
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ dsr ] = read_header(fid,verbose)
% Original header structures - ANALYZE 7.5
%struct dsr
% {
% struct header_key hk; /* 0 + 40 */
% struct image_dimension dime; /* 40 + 108 */
% struct data_history hist; /* 148 + 200 */
% }; /* total= 348 bytes*/
dsr.hk = header_key(fid);
dsr.dime = image_dimension(fid,verbose);
dsr.hist = data_history(fid);
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [hk] = header_key(fid)
% The required elements in the header_key substructure are:
%
% int sizeof_header Must indicate the byte size of the header file.
% int extents Should be 16384, the image file is created as
% contiguous with a minimum extent size.
% char regular Must be 'r' to indicate that all images and
% volumes are the same size.
% Original header structures - ANALYZE 7.5
% struct header_key /* header key */
% { /* off + size */
% int sizeof_hdr /* 0 + 4 */
% char data_type[10]; /* 4 + 10 */
% char db_name[18]; /* 14 + 18 */
% int extents; /* 32 + 4 */
% short int session_error; /* 36 + 2 */
% char regular; /* 38 + 1 */
% char hkey_un0; /* 39 + 1 */
% }; /* total=40 bytes */
fseek(fid,0,'bof');
hk.sizeof_hdr = fread(fid, 1,'*int32'); % should be 348!
hk.data_type = fread(fid,10,'*char')';
hk.db_name = fread(fid,18,'*char')';
hk.extents = fread(fid, 1,'*int32');
hk.session_error = fread(fid, 1,'*int16');
hk.regular = fread(fid, 1,'*char')'; % might be uint8
hk.hkey_un0 = fread(fid, 1,'*uint8')';
% check if this value was a char zero
if hk.hkey_un0 == 48,
hk.hkey_un0 = 0;
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ dime ] = image_dimension(fid,verbose)
%struct image_dimension
% { /* off + size */
% short int dim[8]; /* 0 + 16 */
% /*
% dim[0] Number of dimensions in database; usually 4.
% dim[1] Image X dimension; number of *pixels* in an image row.
% dim[2] Image Y dimension; number of *pixel rows* in slice.
% dim[3] Volume Z dimension; number of *slices* in a volume.
% dim[4] Time points; number of volumes in database
% */
% char vox_units[4]; /* 16 + 4 */
% char cal_units[8]; /* 20 + 8 */
% short int unused1; /* 28 + 2 */
% short int datatype; /* 30 + 2 */
% short int bitpix; /* 32 + 2 */
% short int dim_un0; /* 34 + 2 */
% float pixdim[8]; /* 36 + 32 */
% /*
% pixdim[] specifies the voxel dimensions:
% pixdim[1] - voxel width, mm
% pixdim[2] - voxel height, mm
% pixdim[3] - slice thickness, mm
% pixdim[4] - volume timing, in msec
% ..etc
% */
% float vox_offset; /* 68 + 4 */
% float roi_scale; /* 72 + 4 */
% float funused1; /* 76 + 4 */
% float funused2; /* 80 + 4 */
% float cal_max; /* 84 + 4 */
% float cal_min; /* 88 + 4 */
% int compressed; /* 92 + 4 */
% int verified; /* 96 + 4 */
% int glmax; /* 100 + 4 */
% int glmin; /* 104 + 4 */
% }; /* total=108 bytes */
dime.dim = fread(fid,8,'*int16')';
dime.vox_units = fread(fid,4,'*char')';
dime.cal_units = fread(fid,8,'*char')';
dime.unused1 = fread(fid,1,'*int16');
dime.datatype = fread(fid,1,'*int16');
dime.bitpix = fread(fid,1,'*int16');
dime.dim_un0 = fread(fid,1,'*int16');
dime.pixdim = fread(fid,8,'*float')';
dime.vox_offset = fread(fid,1,'*float');
dime.roi_scale = fread(fid,1,'*float');
dime.funused1 = fread(fid,1,'*float');
dime.funused2 = fread(fid,1,'*float');
dime.cal_max = fread(fid,1,'*float');
dime.cal_min = fread(fid,1,'*float');
dime.compressed = fread(fid,1,'*int32');
dime.verified = fread(fid,1,'*int32');
dime.glmax = fread(fid,1,'*int32');
dime.glmin = fread(fid,1,'*int32');
if dime.dim(1) < 4, % Number of dimensions in database; usually 4.
if verbose,
fprintf('...ensuring 4 dimensions in avw.hdr.dime.dim\n');
end
dime.dim(1) = int16(4);
end
if dime.dim(5) < 1, % Time points; number of volumes in database
if verbose,
fprintf('...ensuring at least 1 volume in avw.hdr.dime.dim(5)\n');
end
dime.dim(5) = int16(1);
end
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ hist ] = data_history(fid)
% Original header structures - ANALYZE 7.5
%struct data_history
% { /* off + size */
% char descrip[80]; /* 0 + 80 */
% char aux_file[24]; /* 80 + 24 */
% char orient; /* 104 + 1 */
% char originator[10]; /* 105 + 10 */
% char generated[10]; /* 115 + 10 */
% char scannum[10]; /* 125 + 10 */
% char patient_id[10]; /* 135 + 10 */
% char exp_date[10]; /* 145 + 10 */
% char exp_time[10]; /* 155 + 10 */
% char hist_un0[3]; /* 165 + 3 */
% int views /* 168 + 4 */
% int vols_added; /* 172 + 4 */
% int start_field; /* 176 + 4 */
% int field_skip; /* 180 + 4 */
% int omax; /* 184 + 4 */
% int omin; /* 188 + 4 */
% int smax; /* 192 + 4 */
% int smin; /* 196 + 4 */
% }; /* total=200 bytes */
hist.descrip = fread(fid,80,'*char')';
hist.aux_file = fread(fid,24,'*char')';
hist.orient = fread(fid, 1,'*uint8'); % see note below on char
hist.originator = fread(fid,10,'*char')';
hist.generated = fread(fid,10,'*char')';
hist.scannum = fread(fid,10,'*char')';
hist.patient_id = fread(fid,10,'*char')';
hist.exp_date = fread(fid,10,'*char')';
hist.exp_time = fread(fid,10,'*char')';
hist.hist_un0 = fread(fid, 3,'*char')';
hist.views = fread(fid, 1,'*int32');
hist.vols_added = fread(fid, 1,'*int32');
hist.start_field = fread(fid, 1,'*int32');
hist.field_skip = fread(fid, 1,'*int32');
hist.omax = fread(fid, 1,'*int32');
hist.omin = fread(fid, 1,'*int32');
hist.smax = fread(fid, 1,'*int32');
hist.smin = fread(fid, 1,'*int32');
% check if hist.orient was saved as ascii char value
switch hist.orient,
case 48, hist.orient = uint8(0);
case 49, hist.orient = uint8(1);
case 50, hist.orient = uint8(2);
case 51, hist.orient = uint8(3);
case 52, hist.orient = uint8(4);
case 53, hist.orient = uint8(5);
end
return
% Note on using char:
% The 'char orient' field in the header is intended to
% hold simply an 8-bit unsigned integer value, not the ASCII representation
% of the character for that value. A single 'char' byte is often used to
% represent an integer value in Analyze if the known value range doesn't
% go beyond 0-255 - saves a byte over a short int, which may not mean
% much in today's computing environments, but given that this format
% has been around since the early 1980's, saving bytes here and there on
% older systems was important! In this case, 'char' simply provides the
% byte of storage - not an indicator of the format for what is stored in
% this byte. Generally speaking, anytime a single 'char' is used, it is
% probably meant to hold an 8-bit integer value, whereas if this has
% been dimensioned as an array, then it is intended to hold an ASCII
% character string, even if that was only a single character.
% Denny <[email protected]>
% Comments
% The header format is flexible and can be extended for new
% user-defined data types. The essential structures of the header
% are the header_key and the image_dimension.
%
% The required elements in the header_key substructure are:
%
% int sizeof_header Must indicate the byte size of the header file.
% int extents Should be 16384, the image file is created as
% contiguous with a minimum extent size.
% char regular Must be 'r' to indicate that all images and
% volumes are the same size.
%
% The image_dimension substructure describes the organization and
% size of the images. These elements enable the database to reference
% images by volume and slice number. Explanation of each element follows:
%
% short int dim[ ]; /* Array of the image dimensions */
%
% dim[0] Number of dimensions in database; usually 4.
% dim[1] Image X dimension; number of pixels in an image row.
% dim[2] Image Y dimension; number of pixel rows in slice.
% dim[3] Volume Z dimension; number of slices in a volume.
% dim[4] Time points; number of volumes in database.
% dim[5] Undocumented.
% dim[6] Undocumented.
% dim[7] Undocumented.
%
% char vox_units[4] Specifies the spatial units of measure for a voxel.
% char cal_units[8] Specifies the name of the calibration unit.
% short int unused1 /* Unused */
% short int datatype /* Datatype for this image set */
% /*Acceptable values for datatype are*/
% #define DT_NONE 0
% #define DT_UNKNOWN 0 /*Unknown data type*/
% #define DT_BINARY 1 /*Binary ( 1 bit per voxel)*/
% #define DT_UNSIGNED_CHAR 2 /*Unsigned character ( 8 bits per voxel)*/
% #define DT_SIGNED_SHORT 4 /*Signed short (16 bits per voxel)*/
% #define DT_SIGNED_INT 8 /*Signed integer (32 bits per voxel)*/
% #define DT_FLOAT 16 /*Floating point (32 bits per voxel)*/
% #define DT_COMPLEX 32 /*Complex (64 bits per voxel; 2 floating point numbers)/*
% #define DT_DOUBLE 64 /*Double precision (64 bits per voxel)*/
% #define DT_RGB 128 /*A Red-Green-Blue datatype*/
% #define DT_ALL 255 /*Undocumented*/
%
% short int bitpix; /* Number of bits per pixel; 1, 8, 16, 32, or 64. */
% short int dim_un0; /* Unused */
%
% float pixdim[]; Parallel array to dim[], giving real world measurements in mm and ms.
% pixdim[0]; Pixel dimensions?
% pixdim[1]; Voxel width in mm.
% pixdim[2]; Voxel height in mm.
% pixdim[3]; Slice thickness in mm.
% pixdim[4]; timeslice in ms (ie, TR in fMRI).
% pixdim[5]; Undocumented.
% pixdim[6]; Undocumented.
% pixdim[7]; Undocumented.
%
% float vox_offset; Byte offset in the .img file at which voxels start. This value can be
% negative to specify that the absolute value is applied for every image
% in the file.
%
% float roi_scale; Specifies the Region Of Interest scale?
% float funused1; Undocumented.
% float funused2; Undocumented.
%
% float cal_max; Specifies the upper bound of the range of calibration values.
% float cal_min; Specifies the lower bound of the range of calibration values.
%
% int compressed; Undocumented.
% int verified; Undocumented.
%
% int glmax; The maximum pixel value for the entire database.
% int glmin; The minimum pixel value for the entire database.
%
%
|
github
|
lcnhappe/happe-master
|
read_stl.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_stl.m
| 4,432 |
utf_8
|
6aec08043b6655fd9efe5194e20bf28f
|
function [pnt, tri, nrm] = read_stl(filename)
% READ_STL reads a triangulation from an ascii or binary *.stl file, which
% is a file format native to the stereolithography CAD software created by
% 3D Systems.
%
% Use as
% [pnt, tri, nrm] = read_stl(filename)
%
% The format is described at http://en.wikipedia.org/wiki/STL_(file_format)
%
% See also WRITE_STL
% Copyright (C) 2006-2011, 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');
% read a small section to determine whether it is ascii or binary
% a binary STL file has an 80 byte asci header, followed by non-printable characters
section = fread(fid, 160, 'uint8');
fseek(fid, 0, 'bof');
if printableascii(section)
% the first 160 characters are printable ascii, so assume it is an ascii format
% solid testsphere
% facet normal -0.13 -0.13 -0.98
% outer loop
% vertex 1.50000 1.50000 0.00000
% vertex 1.50000 1.11177 0.05111
% vertex 1.11177 1.50000 0.05111
% endloop
% endfacet
% ...
ntri = 0;
while ~feof(fid)
line = fgetl(fid);
ntri = ntri + ~isempty(findstr('facet normal', line));
end
fseek(fid, 0, 'bof');
tri = zeros(ntri,3);
nrm = zeros(ntri,3);
pnt = zeros(ntri*3,3);
line = fgetl(fid);
name = sscanf(line, 'solid %s');
for i=1:ntri
line1 = fgetl(fid);
line2 = fgetl(fid); % outer loop
line3 = fgetl(fid);
line4 = fgetl(fid);
line5 = fgetl(fid);
line6 = fgetl(fid); % endloop
line7 = fgetl(fid); % endfacet
i1 = (i-1)*3+1;
i2 = (i-1)*3+2;
i3 = (i-1)*3+3;
tri(i,:) = [i1 i2 i3];
dum = sscanf(strtrim(line1), 'facet normal %f %f %f'); nrm(i,:) = dum(:)';
dum = sscanf(strtrim(line3), 'vertex %f %f %f'); pnt(i1,:) = dum(:)';
dum = sscanf(strtrim(line4), 'vertex %f %f %f'); pnt(i2,:) = dum(:)';
dum = sscanf(strtrim(line5), 'vertex %f %f %f'); pnt(i3,:) = dum(:)';
end
else
% reopen the file in binary mode, which does not make a difference on
% UNIX but it does on windows
fclose(fid);
fid = fopen(filename, 'rb');
fseek(fid, 80, 'bof'); % skip the ascii header
ntri = fread(fid, 1, 'uint32');
tri = reshape(1:(ntri*3),[3 ntri])';
tmp = fread(fid, [12 ntri], '12*float32', 2); % read 12 floats at a time, and skip 2 bytes.
nrm = tmp(1:3,:)';
tmp = reshape(tmp(4:end,:),[3 3 ntri]); % position info
tmp = permute(tmp,[2 3 1]);
pnt = reshape(tmp, [], 3);
% the above replaces the below, which is much slower, because it is using
% a for loop across triangles
% tri = zeros(ntri,3);
% nrm = zeros(ntri,3);
% pnt = zeros(ntri*3,3);
% attr = zeros(ntri,1);
% for i=1:ntri
% i1 = (i-1)*3+1;
% i2 = (i-1)*3+2;
% i3 = (i-1)*3+3;
% tri(i,:) = [i1 i2 i3];
% nrm(i,:) = fread(fid, 3, 'float32');
% pnt(i1,:) = fread(fid, 3, 'float32');
% pnt(i2,:) = fread(fid, 3, 'float32');
% pnt(i3,:) = fread(fid, 3, 'float32');
% attr(i) = fread(fid, 1, 'uint16'); % Attribute byte count, don't know what it is
% end % for each triangle
end
fclose(fid);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function retval = printableascii(num)
% Codes 20hex (32dec) to 7Ehex (126dec), known as the printable characters,
% represent letters, digits, punctuation marks, and a few miscellaneous
% symbols. There are 95 printable characters in total.
num = double(num);
num(num==double(sprintf('\n'))) = double(sprintf(' '));
num(num==double(sprintf('\r'))) = double(sprintf(' '));
num(num==double(sprintf('\t'))) = double(sprintf(' '));
retval = all(num>=32 & num<=126);
|
github
|
lcnhappe/happe-master
|
read_itab_mhd.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_itab_mhd.m
| 12,518 |
utf_8
|
d0ebd0b4e1de627d76cb523010d16ec7
|
function mhd = read_itab_mhd(filename)
fid = fopen(filename, 'rb');
% Name of structure
mhd.stname = fread(fid, [1 10], 'uint8=>char'); % Header identifier (VP_BIOMAG)
mhd.stver = fread(fid, [1 8], 'uint8=>char'); % Header version
mhd.stendian = fread(fid, [1 4], 'uint8=>char'); % LE (little endian) or BE (big endian) format
% Subject's INFOs
mhd.first_name = fread(fid, [1 32], 'uint8=>char'); % Subject's first name
mhd.last_name = fread(fid, [1 32], 'uint8=>char'); % Subject's family name
mhd.id = fread(fid, [1 32], 'uint8=>char'); % Subject's id
mhd.notes = fread(fid, [1 256], 'uint8=>char'); % Notes on measurement
% Other subj infos
mhd.subj_info.sex = fread(fid, [1 1], 'uint8=>char'); % Sex (M or F)
pad = fread(fid, [1 5], 'uint8');
mhd.subj_info.notes = fread(fid, [1 256], 'uint8=>char'); % Notes on subject
mhd.subj_info.height = fread(fid, [1 1], 'float'); % Height in cm
mhd.subj_info.weight = fread(fid, [1 1], 'float'); % Weight in kg
mhd.subj_info.birthday = fread(fid, [1 1], 'int32'); % Birtday (1-31)
mhd.subj_info.birthmonth = fread(fid, [1 1], 'int32'); % Birthmonth (1-12)
mhd.subj_info.birthyear = fread(fid, [1 1], 'int32'); % Birthyear (1900-2002)
% Data acquisition INFOs
mhd.time = fread(fid, [1 12], 'uint8=>char'); % time (ascii)
mhd.date = fread(fid, [1 16], 'uint8=>char'); % date (ascii)
mhd.nchan = fread(fid, [1 1], 'int32'); % total number of channels
mhd.nelech = fread(fid, [1 1], 'int32'); % number of electric channels
mhd.nelerefch = fread(fid, [1 1], 'int32'); % number of electric reference channels
mhd.nmagch = fread(fid, [1 1], 'int32'); % number of magnetic channels
mhd.nmagrefch = fread(fid, [1 1], 'int32'); % number of magnetic reference channels
mhd.nauxch = fread(fid, [1 1], 'int32'); % number of auxiliary channels
mhd.nparamch = fread(fid, [1 1], 'int32'); % number of parameter channels
mhd.ndigitch = fread(fid, [1 1], 'int32'); % number of digit channels
mhd.nflagch = fread(fid, [1 1], 'int32'); % number of flag channels
mhd.data_type = fread(fid, [1 1], 'int32'); % 0 - BE_SHORT (HP-PA, big endian)
% 1 - BE_LONG (HP-PA, big endian)
% 2 - BE_FLOAT (HP-PA, big endian)
% 3 - LE_SHORT (Intel, little endian)
% 4 - LE_LONG (Intel, little endian)
% 5 - LE_FLOAT (Intel, little endian)
% 6 - RTE_A_SHORT (HP-A900, big endian)
% 7 - RTE_A_FLOAT (HP-A900, big endian)
% 8 - ASCII
mhd.smpfq = fread(fid, [1 1], 'single'); % sampling frequency in Hz
mhd.hw_low_fr = fread(fid, [1 1], 'single'); % hw data acquisition low pass filter
mhd.hw_hig_fr = fread(fid, [1 1], 'single'); % hw data acquisition high pass filter
mhd.hw_comb = fread(fid, [1 1], 'int32'); % hw data acquisition 50 Hz filter (1-TRUE)
mhd.sw_hig_tc = fread(fid, [1 1], 'single'); % sw data acquisition high pass time constant
mhd.compensation= fread(fid, [1 1], 'int32'); % 0 - no compensation 1 - compensation
mhd.ntpdata = fread(fid, [1 1], 'int32'); % total number of time points in data
mhd.no_segments = fread(fid, [1 1], 'int32'); % Number of segments described in the segment structure
% INFOs on different segments
for i=1:5
mhd.sgmt(i).start = fread(fid, [1 1], 'int32'); % Starting time point from beginning of data
mhd.sgmt(i).ntptot = fread(fid, [1 1], 'int32'); % Total number of time points
mhd.sgmt(i).type = fread(fid, [1 1], 'int32');
mhd.sgmt(i).no_samples = fread(fid, [1 1], 'int32');
mhd.sgmt(i).st_sample = fread(fid, [1 1], 'int32');
end
mhd.nsmpl = fread(fid, [1 1], 'int32'); % Overall number of samples
% INFOs on different samples
for i=1:4096
mhd.smpl(i).start = fread(fid, [1 1], 'int32'); % Starting time point from beginning of data
mhd.smpl(i).ntptot = fread(fid, [1 1], 'int32'); % Total number of time points
mhd.smpl(i).ntppre = fread(fid, [1 1], 'int32'); % Number of points in pretrigger
mhd.smpl(i).type = fread(fid, [1 1], 'int32');
mhd.smpl(i).quality = fread(fid, [1 1], 'int32');
end
mhd.nrefchan = fread(fid, [1 1], 'int32'); % number of reference channels
mhd.ref_ch = fread(fid, [1 640], 'int32'); % reference channel list
mhd.ntpref = fread(fid, [1 1], 'int32'); % total number of time points in reference
% Header INFOs
mhd.raw_header_type = fread(fid, [1 1], 'int32'); % 0 - Unknown header
% 2 - rawfile (A900)
% 3 - GE runfile header
% 31 - ATB runfile header version 1.0
% 41 - IFN runfile header version 1.0
% 51 - BMDSys runfile header version 1.0
mhd.header_type = fread(fid, [1 1], 'int32'); % 0 - Unknown header
% 2 - rawfile (A900)
% 3 - GE runfile header
% 4 - old header
% 10 - 256ch normal header
% 11 - 256ch master header
% 20 - 640ch normal header
% 21 - 640ch master header
% 31 - ATB runfile header version 1.0
% 41 - IFN runfile header version 1.0
% 51 - BMDSys runfile header version 1.0
mhd.conf_file = fread(fid, [1 64], 'uint8=>char'); % Filename used for data acquisition configuration
mhd.header_size = fread(fid, [1 1], 'int32'); % sizeof(header) at the time of file creation
mhd.start_reference = fread(fid, [1 1], 'int32'); % start reference
mhd.start_data = fread(fid, [1 1], 'int32'); % start data
mhd.rawfile = fread(fid, [1 1], 'int32'); % 0 - not a rawfile 1 - rawfile
mhd.multiplexed_data = fread(fid, [1 1], 'int32'); % 0 - FALSE 1 - TRUE
mhd.isns = fread(fid, [1 1], 'int32'); % sensor code 1 - Single channel
% 28 - Original Rome 28 ch.
% 29 - ..............
% .. - ..............
% 45 - Updated Rome 28 ch. (spring 2009)
% .. - ..............
% .. - ..............
% 55 - Original Chieti 55 ch. flat
% 153 - Original Chieti 153 ch. helmet
% 154 - Chieti 153 ch. helmet from Jan 2002
% Channel's INFOs
for i=1:640
mhd.ch(i).type = fread(fid, [1 1], 'uint8');
pad = fread(fid, [1 3], 'uint8');
% type 0 - unknown
% 1 - ele
% 2 - mag
% 4 - ele ref
% 8 - mag ref
% 16 - aux
% 32 - param
% 64 - digit
% 128 - flag
mhd.ch(i).number = fread(fid, [1 1], 'int32'); % number
mhd.ch(i).label = fixstr(fread(fid, [1 16], 'uint8=>char')); % label
mhd.ch(i).flag = fread(fid, [1 1], 'uint8');
pad = fread(fid, [1 3], 'uint8');
% on/off flag 0 - working channel
% 1 - noisy channel
% 2 - very noisy channel
% 3 - broken channel
mhd.ch(i).amvbit = fread(fid, [1 1], 'float'); % calibration from LSB to mV
mhd.ch(i).calib = fread(fid, [1 1], 'float'); % calibration from mV to unit
mhd.ch(i).unit = fread(fid, [1 6], 'uint8=>char'); % unit label (fT, uV, ...)
pad = fread(fid, [1 2], 'uint8');
mhd.ch(i).ncoils = fread(fid, [1 1], 'int32'); % number of coils building up one channel
mhd.ch(i).wgt = fread(fid, [1 10], 'float'); % weight of coils
% position and orientation of coils
for j=1:10
mhd.ch(i).position(j).r_s = fread(fid, [1 3], 'float');
mhd.ch(i).position(j).u_s = fread(fid, [1 3], 'float');
end
end
% Sensor position INFOs
mhd.r_center = fread(fid, [1 3], 'float'); % sensor position in convenient format
mhd.u_center = fread(fid, [1 3], 'float');
mhd.th_center = fread(fid, [1 1], 'float'); % sensor orientation as from markers fit
mhd.fi_center= fread(fid, [1 1], 'float');
mhd.rotation_angle= fread(fid, [1 1], 'float');
mhd.cosdir = fread(fid, [3 3], 'float'); % for compatibility only
mhd.irefsys = fread(fid, [1 1], 'int32'); % reference system 0 - sensor reference system
% 1 - Polhemus
% 2 - head3
% 3 - MEG
% Marker positions for MRI integration
mhd.num_markers = fread(fid, [1 1], 'int32'); % Total number of markers
mhd.i_coil = fread(fid, [1 64], 'int32'); % Markers to be used to find sensor position
mhd.marker = fread(fid, [3 64], 'float'); % Position of all the markers - MODIFIED VP
mhd.best_chi = fread(fid, [1 1], 'float'); % Best chi_square value obtained in finding sensor position
mhd.cup_vertex_center = fread(fid, [1 1], 'float'); % dist anc sensor cente vertex (as entered
% from keyboard)
mhd.cup_fi_center = fread(fid, [1 1], 'float'); % fi angle of sensor center
mhd.cup_rotation_angle = fread(fid, [1 1], 'float'); % rotation angle of sensor center axis
mhd.dist_a1_a2 = fread(fid, [1 1], 'float'); % head informations
% (used to find subject's head dimensions)
mhd.dist_inion_nasion = fread(fid, [1 1], 'float');
mhd.max_circ = fread(fid, [1 1], 'float');
mhd.nasion_vertex_inion = fread(fid, [1 1], 'float');
% Data analysis INFOs
mhd.security = fread(fid, [1 1], 'int32'); % security flag
mhd.ave_alignement = fread(fid, [1 1], 'int32'); % average data alignement 0 - FALSE
% 1 - TRUE
mhd.itri = fread(fid, [1 1], 'int32'); % trigger channel number
mhd.ntpch = fread(fid, [1 1], 'int32'); % no. of time points per channel
mhd.ntppre = fread(fid, [1 1], 'int32'); % no. of time points of pretrigger
mhd.navrg = fread(fid, [1 1], 'int32'); % no. of averages
mhd.nover = fread(fid, [1 1], 'int32'); % no. of discarded averages
mhd.nave_filt = fread(fid, [1 1], 'int32'); % no. of applied filters
% Filters used before average
for i=1:15
mhd.ave_filt(i).type = fread(fid, [1 1], 'int32'); % type 0 - no filter
% 1 - bandpass - param[0]: highpass freq
% - param[1]: lowpass freq
% 2 - notch - param[0]: notch freq 1
% param[1]: notch freq 2
% param[2]: notch freq 3
% param[3]: notch freq 4
% param[4]: span
% 3 - artifact - param[0]: True/False
% 4 - adaptive - param[0]: True/False
% 5 - rectifier - param[0]: True/False
% 6 - heart - param[0]: True/False
% 7 - evoked - param[0]: True/False
% 8 - derivate - param[0]: True/False
% 9 - polarity - param[0]: True/False
mhd.ave_filt(i).param = fread(fid, [1 5], 'float'); % up to 5 filter parameters
end
mhd.stdev = fread(fid, [1 1], 'int32'); % 0 - not present
mhd.bas_start = fread(fid, [1 1], 'int32'); % starting data points for baseline
mhd.bas_end = fread(fid, [1 1], 'int32'); % ending data points for baseline
mhd.source_files = fread(fid, [1 32], 'int32'); % Progressive number of files (if more than one)
% template INFOs
mhd.ichtpl = fread(fid, [1 1], 'int32');
mhd.ntptpl = fread(fid, [1 1], 'int32');
mhd.ifitpl = fread(fid, [1 1], 'int32');
mhd.corlim = fread(fid, [1 1], 'float');
% Filters used before template
for i=1:15
mhd.tpl_filt(i).type = fread(fid, [1 1], 'int32'); % type 0 - no filter
% 1 - bandpass - param[0]: highpass freq
% - param[1]: lowpass freq
% 2 - notch - param[0]: notch freq 1
% param[1]: notch freq 2
% param[2]: notch freq 3
% param[3]: notch freq 4
% param[4]: span
% 3 - artifact - param[0]: True/False
% 4 - adaptive - param[0]: True/False
% 5 - rectifier - param[0]: True/False
% 6 - heart - param[0]: True/False
% 7 - evoked - param[0]: True/False
% 8 - derivate - param[0]: True/False
% 9 - polarity - param[0]: True/False
mhd.tpl_filt(i).param = fread(fid, [1 5], 'float'); % up to 5 filter parameters
end
% Just in case info
mhd.dummy = fread(fid, [1 64], 'int32');
% there seems to be more dummy data at the end...
fclose(fid);
function str = fixstr(str)
sel = find(str==0, 1, 'first');
if ~isempty(sel)
str = str(1:sel-1);
end
|
github
|
lcnhappe/happe-master
|
read_plexon_plx.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_plexon_plx.m
| 20,283 |
utf_8
|
ec115cb91003e60359655fdd73fdfdb6
|
function [varargout] = read_plexon_plx(filename, varargin)
% READ_PLEXON_PLX reads header or data from a Plexon *.plx file, which
% is a file containing action-potential (spike) timestamps and waveforms
% (spike channels), event timestamps (event channels), and continuous
% variable data (continuous A/D channels).
%
% Use as
% [hdr] = read_plexon_plx(filename)
% [dat] = read_plexon_plx(filename, ...)
% [dat1, dat2, dat3, hdr] = read_plexon_plx(filename, ...)
%
% Optional input arguments should be specified in key-value pairs
% 'header' = structure with header information
% 'memmap' = 0 or 1
% 'feedback' = 0 or 1
% 'ChannelIndex' = number, or list of numbers (that will result in multiple outputs)
% 'SlowChannelIndex' = number, or list of numbers (that will result in multiple outputs)
% 'EventIndex' = number, or list of numbers (that will result in multiple outputs)
% Copyright (C) 2007-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$
% parse the optional input arguments
hdr = ft_getopt(varargin, 'header');
memmap = ft_getopt(varargin, 'memmap', false);
feedback = ft_getopt(varargin, 'feedback', true);
ChannelIndex = ft_getopt(varargin, 'ChannelIndex'); % type 1
EventIndex = ft_getopt(varargin, 'EventIndex'); % type 4
SlowChannelIndex = ft_getopt(varargin, 'SlowChannelIndex'); % type 5
needhdr = isempty(hdr);
% start with empty return values
varargout = {};
% the datafile is little endian, hence it may be neccessary to swap bytes in
% the memory mapped data stream depending on the CPU type of this computer
if littleendian
swapFcn = @(x) x;
else
swapFcn = @(x) swapbytes(x);
end
% read header info from file, use Matlabs for automatic byte-ordering
fid = fopen(filename, 'r', 'ieee-le');
fseek(fid, 0, 'eof');
siz = ftell(fid);
fseek(fid, 0, 'bof');
if needhdr
if feedback, fprintf('reading header from %s\n', filename); end
% a PLX file consists of a file header, channel headers, and data blocks
hdr = PL_FileHeader(fid);
for i=1:hdr.NumDSPChannels
hdr.ChannelHeader(i) = PL_ChannelHeader(fid);
end
for i=1:hdr.NumEventChannels
hdr.EventHeader(i) = PL_EventHeader(fid);
end
for i=1:hdr.NumSlowChannels
hdr.SlowChannelHeader(i) = PL_SlowChannelHeader(fid);
end
hdr.DataOffset = ftell(fid);
if memmap
% open the file as meory mapped object, note that byte swapping may be needed
mm = memmapfile(filename, 'offset', hdr.DataOffset, 'format', 'int16');
end
dum = struct(...
'Type', [],...
'UpperByteOf5ByteTimestamp', [],...
'TimeStamp', [],...
'Channel', [],...
'Unit', [],...
'NumberOfWaveforms', [],...
'NumberOfWordsInWaveform', [] ...
);
% read the header of each data block and remember its data offset in bytes
Nblocks = 0;
offset = hdr.DataOffset; % only used when reading from memmapped file
hdr.DataBlockOffset = [];
hdr.DataBlockHeader = dum;
while offset<siz
if Nblocks>=length(hdr.DataBlockOffset);
% allocate another 1000 elements, this prevents continuous reallocation
hdr.DataBlockOffset(Nblocks+10000) = 0;
hdr.DataBlockHeader(Nblocks+10000) = dum;
if feedback, fprintf('reading DataBlockHeader %4.1f%%\n', 100*(offset-hdr.DataOffset)/(siz-hdr.DataOffset)); end
end
Nblocks = Nblocks+1;
if memmap
% get the header information from the memory mapped file
hdr.DataBlockOffset(Nblocks) = offset;
hdr.DataBlockHeader(Nblocks) = PL_DataBlockHeader(mm, offset-hdr.DataOffset, swapFcn);
% skip the header (16 bytes) and the data (int16 words)
offset = offset + 16 + 2 * double(hdr.DataBlockHeader(Nblocks).NumberOfWordsInWaveform * hdr.DataBlockHeader(Nblocks).NumberOfWaveforms);
else
% read the header information from the file the traditional way
hdr.DataBlockOffset(Nblocks) = offset;
hdr.DataBlockHeader(Nblocks) = PL_DataBlockHeader(fid, [], swapFcn);
fseek(fid, 2 * double(hdr.DataBlockHeader(Nblocks).NumberOfWordsInWaveform * hdr.DataBlockHeader(Nblocks).NumberOfWaveforms), 'cof'); % data consists of short integers
offset = ftell(fid);
end % if memmap
end
% this prints the final 100%
if feedback, fprintf('reading DataBlockHeader %4.1f%%\n', 100*(offset-hdr.DataOffset)/(siz-hdr.DataOffset)); end
% remove the allocated space that was not needed
hdr.DataBlockOffset = hdr.DataBlockOffset(1:Nblocks);
hdr.DataBlockHeader = hdr.DataBlockHeader(1:Nblocks);
end % if needhdr
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the spike channel data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(ChannelIndex)
if feedback, fprintf('reading spike data from %s\n', filename); end
if memmap
% open the file as meory mapped object, note that byte swapping may be needed
mm = memmapfile(filename, 'offset', hdr.DataOffset, 'format', 'int16');
end
type = [hdr.DataBlockHeader.Type];
chan = [hdr.DataBlockHeader.Channel];
ts = [hdr.DataBlockHeader.TimeStamp];
for i=1:length(ChannelIndex)
% determine the data blocks with continuous data belonging to this channel
sel = (type==1 & chan==hdr.ChannelHeader(ChannelIndex(i)).Channel);
sel = find(sel);
if isempty(sel)
warning('spike channel %d contains no data', ChannelIndex(i));
varargin{end+1} = [];
continue;
end
% the number of samples can potentially be different in each block
num = double([hdr.DataBlockHeader(sel).NumberOfWordsInWaveform]) .* double([hdr.DataBlockHeader(sel).NumberOfWaveforms]);
% check whether the number of samples per block makes sense
if any(num~=num(1))
error('spike channel blocks with diffent number of samples');
end
% allocate memory to hold the data
buf = zeros(num(1), length(sel), 'int16');
if memmap
% get the header information from the memory mapped file
datbeg = double(hdr.DataBlockOffset(sel) - hdr.DataOffset)/2 + 8 + 1; % expressed in 2-byte words, minus the file header, skip the 16 byte block header
datend = datbeg + num - 1;
for j=1:length(sel)
buf(:,j) = mm.Data(datbeg(j):datend(j));
end
% optionally swap the bytes to correct for the endianness
buf = swapFcn(buf);
else
% read the data from the file in the traditional way
offset = double(hdr.DataBlockOffset(sel)) + 16; % expressed in bytes, skip the 16 byte block header
for j=1:length(sel)
fseek(fid, offset(j), 'bof');
buf(:,j) = fread(fid, num(j), 'int16');
end
end % if memmap
% remember the data for this channel
varargout{i} = buf;
end %for ChannelIndex
end % if ChannelIndex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the continuous channel data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(SlowChannelIndex)
if feedback, fprintf('reading continuous data from %s\n', filename); end
if memmap
% open the file as meory mapped object, note that byte swapping may be needed
mm = memmapfile(filename, 'offset', hdr.DataOffset, 'format', 'int16');
end
type = [hdr.DataBlockHeader.Type];
chan = [hdr.DataBlockHeader.Channel];
ts = [hdr.DataBlockHeader.TimeStamp];
for i=1:length(SlowChannelIndex)
% determine the data blocks with continuous data belonging to this channel
sel = (type==5 & chan==hdr.SlowChannelHeader(SlowChannelIndex(i)).Channel);
sel = find(sel);
if isempty(sel)
error(sprintf('Continuous channel %d contains no data', SlowChannelIndex(i)));
% warning('Continuous channel %d contains no data', SlowChannelIndex(i));
% varargin{end+1} = [];
% continue;
end
% the number of samples can be different in each block
num = double([hdr.DataBlockHeader(sel).NumberOfWordsInWaveform]) .* double([hdr.DataBlockHeader(sel).NumberOfWaveforms]);
cumnum = cumsum([0 num]);
% allocate memory to hold the data
buf = zeros(1, cumnum(end), 'int16');
if memmap
% get the header information from the memory mapped file
datbeg = double(hdr.DataBlockOffset(sel) - hdr.DataOffset)/2 + 8 + 1; % expressed in 2-byte words, minus the file header, skip the 16 byte block header
datend = datbeg + num - 1;
for j=1:length(sel)
bufbeg = cumnum(j)+1;
bufend = cumnum(j+1);
% copy the data from the memory mapped file into the continuous buffer
buf(bufbeg:bufend) = mm.Data(datbeg(j):datend(j));
end
% optionally swap the bytes to correct for the endianness
buf = swapFcn(buf);
else
% read the data from the file in the traditional way
offset = double(hdr.DataBlockOffset(sel)) + 16; % expressed in bytes, skip the 16 byte block header
for j=1:length(sel)
bufbeg = cumnum(j)+1;
bufend = cumnum(j+1);
% copy the data from the file into the continuous buffer
fseek(fid, offset(j), 'bof');
buf(bufbeg:bufend) = fread(fid, num(j), 'int16');
end
end % if memmap
% remember the data for this channel
varargout{i} = buf;
end %for SlowChannelIndex
end % if SlowChannelIndex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read the event channel data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if ~isempty(EventIndex)
if feedback, fprintf('reading events from %s\n', filename); end
type = [hdr.DataBlockHeader.Type];
unit = [hdr.DataBlockHeader.Unit];
chan = [hdr.DataBlockHeader.Channel];
ts = [hdr.DataBlockHeader.TimeStamp];
for i=1:length(EventIndex)
% determine the data blocks with continuous data belonging to this channel
sel = (type==4 & chan==hdr.EventHeader(EventIndex(i)).Channel);
sel = find(sel);
% all information is already contained in the DataBlockHeader, i.e. there is nothing to read
if isempty(sel)
warning('event channel %d contains no data', EventIndex(i));
end
event.TimeStamp = ts(sel);
event.Channel = chan(sel);
event.Unit = unit(sel);
varargout{i} = event;
end % for EventIndex
end % if EventIndex
fclose(fid);
% always return the header as last
varargout{end+1} = hdr;
return
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTIONS for reading the different header elements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hdr = PL_FileHeader(fid)
hdr.MagicNumber = fread(fid, 1, 'uint32=>uint32'); % = 0x58454c50;
hdr.Version = fread(fid, 1, 'int32' ); % Version of the data format; determines which data items are valid
hdr.Comment = fread(fid, [1 128], 'uint8=>char' ); % User-supplied comment
hdr.ADFrequency = fread(fid, 1, 'int32' ); % Timestamp frequency in hertz
hdr.NumDSPChannels = fread(fid, 1, 'int32' ); % Number of DSP channel headers in the file
hdr.NumEventChannels = fread(fid, 1, 'int32' ); % Number of Event channel headers in the file
hdr.NumSlowChannels = fread(fid, 1, 'int32' ); % Number of A/D channel headers in the file
hdr.NumPointsWave = fread(fid, 1, 'int32' ); % Number of data points in waveform
hdr.NumPointsPreThr = fread(fid, 1, 'int32' ); % Number of data points before crossing the threshold
hdr.Year = fread(fid, 1, 'int32' ); % Time/date when the data was acquired
hdr.Month = fread(fid, 1, 'int32' );
hdr.Day = fread(fid, 1, 'int32' );
hdr.Hour = fread(fid, 1, 'int32' );
hdr.Minute = fread(fid, 1, 'int32' );
hdr.Second = fread(fid, 1, 'int32' );
hdr.FastRead = fread(fid, 1, 'int32' ); % reserved
hdr.WaveformFreq = fread(fid, 1, 'int32' ); % waveform sampling rate; ADFrequency above is timestamp freq
hdr.LastTimestamp = fread(fid, 1, 'double'); % duration of the experimental session, in ticks
% The following 6 items are only valid if Version >= 103
hdr.Trodalness = fread(fid, 1, 'char' ); % 1 for single, 2 for stereotrode, 4 for tetrode
hdr.DataTrodalness = fread(fid, 1, 'char' ); % trodalness of the data representation
hdr.BitsPerSpikeSample = fread(fid, 1, 'char' ); % ADC resolution for spike waveforms in bits (usually 12)
hdr.BitsPerSlowSample = fread(fid, 1, 'char' ); % ADC resolution for slow-channel data in bits (usually 12)
hdr.SpikeMaxMagnitudeMV = fread(fid, 1, 'uint16'); % the zero-to-peak voltage in mV for spike waveform adc values (usually 3000)
hdr.SlowMaxMagnitudeMV = fread(fid, 1, 'uint16'); % the zero-to-peak voltage in mV for slow-channel waveform adc values (usually 5000); Only valid if Version >= 105 (usually either 1000 or 500)
% The following item is only valid if Version >= 105
hdr.SpikePreAmpGain = fread(fid, 1, 'uint16'); % so that this part of the header is 256 bytes
hdr.Padding = fread(fid, 46, 'char' ); % so that this part of the header is 256 bytes
% Counters for the number of timestamps and waveforms in each channel and unit.
% Note that these only record the counts for the first 4 units in each channel.
% channel numbers are 1-based - array entry at [0] is unused
hdr.TSCounts = fread(fid, [5 130], 'int32' ); % number of timestamps[channel][unit]
hdr.WFCounts = fread(fid, [5 130], 'int32' ); % number of waveforms[channel][unit]
% Starting at index 300, the next array also records the number of samples for the
% continuous channels. Note that since EVCounts has only 512 entries, continuous
% channels above channel 211 do not have sample counts.
hdr.EVCounts = fread(fid, 512, 'int32' ); % number of timestamps[event_number]
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hdr = PL_ChannelHeader(fid)
hdr.Name = fread(fid, [1 32], 'uint8=>char' ); % Name given to the DSP channel
hdr.SIGName = fread(fid, [1 32], 'uint8=>char' ); % Name given to the corresponding SIG channel
hdr.Channel = fread(fid, 1, 'int32' ); % DSP channel number, 1-based
hdr.WFRate = fread(fid, 1, 'int32' ); % When MAP is doing waveform rate limiting, this is limit w/f per sec divided by 10
hdr.SIG = fread(fid, 1, 'int32' ); % SIG channel associated with this DSP channel 1 - based
hdr.Ref = fread(fid, 1, 'int32' ); % SIG channel used as a Reference signal, 1- based
hdr.Gain = fread(fid, 1, 'int32' ); % actual gain divided by SpikePreAmpGain. For pre version 105, actual gain divided by 1000.
hdr.Filter = fread(fid, 1, 'int32' ); % 0 or 1
hdr.Threshold = fread(fid, 1, 'int32' ); % Threshold for spike detection in a/d values
hdr.Method = fread(fid, 1, 'int32' ); % Method used for sorting units, 1 - boxes, 2 - templates
hdr.NUnits = fread(fid, 1, 'int32' ); % number of sorted units
hdr.Template = fread(fid, [64 5], 'int16' ); % Templates used for template sorting, in a/d values
hdr.Fit = fread(fid, 5, 'int32' ); % Template fit
hdr.SortWidth = fread(fid, 1, 'int32' ); % how many points to use in template sorting (template only)
hdr.Boxes = reshape(fread(fid, 4*2*5, 'int16' ), [4 2 5]); % the boxes used in boxes sorting
hdr.SortBeg = fread(fid, 1, 'int32' ); % beginning of the sorting window to use in template sorting (width defined by SortWidth)
hdr.Comment = fread(fid, [1 128], 'uint8=>char' );
hdr.Padding = fread(fid, 11, 'int32' );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hdr = PL_EventHeader(fid)
hdr.Name = fread(fid, [1 32], 'uint8=>char' ); % name given to this event
hdr.Channel = fread(fid, 1, 'int32' ); % event number, 1-based
hdr.Comment = fread(fid, [1 128], 'uint8=>char' );
hdr.Padding = fread(fid, 33, 'int32' );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hdr = PL_SlowChannelHeader(fid)
hdr.Name = fread(fid, [1 32], 'uint8=>char' ); % name given to this channel
hdr.Channel = fread(fid, 1, 'int32' ); % channel number, 0-based
hdr.ADFreq = fread(fid, 1, 'int32' ); % digitization frequency
hdr.Gain = fread(fid, 1, 'int32' ); % gain at the adc card
hdr.Enabled = fread(fid, 1, 'int32' ); % whether this channel is enabled for taking data, 0 or 1
hdr.PreAmpGain = fread(fid, 1, 'int32' ); % gain at the preamp
% As of Version 104, this indicates the spike channel (PL_ChannelHeader.Channel) of
% a spike channel corresponding to this continuous data channel.
% <=0 means no associated spike channel.
hdr.SpikeChannel = fread(fid, 1, 'int32' );
hdr.Comment = fread(fid, [1 128], 'uint8=>char' );
hdr.Padding = fread(fid, 28, 'int32' );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function hdr = PL_DataBlockHeader(fid, offset, swapFcn)
% % this is the conventional code, it has been replaced by code that works
% % with both regular and memmapped files
% hdr.Type = fread(fid, 1, 'int16=>int16' ); % Data type; 1=spike, 4=Event, 5=continuous
% hdr.UpperByteOf5ByteTimestamp = fread(fid, 1, 'uint16=>uint16' ); % Upper 8 bits of the 40 bit timestamp
% hdr.TimeStamp = fread(fid, 1, 'uint32=>uint32' ); % Lower 32 bits of the 40 bit timestamp
% hdr.Channel = fread(fid, 1, 'int16=>int16' ); % Channel number
% hdr.Unit = fread(fid, 1, 'int16=>int16' ); % Sorted unit number; 0=unsorted
% hdr.NumberOfWaveforms = fread(fid, 1, 'int16=>int16' ); % Number of waveforms in the data to folow, usually 0 or 1
% hdr.NumberOfWordsInWaveform = fread(fid, 1, 'int16=>int16' ); % Number of samples per waveform in the data to follow
if isa(fid, 'memmapfile')
mm = fid;
datbeg = offset/2 + 1; % the offset is in bytes (minus the file header), the memory mapped file is indexed in int16 words
datend = offset/2 + 8;
buf = mm.Data(datbeg:datend);
else
buf = fread(fid, 8, 'int16=>int16');
end
hdr.Type = swapFcn(buf(1));
hdr.UpperByteOf5ByteTimestamp = swapFcn(uint16(buf(2)));
hdr.TimeStamp = swapFcn(typecast(buf([3 4]), 'uint32'));
hdr.Channel = swapFcn(buf(5));
hdr.Unit = swapFcn(buf(6));
hdr.NumberOfWaveforms = swapFcn(buf(7));
hdr.NumberOfWordsInWaveform = swapFcn(buf(8));
|
github
|
lcnhappe/happe-master
|
read_neurosim_evolution.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_neurosim_evolution.m
| 4,493 |
utf_8
|
611253a932a6acc90c0b61a442dc58a5
|
function [hdr, dat] = read_neurosim_evolution(filename, varargin)
% READ_NEUROSIM_EVOLUTION reads the "evolution" file that is written
% by Jan van der Eerden's NeuroSim software. When a directory is used
% as input, the default filename 'evolution' is read.
%
% Use as
% [hdr, dat] = read_neurosim_evolution(filename, ...)
% where additional options should come in key-value pairs and can include
% Vonly = 0 or 1, only give the membrane potentials as output
% headerOnly = 0 or 1, only read the header information (skip the data), automatically set to 1 if nargout==1
%
% See also FT_READ_HEADER, FT_READ_DATA
% Copyright (C) 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$
if isdir(filename)
filename = fullfile(filename, 'evolution');
end
Vonly = ft_getopt(varargin, 'Vonly',0);
headerOnly = ft_getopt(varargin, 'headerOnly',0);
if nargout<2 % make sure that when only one output is requested the header is returned
headerOnly=true;
end
label = {};
orig = {};
fid = fopen(filename, 'rb');
% read the header
line = '#';
ishdr=1;
while ishdr==1
% find temporal information
if strfind(lower(line),'start time')
dum= regexp(line, 'time\s+(\d+.\d+E[+-]\d+)', 'tokens');
hdr.FirstTimeStamp = str2double(dum{1}{1});
end
if strfind(lower(line),'time bin')
dum= regexp(line, 'bin\s+(\d+.\d+E[+-]\d+)', 'tokens');
dt=str2double(dum{1}{1});
hdr.Fs= 1e3/dt;
hdr.TimeStampPerSample=dt;
end
if strfind(lower(line),'end time')
dum= regexp(line, 'time\s+(\d+.\d+E[+-]\d+)', 'tokens');
hdr.LastTimeStamp = str2double(dum{1}{1});
hdr.nSamples=int64((hdr.LastTimeStamp-hdr.FirstTimeStamp)/dt+1);
end
% parse the content of the line, determine the label for each column
colid = sscanf(line, '# column %d:', 1);
if ~isempty(colid)
label{colid} = [num2str(colid) rmspace(line(find(line==':'):end))];
end
offset = ftell(fid); % remember the file pointer position
line = fgetl(fid); % get the next line
if ~isempty(line) && line(1)~='#' && ~isempty(str2num(line))
% the data starts here, rewind the last line
fseek(fid, offset, 'bof');
line = [];
ishdr=0;
else
orig{end+1} = line;
end
end
timelab=find(~cellfun('isempty',regexp(lower(label), 'time', 'match')));
if ~headerOnly
% read the complete data
dat = fscanf(fid, '%f', [length(label), inf]);
hdr.nSamples = length(dat(timelab, :)); %overwrites the value written in the header with the actual number of samples found
hdr.LastTimeStamp = dat(1,end);
end
fclose(fid);
% only extract V_membrane if wanted
if Vonly
matchLab=regexp(label,'V of (\S+) neuron','start');
idx=find(~cellfun(@isempty,matchLab));
if isempty(idx) % most likely a multi compartment simulation
matchLab=regexp(label,'V\S+ of (\S+) neuron','start');
idx=find(~cellfun(@isempty,matchLab));
end
if ~headerOnly
dat=dat([timelab idx],:);
end
label=label([timelab idx]);
for n=2:length(label) % renumbering of the labels
label{n}=[num2str(n) label{n}(regexp(label{n},': V'):end)];
end
end
% convert the header into FieldTrip style
hdr.label = label(:);
hdr.nChans = length(label);
hdr.nSamplesPre = 0;
hdr.nTrials = 1;
% also store the original ascii header details
hdr.orig = orig(:);
[hdr.chanunit hdr.chantype] = deal(cell(length(label),1));
hdr.chantype(:) = {'evolution (neurosim)'};
hdr.chanunit(:) = {'unknown'};
function y=rmspace(x)
% remove double spaces from string
% (c) Bart Gips 2012
y=strtrim(x);
[sbeg send]=regexp(y,' \s+');
for n=1:length(sbeg)
y(sbeg(n):send(n)-1)=[];
end
|
github
|
lcnhappe/happe-master
|
read_eeglabevent.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_eeglabevent.m
| 3,698 |
utf_8
|
d48c0efc8368b120e96562164a153a88
|
% read_eeglabevent() - import EEGLAB dataset events
%
% Usage:
% >> event = read_eeglabevent(filename, ...);
%
% Inputs:
% filename - [string] file name
%
% Optional inputs:
% 'header' - FILEIO structure header
%
% Outputs:
% event - FILEIO toolbox event structure
%
% Author: Arnaud Delorme, SCCN, INC, UCSD, 2008-
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
function event = read_eeglabevent(filename, varargin)
if nargin < 1
help read_eeglabheader;
return;
end;
hdr = ft_getopt(varargin, 'header');
if isempty(hdr)
hdr = read_eeglabheader(filename);
end
event = []; % these will be the output in FieldTrip format
oldevent = hdr.orig.event; % these are in EEGLAB format
if ~isempty(oldevent)
nameList=fieldnames(oldevent);
else
nameList=[];
end;
nameList=setdiff(nameList,{'type','value','sample','offset','duration','latency'});
for index = 1:length(oldevent)
if isfield(oldevent,'code')
type = oldevent(index).code;
elseif isfield(oldevent,'value')
type = oldevent(index).value;
else
type = 'trigger';
end;
% events can have a numeric or a string value
if isfield(oldevent,'type')
value = oldevent(index).type;
else
value = 'default';
end;
% this is the sample number of the concatenated data to which the event corresponds
sample = oldevent(index).latency;
% a non-zero offset only applies to trial-events, i.e. in case the data is
% segmented and each data segment needs to be represented as event. In
% that case the offset corresponds to the baseline duration (times -1).
offset = 0;
if isfield(oldevent, 'duration')
duration = oldevent(index).duration;
else
duration = 0;
end;
% add the current event in FieldTrip format
event(index).type = type; % this is usually a string, e.g. 'trigger' or 'trial'
event(index).value = value; % in case of a trigger, this is the value
event(index).sample = sample; % this is the sample in the datafile at which the event happens
event(index).offset = offset; % some events should be represented with a shifted time-axix, e.g. a trial with a baseline period
event(index).duration = duration; % some events have a duration, such as a trial
%add custom fields
for iField=1:length(nameList)
eval(['event(index).' nameList{iField} '=oldevent(index).' nameList{iField} ';']);
end;
end;
if hdr.nTrials>1
% add the trials to the event structure
for i=1:hdr.nTrials
event(end+1).type = 'trial';
event(end ).sample = (i-1)*hdr.nSamples + 1;
if isfield(oldevent,'setname') && (length(oldevent) == hdr.nTrials)
event(end ).value = oldevent(i).setname; %accommodate Widmann's pop_grandaverage function
else
event(end ).value = [];
end;
event(end ).offset = -hdr.nSamplesPre;
event(end ).duration = hdr.nSamples;
end
end
|
github
|
lcnhappe/happe-master
|
read_bti_ascii.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/read_bti_ascii.m
| 2,240 |
utf_8
|
560f3413b1fc96661f8ed42823efdc13
|
function [file] = read_bti_ascii(filename)
% READ_BTI_ASCII reads general data from a BTI configuration file
%
% The file should be formatted like
% Group:
% item1 : value1a value1b value1c
% item2 : value2a value2b value2c
% item3 : value3a value3b value3c
% item4 : value4a value4b value4c
%
% Copyright (C) 2004, 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');
if fid==-1
error(sprintf('could not open file %s', filename));
end
line = '';
while ischar(line)
line = cleanline(fgetl(fid))
if isempty(line) | line==-1 | isempty(findstr(line, ':'))
continue
end
% the line is not empty, which means that we have encountered a chunck of information
if findstr(line, ':')~=length(line)
[item, value] = strtok(line, ':');
value(1) = ' '; % remove the :
value = strtrim(value);
item = strtrim(item);
item(findstr(item, '.')) = '_';
item(findstr(item, ' ')) = '_';
if ischar(item)
eval(sprintf('file.%s = ''%s'';', item, value));
else
eval(sprintf('file.%s = %s;', item, value));
end
else
subline = cleanline(fgetl(fid));
error, the rest has not been implemented (yet)
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function line = cleanline(line)
if isempty(line) | line==-1
return
end
comment = findstr(line, '//');
if ~isempty(comment)
line(min(comment):end) = ' ';
end
line = strtrim(line);
|
github
|
lcnhappe/happe-master
|
openbdf.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/fileio/private/openbdf.m
| 6,812 |
utf_8
|
cb49358a2a955b165a5c50127c25e3d8
|
% openbdf() - Opens an BDF File (European Data Format for Biosignals) in MATLAB (R)
%
% Usage:
% >> EDF=openedf(FILENAME)
%
% Note: About EDF -> www.biosemi.com/faq/file_format.htm
%
% Author: Alois Schloegl, 5.Nov.1998
%
% See also: readedf()
% Copyright (C) 1997-1998 by Alois Schloegl
% [email protected]
% Ver 2.20 18.Aug.1998
% Ver 2.21 10.Oct.1998
% Ver 2.30 5.Nov.1998
%
% For use under Octave define the following function
% function s=upper(s); s=toupper(s); end;
% V2.12 Warning for missing Header information
% V2.20 EDF.AS.* changed
% V2.30 EDF.T0 made Y2K compatible until Year 2090
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
% Name changed for bdf files Sept 6,2002 T.S. Lorig
% Header updated for EEGLAB format (update web link too) - Arnaud Delorme 14 Oct 2002
function [DAT,H1]=openbdf(FILENAME)
SLASH='/'; % defines Seperator for Subdirectories
BSLASH=char(92);
cname=computer;
if cname(1:2)=='PC' SLASH=BSLASH; end;
fid=fopen(FILENAME,'r','ieee-le');
if fid<0
fprintf(2,['Error LOADEDF: File ' FILENAME ' not found\n']);
return;
end;
EDF.FILE.FID=fid;
EDF.FILE.OPEN = 1;
EDF.FileName = FILENAME;
PPos=min([max(find(FILENAME=='.')) length(FILENAME)+1]);
SPos=max([0 find((FILENAME=='/') | (FILENAME==BSLASH))]);
EDF.FILE.Ext = FILENAME(PPos+1:length(FILENAME));
EDF.FILE.Name = FILENAME(SPos+1:PPos-1);
if SPos==0
EDF.FILE.Path = pwd;
else
EDF.FILE.Path = FILENAME(1:SPos-1);
end;
EDF.FileName = [EDF.FILE.Path SLASH EDF.FILE.Name '.' EDF.FILE.Ext];
H1=char(fread(EDF.FILE.FID,256,'char')'); %
EDF.VERSION=H1(1:8); % 8 Byte Versionsnummer
%if 0 fprintf(2,'LOADEDF: WARNING Version EDF Format %i',ver); end;
EDF.PID = deblank(H1(9:88)); % 80 Byte local patient identification
EDF.RID = deblank(H1(89:168)); % 80 Byte local recording identification
%EDF.H.StartDate = H1(169:176); % 8 Byte
%EDF.H.StartTime = H1(177:184); % 8 Byte
EDF.T0=[str2num(H1(168+[7 8])) str2num(H1(168+[4 5])) str2num(H1(168+[1 2])) str2num(H1(168+[9 10])) str2num(H1(168+[12 13])) str2num(H1(168+[15 16])) ];
% Y2K compatibility until year 2090
if EDF.VERSION(1)=='0'
if EDF.T0(1) < 91
EDF.T0(1)=2000+EDF.T0(1);
else
EDF.T0(1)=1900+EDF.T0(1);
end;
else ;
% in a future version, this is hopefully not needed
end;
EDF.HeadLen = str2num(H1(185:192)); % 8 Byte Length of Header
% reserved = H1(193:236); % 44 Byte
EDF.NRec = str2num(H1(237:244)); % 8 Byte # of data records
EDF.Dur = str2num(H1(245:252)); % 8 Byte # duration of data record in sec
EDF.NS = str2num(H1(253:256)); % 8 Byte # of signals
EDF.Label = char(fread(EDF.FILE.FID,[16,EDF.NS],'char')');
EDF.Transducer = char(fread(EDF.FILE.FID,[80,EDF.NS],'char')');
EDF.PhysDim = char(fread(EDF.FILE.FID,[8,EDF.NS],'char')');
EDF.PhysMin= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'));
EDF.PhysMax= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'));
EDF.DigMin = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); %
EDF.DigMax = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); %
% check validity of DigMin and DigMax
if (length(EDF.DigMin) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Digital Minimum\n');
EDF.DigMin = -(2^15)*ones(EDF.NS,1);
end
if (length(EDF.DigMax) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Digital Maximum\n');
EDF.DigMax = (2^15-1)*ones(EDF.NS,1);
end
if (any(EDF.DigMin >= EDF.DigMax))
fprintf(2,'Warning OPENEDF: Digital Minimum larger than Maximum\n');
end
% check validity of PhysMin and PhysMax
if (length(EDF.PhysMin) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Physical Minimum\n');
EDF.PhysMin = EDF.DigMin;
end
if (length(EDF.PhysMax) ~= EDF.NS)
fprintf(2,'Warning OPENEDF: Failing Physical Maximum\n');
EDF.PhysMax = EDF.DigMax;
end
if (any(EDF.PhysMin >= EDF.PhysMax))
fprintf(2,'Warning OPENEDF: Physical Minimum larger than Maximum\n');
EDF.PhysMin = EDF.DigMin;
EDF.PhysMax = EDF.DigMax;
end
EDF.PreFilt= char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); %
tmp = fread(EDF.FILE.FID,[8,EDF.NS],'char')'; % samples per data record
EDF.SPR = str2num(char(tmp)); % samples per data record
fseek(EDF.FILE.FID,32*EDF.NS,0);
EDF.Cal = (EDF.PhysMax-EDF.PhysMin)./ ...
(EDF.DigMax-EDF.DigMin);
EDF.Off = EDF.PhysMin - EDF.Cal .* EDF.DigMin;
tmp = find(EDF.Cal < 0);
EDF.Cal(tmp) = ones(size(tmp));
EDF.Off(tmp) = zeros(size(tmp));
EDF.Calib=[EDF.Off';(diag(EDF.Cal))];
%EDF.Calib=sparse(diag([1; EDF.Cal]));
%EDF.Calib(1,2:EDF.NS+1)=EDF.Off';
EDF.SampleRate = EDF.SPR / EDF.Dur;
EDF.FILE.POS = ftell(EDF.FILE.FID);
if EDF.NRec == -1 % unknown record size, determine correct NRec
fseek(EDF.FILE.FID, 0, 'eof');
endpos = ftell(EDF.FILE.FID);
EDF.NRec = floor((endpos - EDF.FILE.POS) / (sum(EDF.SPR) * 2));
fseek(EDF.FILE.FID, EDF.FILE.POS, 'bof');
H1(237:244)=sprintf('%-8i',EDF.NRec); % write number of records
end;
EDF.Chan_Select=(EDF.SPR==max(EDF.SPR));
for k=1:EDF.NS
if EDF.Chan_Select(k)
EDF.ChanTyp(k)='N';
else
EDF.ChanTyp(k)=' ';
end;
if findstr(upper(EDF.Label(k,:)),'ECG')
EDF.ChanTyp(k)='C';
elseif findstr(upper(EDF.Label(k,:)),'EKG')
EDF.ChanTyp(k)='C';
elseif findstr(upper(EDF.Label(k,:)),'EEG')
EDF.ChanTyp(k)='E';
elseif findstr(upper(EDF.Label(k,:)),'EOG')
EDF.ChanTyp(k)='O';
elseif findstr(upper(EDF.Label(k,:)),'EMG')
EDF.ChanTyp(k)='M';
end;
end;
EDF.AS.spb = sum(EDF.SPR); % Samples per Block
bi=[0;cumsum(EDF.SPR)];
idx=[];idx2=[];
for k=1:EDF.NS,
idx2=[idx2, (k-1)*max(EDF.SPR)+(1:EDF.SPR(k))];
end;
maxspr=max(EDF.SPR);
idx3=zeros(EDF.NS*maxspr,1);
for k=1:EDF.NS, idx3(maxspr*(k-1)+(1:maxspr))=bi(k)+ceil((1:maxspr)'/maxspr*EDF.SPR(k));end;
%EDF.AS.bi=bi;
EDF.AS.IDX2=idx2;
%EDF.AS.IDX3=idx3;
DAT.Head=EDF;
DAT.MX.ReRef=1;
%DAT.MX=feval('loadxcm',EDF);
return;
|
github
|
lcnhappe/happe-master
|
ft_trialfun_general.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/trialfun/ft_trialfun_general.m
| 13,804 |
utf_8
|
24b04b8f0e079fd37494db20f8d6a99a
|
function [trl, event] = ft_trialfun_general(cfg)
% FT_TRIALFUN_GENERAL determines trials/segments in the data that are
% interesting for analysis, using the general event structure returned
% by read_event. This function is independent of the dataformat
%
% The trialdef structure can contain the following specifications
% cfg.trialdef.eventtype = 'string'
% cfg.trialdef.eventvalue = number, string or list with numbers or strings
% cfg.trialdef.prestim = latency in seconds (optional)
% cfg.trialdef.poststim = latency in seconds (optional)
%
% If you want to read all data from a continous file in segments, you can specify
% cfg.trialdef.triallength = duration in seconds (can be Inf)
% cfg.trialdef.ntrials = number of trials
%
% If you specify
% cfg.trialdef.eventtype = '?'
% a list with the events in your datafile will be displayed on screen.
%
% If you specify
% cfg.trialdef.eventtype = 'gui'
% a graphical user interface will allow you to select events of interest.
%
% See also FT_DEFINETRIAL, FT_PREPROCESSING
% 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$
% some events do not require the specification a type, pre or poststim period
% in that case it is more convenient not to have them, instead of making them empty
if ~isfield(cfg, 'trialdef')
cfg.trialdef = [];
end
if isfield(cfg.trialdef, 'eventvalue') && isempty(cfg.trialdef.eventvalue ), cfg.trialdef = rmfield(cfg.trialdef, 'eventvalue' ); end
if isfield(cfg.trialdef, 'prestim') && isempty(cfg.trialdef.prestim ), cfg.trialdef = rmfield(cfg.trialdef, 'prestim' ); end
if isfield(cfg.trialdef, 'poststim') && isempty(cfg.trialdef.poststim ), cfg.trialdef = rmfield(cfg.trialdef, 'poststim' ); end
if isfield(cfg.trialdef, 'triallength') && isempty(cfg.trialdef.triallength ), cfg.trialdef = rmfield(cfg.trialdef, 'triallength'); end
if isfield(cfg.trialdef, 'ntrials') && isempty(cfg.trialdef.ntrials ), cfg.trialdef = rmfield(cfg.trialdef, 'ntrials' ); end
if isfield(cfg.trialdef, 'triallength')
% reading all segments from a continuous file is incompatible with any other option
try, cfg.trialdef = rmfield(cfg.trialdef, 'eventvalue'); end
try, cfg.trialdef = rmfield(cfg.trialdef, 'prestim' ); end
try, cfg.trialdef = rmfield(cfg.trialdef, 'poststim' ); end
if ~isfield(cfg.trialdef, 'ntrials')
if isinf(cfg.trialdef.triallength)
cfg.trialdef.ntrials = 1;
else
cfg.trialdef.ntrials = inf;
end
end
end
% default rejection parameter
if ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end
if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end
if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end
% read the header, contains the sampling frequency
hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat);
% read the events
if isfield(cfg, 'event')
fprintf('using the events from the configuration structure\n');
event = cfg.event;
else
fprintf('reading the events from ''%s''\n', cfg.headerfile);
event = ft_read_event(cfg.headerfile, 'headerformat', cfg.headerformat, 'eventformat', cfg.eventformat, 'dataformat', cfg.dataformat);
end
% for the following, the trials do not depend on the events in the data
if isfield(cfg.trialdef, 'triallength')
if isinf(cfg.trialdef.triallength)
% make one long trial with the complete continuous data in it
trl = [1 hdr.nSamples*hdr.nTrials 0];
elseif isinf(cfg.trialdef.ntrials)
% cut the continous data into as many segments as possible
nsamples = round(cfg.trialdef.triallength*hdr.Fs);
trlbeg = 1:nsamples:(hdr.nSamples*hdr.nTrials - nsamples + 1);
trlend = trlbeg + nsamples - 1;
offset = zeros(size(trlbeg));
trl = [trlbeg(:) trlend(:) offset(:)];
else
% make the pre-specified number of trials
nsamples = round(cfg.trialdef.triallength*hdr.Fs);
trlbeg = (0:(cfg.trialdef.ntrials-1))*nsamples + 1;
trlend = trlbeg + nsamples - 1;
offset = zeros(size(trlbeg));
trl = [trlbeg(:) trlend(:) offset(:)];
end
return
end
trl = [];
val = [];
if isfield(cfg.trialdef, 'eventtype')
if strcmp(cfg.trialdef.eventtype, '?')
% no trials should be added, show event information using subfunction and exit
show_event(event);
return
elseif strcmp(cfg.trialdef.eventtype, 'gui') || (isfield(cfg.trialdef, 'eventvalue') && length(cfg.trialdef.eventvalue)==1 && strcmp(cfg.trialdef.eventvalue, 'gui'))
cfg.trialdef = select_event(event, cfg.trialdef);
usegui = 1;
else
usegui = 0;
end
else
usegui = 0;
end
% start by selecting all events
sel = true(1, length(event)); % this should be a row vector
% select all events of the specified type
if isfield(cfg.trialdef, 'eventtype') && ~isempty(cfg.trialdef.eventtype)
for i=1:numel(event)
sel(i) = sel(i) && ismatch(event(i).type, cfg.trialdef.eventtype);
end
elseif ~isfield(cfg.trialdef, 'eventtype') || isempty(cfg.trialdef.eventtype)
% search for trial events
for i=1:numel(event)
sel(i) = sel(i) && ismatch(event(i).type, 'trial');
end
end
% select all events with the specified value
if isfield(cfg.trialdef, 'eventvalue') && ~isempty(cfg.trialdef.eventvalue)
for i=1:numel(event)
sel(i) = sel(i) && ismatch(event(i).value, cfg.trialdef.eventvalue);
end
end
% convert from boolean vector into a list of indices
sel = find(sel);
if usegui
% Checks whether offset and duration are defined for all the selected
% events and/or prestim/poststim are defined in trialdef.
if (any(cellfun('isempty', {event(sel).offset})) || ...
any(cellfun('isempty', {event(sel).duration}))) && ...
~(isfield(cfg.trialdef, 'prestim') && isfield(cfg.trialdef, 'poststim'))
% If at least some of offset/duration values and prestim/poststim
% values are missing tries to ask the user for prestim/poststim
answer = inputdlg({'Prestimulus latency (sec)','Poststimulus latency (sec)'}, 'Enter borders');
if isempty(answer) || any(cellfun('isempty', answer))
error('The information in the data and cfg is insufficient to define trials.');
else
cfg.trialdef.prestim=str2double(answer{1});
cfg.trialdef.poststim=str2double(answer{2});
if isnan(cfg.trialdef.prestim) || isnan(cfg.trialdef.poststim)
error('Illegal input for trial borders');
end
end
end % if specification is not complete
end % if usegui
for i=sel
% catch empty fields in the event table and interpret them meaningfully
if isempty(event(i).offset)
% time axis has no offset relative to the event
event(i).offset = 0;
end
if isempty(event(i).duration)
% the event does not specify a duration
event(i).duration = 0;
end
% determine where the trial starts with respect to the event
if ~isfield(cfg.trialdef, 'prestim')
trloff = event(i).offset;
trlbeg = event(i).sample;
else
% override the offset of the event
trloff = round(-cfg.trialdef.prestim*hdr.Fs);
% also shift the begin sample with the specified amount
trlbeg = event(i).sample + trloff;
end
% determine the number of samples that has to be read (excluding the begin sample)
if ~isfield(cfg.trialdef, 'poststim')
trldur = max(event(i).duration - 1, 0);
else
% this will not work if prestim was not defined, the code will then crash
trldur = round((cfg.trialdef.poststim+cfg.trialdef.prestim)*hdr.Fs) - 1;
end
trlend = trlbeg + trldur;
% add the beginsample, endsample and offset of this trial to the list
% if all samples are in the dataset
if trlbeg>0 && trlend<=hdr.nSamples*hdr.nTrials,
trl = [trl; [trlbeg trlend trloff]];
if isnumeric(event(i).value),
val = [val; event(i).value];
elseif ischar(event(i).value) && numel(event(i).value)>1 && (event(i).value(1)=='S'|| event(i).value(1)=='R')
% on brainvision these are called 'S 1' for stimuli or 'R 1' for responses
val = [val; str2double(event(i).value(2:end))];
else
val = [val; nan];
end
end
end
% append the vector with values
if ~isempty(val) && ~all(isnan(val)) && size(trl,1)==size(val,1)
trl = [trl val];
end
if usegui && ~isempty(trl)
% This complicated line just computes the trigger times in seconds and
% converts them to a cell array of strings to use in the GUI
eventstrings = cellfun(@num2str, mat2cell((trl(:, 1)- trl(:, 3))./hdr.Fs , ones(1, size(trl, 1))), 'UniformOutput', 0);
% Let us start with handling at least the completely unsegmented case
% semi-automatically. The more complicated cases are better left
% to the user.
if hdr.nTrials==1
selected = find(trl(:,1)>0 & trl(:,2)<=hdr.nSamples);
else
selected = find(trl(:,1)>0);
end
indx = select_channel_list(eventstrings, selected , 'Select events');
trl=trl(indx, :);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that shows event table
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function show_event(event)
if isempty(event)
fprintf('no events were found in the datafile\n');
return
end
eventtype = unique({event.type});
Neventtype = length(eventtype);
if Neventtype==0
fprintf('no events were found in the datafile\n');
else
fprintf('the following events were found in the datafile\n');
for i=1:Neventtype
sel = find(strcmp(eventtype{i}, {event.type}));
try
eventvalue = unique({event(sel).value}); % cell-array with string value
eventvalue = sprintf('''%s'' ', eventvalue{:}); % translate into a single string
catch
eventvalue = unique(cell2mat({event(sel).value})); % array with numeric values or empty
eventvalue = num2str(eventvalue); % translate into a single string
end
fprintf('event type: ''%s'' ', eventtype{i});
fprintf('with event values: %s', eventvalue);
fprintf('\n');
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that allows the user to select an event using gui
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function trialdef = select_event(event, trialdef)
if isempty(event)
fprintf('no events were found in the datafile\n');
return
end
if strcmp(trialdef.eventtype, 'gui')
eventtype = unique({event.type});
else
eventtype ={trialdef.eventtype};
end
Neventtype = length(eventtype);
if Neventtype==0
fprintf('no events were found in the datafile\n');
else
% Two lists are built in parallel
settings={}; % The list of actual values to be used later
strsettings={}; % The list of strings to show in the GUI
for i=1:Neventtype
sel = find(strcmp(eventtype{i}, {event.type}));
emptyval = find(cellfun('isempty', {event(sel).value}));
if all(cellfun(@isnumeric, {event(sel).value}))
[event(sel(emptyval)).value]=deal(Inf);
eventvalue = unique([event(sel).value]);
else
if ~isempty(find(strcmp('Inf', {event(sel).value})))
% It's a very unlikely scenario but ...
warning('Event value''Inf'' cannot be handled by GUI selection. Mistakes are possible.')
end
[event(sel(emptyval)).value]=deal('Inf');
eventvalue = unique({event(sel).value});
if ~iscell(eventvalue)
eventvalue = {eventvalue};
end
end
for j=1:length(eventvalue)
if (isnumeric(eventvalue(j)) && eventvalue(j)~=Inf) || ...
(iscell(eventvalue(j)) && ischar(eventvalue{j}) && ~strcmp(eventvalue{j}, 'Inf'))
settings = [settings; [eventtype(i), eventvalue(j)]];
else
settings = [settings; [eventtype(i), {[]}]];
end
if isa(eventvalue, 'numeric')
strsettings = [strsettings; {['Type: ' eventtype{i} ' ; Value: ' num2str(eventvalue(j))]}];
else
strsettings = [strsettings; {['Type: ' eventtype{i} ' ; Value: ' eventvalue{j}]}];
end
end
end
if isempty(strsettings)
fprintf('no events of the selected type were found in the datafile\n');
return
end
[selection, ok] = listdlg('ListString',strsettings, 'SelectionMode', 'multiple', 'Name', 'Select event', 'ListSize', [300 300]);
if ok
trialdef.eventtype = settings(selection,1);
trialdef.eventvalue = settings(selection,2);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION returns true if x is a member of array y, regardless of the class of x and y
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function s = ismatch(x, y)
if isempty(x) || isempty(y)
s = false;
elseif ischar(x) && ischar(y)
s = strcmp(x, y);
elseif isnumeric(x) && isnumeric(y)
s = ismember(x, y);
elseif ischar(x) && iscell(y)
y = y(strcmp(class(x), cellfun(@class, y, 'UniformOutput', false)));
s = ismember(x, y);
elseif isnumeric(x) && iscell(y) && all(cellfun(@isnumeric, y))
s = false;
for i=1:numel(y)
s = s || ismember(x, y{i});
end
else
s = false;
end
|
github
|
lcnhappe/happe-master
|
ft_trialfun_realtime.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/trialfun/ft_trialfun_realtime.m
| 4,420 |
utf_8
|
d7133e3da082881a031513a257c0a2d9
|
function trl = ft_trialfun_realtime(cfg)
% FT_TRIALFUN_REALTIME can be used to segment a continuous stream of
% data in real-time. Trials are defined as [begsample endsample offset
% condition]
%
% The configuration structure can contain the following specifications
% cfg.minsample = the last sample number that was already considered (passed from rt_process)
% cfg.blocksize = in seconds. In case of events, offset is
% wrt the trigger.
% cfg.offset = the offset wrt the 0 point. In case of no events, offset is wrt
% prevSample. E.g., [-0.9 1] will read 1 second blocks with
% 0.9 second overlap
% cfg.bufferdata = {'first' 'last'}. If 'last' then only the last block of
% interest is read. Otherwise, all well-defined blocks are read (default = 'first')
% Copyright (C) 2009, Marcel van Gerven
%
% 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(cfg,'minsample'), cfg.minsample = 0; end
if ~isfield(cfg,'blocksize'), cfg.blocksize = 0.1; end
if ~isfield(cfg,'offset'), cfg.offset = 0; end
if ~isfield(cfg,'bufferdata'), cfg.bufferdata = 'first'; end
if ~isfield(cfg,'triggers'), cfg.triggers = []; end
% blocksize and offset in terms of samples
cfg.blocksize = round(cfg.blocksize * cfg.hdr.Fs);
cfg.offset = round(cfg.offset * cfg.hdr.Fs);
% retrieve trials of interest
if isempty(cfg.event) % asynchronous mode
trl = trialfun_asynchronous(cfg);
else % synchronous mode
trl = trialfun_synchronous(cfg);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function trl = trialfun_asynchronous(cfg)
trl = [];
prevSample = cfg.minsample;
if strcmp(cfg.bufferdata, 'last') % only get last block
% begsample starts blocksize samples before the end
begsample = cfg.hdr.nSamples*cfg.hdr.nTrials - cfg.blocksize;
% begsample should be offset samples away from the previous read
if begsample >= (prevSample + cfg.offset)
endsample = cfg.hdr.nSamples*cfg.hdr.nTrials;
if begsample < endsample && begsample > 0
trl = [begsample endsample 0 nan];
end
end
else % get all blocks
while true
% see whether new samples are available
newsamples = (cfg.hdr.nSamples*cfg.hdr.nTrials-prevSample);
% if newsamples exceeds the offset plus length specified in blocksize
if newsamples >= (cfg.offset+cfg.blocksize)
% we do not consider samples < 1
begsample = max(1,prevSample+cfg.offset);
endsample = max(1,prevSample+cfg.offset+cfg.blocksize);
if begsample < endsample && endsample <= cfg.hdr.nSamples*cfg.hdr.nTrials
trl = [trl; [begsample endsample 0 nan]];
end
prevSample = endsample;
else
break;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function trl = trialfun_synchronous(cfg)
trl = [];
% process all events
for j=1:length(cfg.event)
if isempty(cfg.triggers)
curtrig = cfg.event(j).value;
else
[m1,curtrig] = ismember(cfg.event(j).value,cfg.triggers);
end
if isempty(curtrig), curtrig = nan; end
if isempty(cfg.triggers) || (~isempty(m1) && m1)
% catched a trigger of interest
% we do not consider samples < 1
begsample = max(1,cfg.event(j).sample + cfg.offset);
endsample = max(1,begsample + cfg.blocksize);
trl = [trl; [begsample endsample cfg.offset curtrig]];
end
end
|
github
|
lcnhappe/happe-master
|
select_channel_list.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/trialfun/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
|
lcnhappe/happe-master
|
ft_headmodel_fns.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/ft_headmodel_fns.m
| 5,517 |
utf_8
|
f2babb12e0dbf26d42ff2aa1a9791792
|
function headmodel = ft_headmodel_fns(seg, varargin)
% FT_HEADMODEL_FNS creates the volume conduction structure to be used
% in the FNS forward solver.
%
% Use as
% headmodel = ft_headmodel_fns(seg, ...)
%
% Optional input arguments should be specified in key-value pairs and
% can include
% tissuecond = matrix C [9XN tissue types]; where N is the number of
% tissues and a 3x3 tensor conductivity matrix is stored
% in each column.
% tissue = see fns_contable_write
% tissueval = match tissues of segmentation input
% transform = 4x4 transformation matrix (default eye(4))
% sens = sensor information (for which ft_datatype(sens,'sens')==1)
% deepelec = used in the case of deep voxel solution
% tolerance = scalar (default 1e-8)
%
% Standard default values for conductivity matrix C are derived from
% Saleheen HI, Ng KT. New finite difference formulations for general
% inhomogeneous anisotropic bioelectric problems. IEEE Trans Biomed Eng.
% 1997
%
% Additional documentation available at:
% http://hunghienvn.nmsu.edu/wiki/index.php/FNS
%
% See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD
% Copyright (C) 2011, Cristiano Micheli and Hung Dang
%
% 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$
ft_hastoolbox('fns', 1);
% get the optional arguments
tissue = ft_getopt(varargin, 'tissue', []);
tissueval = ft_getopt(varargin, 'tissueval', []);
tissuecond = ft_getopt(varargin, 'tissuecond', []);
transform = ft_getopt(varargin, 'transform', eye(4));
unit = ft_getopt(varargin, 'unit', 'mm');
sens = ft_getopt(varargin, 'sens', []);
deepelec = ft_getopt(varargin, 'deepelec', []); % used in the case of deep voxel solution
tolerance = ft_getopt(varargin, 'tolerance', 1e-8);
if isempty(sens)
error('A set of sensors is required')
end
if ispc
error('FNS only works on Linux and OS X')
end
% check the consistency between tissue values and the segmentation
vecval = ismember(tissueval,unique(seg(:)));
if any(vecval)==0
warning('Some of the tissue values are not in the segmentation')
end
% create the files to be written
try
tmpfolder = pwd;
cd(tempdir)
[tmp,tname] = fileparts(tempname);
segfile = [tname];
[tmp,tname] = fileparts(tempname);
confile = [tname '.csv'];
[tmp,tname] = fileparts(tempname);
elecfile = [tname '.h5'];
[tmp,tname] = fileparts(tempname);
exefile = [tname '.sh'];
[tmp,tname] = fileparts(tempname);
datafile = [tname '.h5'];
% this requires the fieldtrip/fileio toolbox
ft_hastoolbox('fileio', 1);
% create a fake mri structure and write the segmentation on disk
disp('writing the segmentation file...')
mri = [];
mri.dim = size(seg);
mri.transform = eye(4);
mri.seg = uint8(seg);
cfg = [];
cfg.datatype = 'uint8';
cfg.coordsys = 'ctf';
cfg.parameter = 'seg';
cfg.filename = segfile;
cfg.filetype = 'analyze';
ft_volumewrite(cfg, mri);
% write the cond matrix on disk, load the default cond matrix in case not specified
disp('writing the conductivity file...')
condmatrix = fns_contable_write('tissue',tissue,'tissueval',tissueval,'tissuecond',tissuecond);
csvwrite(confile,condmatrix);
% write the positions of the electrodes on disk
disp('writing the electrodes file...')
pos = ft_warp_apply(inv(transform),sens.elecpos); % in voxel coordinates!
% convert pos into int32 datatype.
hdf5write(elecfile, '/electrodes/gridlocs', int32(pos));
% Exe file
efid = fopen(exefile, 'w');
if ~ispc
fprintf(efid,'#!/usr/bin/env bash\n');
fprintf(efid,['elecsfwd1 -img ' segfile ' -electrodes ./' elecfile ' -data ./', ...
datafile ' -contable ./' confile ' -TOL ' num2str(tolerance) ' \n']);%2>&1 > /dev/null
end
fclose(efid);
% run the shell instructions
dos(sprintf('chmod +x %s', exefile));
dos(['./' exefile]);
% FIXME: find a cleverer way to store the huge transfer matrix (vista?)
[transfer,status] = fns_read_transfer(datafile);
cleaner(segfile,confile,elecfile,exefile,datafile)
catch ME
disp('The transfer matrix was not written')
cleaner(segfile,confile,elecfile,exefile,datafile)
cd(tmpfolder)
rethrow(ME)
end
% start with an empty volume conductor
headmodel = [];
headmodel.tissue = tissue;
headmodel.tissueval = tissueval;
headmodel.transform = transform;
headmodel.unit = unit;
headmodel.segdim = size(seg);
headmodel.type = 'fns';
headmodel.transfer = transfer;
if ~isempty(deepelec)
headmodel.deepelec = deepelec;
end
function cleaner(segfile,confile,elecfile,exefile,datafile)
delete([segfile '.hdr']);
delete([segfile '.img']);
delete(confile);
delete(elecfile);
delete(exefile);
delete(datafile);
|
github
|
lcnhappe/happe-master
|
ft_convert_units.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/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
|
lcnhappe/happe-master
|
ft_apply_montage.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/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
|
lcnhappe/happe-master
|
ft_headmodel_slab.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/ft_headmodel_slab.m
| 3,563 |
utf_8
|
a25dc7acd56e431b9a85280512392362
|
function headmodel = ft_headmodel_slab(mesh1, mesh2, Pc, varargin)
% FT_HEADMODEL_SLAB creates an EEG volume conduction model that
% is described with an infinite conductive slab. You can think
% of this as two parallel planes containing a mass of conductive
% material (e.g. water) and externally to them a non-conductive material
% (e.g. air).
%
% Use as
% headmodel = ft_headmodel_slab(mesh1, mesh2, Pc, varargin)
% where
% mesh1.pos = Nx3 vector specifying N points through which the 'upper' plane is fitted
% mesh2.pos = Nx3 vector specifying N points through which the 'lower' plane is fitted
% Pc = 1x3 vector specifying the spatial position of a point lying in the conductive slab
% (this determines the plane's normal's direction)
%
% Optional arguments should be specified in key-value pairs and can include
% 'sourcemodel' = 'monopole'
% 'conductivity' = number , conductivity value of the conductive halfspace (default = 1)
%
% See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD
% Copyright (C) 2012, Donders Centre for Cognitive Neuroimaging, Nijmegen, NL
%
% 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$
model = ft_getopt(varargin, 'sourcemodel', 'monopole');
cond = ft_getopt(varargin, 'conductivity');
if isempty(cond)
warning('Conductivity was not specified, using 1');
cond = 1;
end
% the description of this volume conduction model consists of the
% description of the plane, and a point in the void halfspace
% replace pnt with pos
mesh1 = fixpos(mesh1);
mesh2 = fixpos(mesh2);
if isstruct(mesh1) && isfield(mesh1,'pos')
pos1 = mesh1.pos;
pos2 = mesh2.pos;
elseif size(mesh1,2)==3
pos1 = mesh1;
pos2 = mesh2;
else
error('incorrect specification of the geometry');
end
% fit a plane to the points
[N1,P1] = fit_plane(pos1);
[N2,P2] = fit_plane(pos2);
% checks if Pc is in the conductive part. If not, flip
incond = acos(dot(N1,(Pc-P1)./norm(Pc-P1))) > pi/2;
if ~incond
N1 = -N1;
end
incond = acos(dot(N2,(Pc-P2)./norm(Pc-P2))) > pi/2;
if ~incond
N2 = -N2;
end
headmodel = [];
headmodel.cond = cond;
headmodel.pos1 = P1(:)'; % a point that lies on the plane that separates the conductive tissue from the air
headmodel.ori1 = N1(:)'; % a unit vector pointing towards the air
headmodel.ori1 = headmodel.ori1/norm(headmodel.ori1);
headmodel.pos2 = P2(:)';
headmodel.ori2 = N2(:)';
headmodel.ori2 = headmodel.ori2/norm(headmodel.ori2);
if strcmpi(model,'monopole')
headmodel.type = 'slab_monopole';
else
error('unknow method')
end
function [N,P] = fit_plane(X)
% Fits a plane through a number of points in 3D cartesian coordinates
P = mean(X,1); % the plane is spanned by this point and by a normal vector
X = bsxfun(@minus,X,P);
[u, s, v] = svd(X, 0);
N = v(:,3); % orientation of the plane, can be in either direction
|
github
|
lcnhappe/happe-master
|
ft_prepare_vol_sens.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/ft_prepare_vol_sens.m
| 26,259 |
utf_8
|
225596851f014058749908d3367e615b
|
function [headmodel, sens] = ft_prepare_vol_sens(headmodel, sens, varargin)
% FT_PREPARE_VOL_SENS does some bookkeeping to ensure that the volume
% conductor model and the sensor array are ready for subsequent forward
% leadfield computations. It takes care of some pre-computations that can
% be done efficiently prior to the leadfield calculations.
%
% Use as
% [headmodel, sens] = ft_prepare_vol_sens(headmodel, sens, ...)
% with input arguments
% headmodel structure with volume conductor definition
% sens structure with gradiometer or electrode definition
%
% The headmodel structure represents a volume conductor model of the head,
% its contents depend on the type of model. The sens structure represents a
% sensor array, i.e. EEG electrodes or MEG gradiometers.
%
% Additional options should be specified in key-value pairs and can be
% 'channel' cell-array with strings (default = 'all')
% 'order' number, for single shell "Nolte" model (default = 10)
%
% The detailed behaviour of this function depends on whether the input
% consists of EEG or MEG and furthermoree depends on the type of volume
% conductor model:
% - in case of EEG single and concentric sphere models, the electrodes are
% projected onto the skin surface.
% - in case of EEG boundary element models, the electrodes are projected on
% the surface and a blilinear interpoaltion matrix from vertices to
% electrodes is computed.
% - in case of MEG and a localspheres model, a local sphere is determined
% for each coil in the gradiometer definition.
% - in case of MEG with a singleshell Nolte model, the volume conduction
% model is initialized
% In any case channel selection and reordering will be done. The channel
% order returned by this function corresponds to the order in the 'channel'
% option, or if not specified, to the order in the input sensor array.
%
% See also FT_COMPUTE_LEADFIELD, FT_READ_VOL, FT_READ_SENS, FT_TRANSFORM_VOL,
% FT_TRANSFORM_SENS
% Copyright (C) 2004-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 iscell(headmodel) && iscell(sens)
% this represents combined EEG, ECoG and/or MEG
for i=1:numel(headmodel)
[headmodel{i}, sens{i}] = ft_prepare_vol_sens(headmodel{i}, sens{i}, varargin{:});
end
return
end
% get the optional input arguments
% fileformat = ft_getopt(varargin, 'fileformat');
channel = ft_getopt(varargin, 'channel', sens.label); % cell-array with channel labels, default is all
order = ft_getopt(varargin, 'order', 10); % order of expansion for Nolte method; 10 should be enough for real applications; in simulations it makes sense to go higher
% ensure that the sensor description is up-to-date (Aug 2011)
sens = ft_datatype_sens(sens);
% this is to support volumes saved in mat-files, particularly interpolated
if ischar(headmodel)
vpath = fileparts(headmodel); % remember the path to the file
headmodel = ft_read_vol(headmodel); % replace the filename with the content of the file
end
% ensure that the volume conduction description is up-to-date (Jul 2012)
headmodel = ft_datatype_headmodel(headmodel);
% determine whether the input contains EEG or MEG sensors
iseeg = ft_senstype(sens, 'eeg');
ismeg = ft_senstype(sens, 'meg');
% determine the skin compartment
if ~isfield(headmodel, 'skin_surface')
if isfield(headmodel, 'bnd')
headmodel.skin_surface = find_outermost_boundary(headmodel.bnd);
elseif isfield(headmodel, 'r') && length(headmodel.r)<=4
[dum, headmodel.skin_surface] = max(headmodel.r);
end
end
% determine the inner_skull_surface compartment
if ~isfield(headmodel, 'inner_skull_surface')
if isfield(headmodel, 'bnd')
headmodel.inner_skull_surface = find_innermost_boundary(headmodel.bnd);
elseif isfield(headmodel, 'r') && length(headmodel.r)<=4
[dum, headmodel.inner_skull_surface] = min(headmodel.r);
end
end
% otherwise the voltype assignment to an empty struct below won't work
if isempty(headmodel)
headmodel = [];
end
% this makes them easier to recognise
sens.type = ft_senstype(sens);
headmodel.type = ft_voltype(headmodel);
if isfield(headmodel, 'unit') && isfield(sens, 'unit') && ~strcmp(headmodel.unit, sens.unit)
error('inconsistency in the units of the volume conductor and the sensor array');
end
if ismeg && iseeg
% this is something that could be implemented relatively easily
error('simultaneous EEG and MEG not yet supported');
elseif ~ismeg && ~iseeg
error('the input does not look like EEG, nor like MEG');
elseif ismeg
% always ensure that there is a linear transfer matrix for combining the coils into gradiometers
if ~isfield(sens, 'tra');
Nchans = length(sens.label);
Ncoils = size(sens.coilpos,1);
if Nchans~=Ncoils
error('inconsistent number of channels and coils');
end
sens.tra = eye(Nchans, Ncoils);
end
if ~ft_voltype(headmodel, 'localspheres')
% select the desired channels from the gradiometer array
[selchan, selsens] = match_str(channel, sens.label);
% only keep the desired channels, order them according to the users specification
try, sens.chantype = sens.chantype(selsens,:); end
try, sens.chanunit = sens.chanunit(selsens,:); end
try, sens.chanpos = sens.chanpos (selsens,:); end
try, sens.chanori = sens.chanori (selsens,:); end
sens.label = sens.label(selsens);
sens.tra = sens.tra(selsens,:);
else
% for the localspheres model it is done further down
end
% remove the coils that do not contribute to any channel output
selcoil = any(sens.tra~=0,1);
sens.coilpos = sens.coilpos(selcoil,:);
sens.coilori = sens.coilori(selcoil,:);
sens.tra = sens.tra(:,selcoil);
switch ft_voltype(headmodel)
case {'infinite' 'infinite_monopole' 'infinite_currentdipole' 'infinite_magneticdipole'}
% nothing to do
case 'singlesphere'
% nothing to do
case 'concentricspheres'
% nothing to do
case 'neuromag'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% if the forward model is computed using the external Neuromag toolbox,
% we have to add a selection of the channels so that the channels
% in the forward model correspond with those in the data.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[selchan, selsens] = match_str(channel, sens.label);
headmodel.chansel = selsens;
case 'localspheres'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% If the volume conduction model consists of multiple spheres then we
% have to match the channels in the gradiometer array and the volume
% conduction model.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the initial localspheres volume conductor has a local sphere per
% channel, whereas it should have a local sphere for each coil
if size(headmodel.r,1)==size(sens.coilpos,1) && ~isfield(headmodel, 'label')
% it appears that each coil already has a sphere, which suggests
% that the volume conductor already has been prepared to match the
% sensor array
return
elseif size(headmodel.r,1)==size(sens.coilpos,1) && isfield(headmodel, 'label')
if ~isequal(headmodel.label(:), sens.label(:))
% if only the order is different, it would be possible to reorder them
error('the coils in the volume conduction model do not correspond to the sensor array');
else
% the coil-specific spheres in the volume conductor should not have a label
% because the label is already specified for the coils in the
% sensor array
headmodel = rmfield(headmodel, 'label');
end
return
end
% the CTF way of representing the headmodel is one-sphere-per-channel
% whereas the FieldTrip way of doing the forward computation is one-sphere-per-coil
Nchans = size(sens.tra,1);
Ncoils = size(sens.tra,2);
Nspheres = size(headmodel.label);
if isfield(headmodel, 'orig')
% these are present in a CTF *.hdm file
singlesphere.o(1,1) = headmodel.orig.MEG_Sphere.ORIGIN_X;
singlesphere.o(1,2) = headmodel.orig.MEG_Sphere.ORIGIN_Y;
singlesphere.o(1,3) = headmodel.orig.MEG_Sphere.ORIGIN_Z;
singlesphere.r = headmodel.orig.MEG_Sphere.RADIUS;
% ensure consistent units
singlesphere = ft_convert_units(singlesphere, headmodel.unit);
% determine the channels that do not have a corresponding sphere
% and use the globally fitted single sphere for those
missing = setdiff(sens.label, headmodel.label);
if ~isempty(missing)
warning('using the global fitted single sphere for %d channels that do not have a local sphere', length(missing));
end
for i=1:length(missing)
headmodel.label(end+1) = missing(i);
headmodel.r(end+1,:) = singlesphere.r;
headmodel.o(end+1,:) = singlesphere.o;
end
end
% make a new structure that only holds the local spheres, one per coil
localspheres = [];
localspheres.type = headmodel.type;
localspheres.unit = headmodel.unit;
% for each coil in the MEG helmet, determine the corresponding channel and from that the corresponding local sphere
for i=1:Ncoils
coilindex = find(sens.tra(:,i)~=0); % to which channel does this coil belong
if length(coilindex)>1
% this indicates that there are multiple channels to which this coil contributes,
% which happens if the sensor array represents a synthetic higher-order gradient.
[dum, coilindex] = max(abs(sens.tra(:,i)));
end
coillabel = sens.label{coilindex}; % what is the label of this channel
chanindex = find(strcmp(coillabel, headmodel.label)); % what is the index of this channel in the list of local spheres
localspheres.r(i,:) = headmodel.r(chanindex);
localspheres.o(i,:) = headmodel.o(chanindex,:);
end
headmodel = localspheres;
% finally do the selection of channels and coils
% order them according to the users specification
[selchan, selsens] = match_str(channel, sens.label);
% first only modify the linear combination of coils into channels
try, sens.chantype = sens.chantype(selsens,:); end
try, sens.chanunit = sens.chanunit(selsens,:); end
try, sens.chanpos = sens.chanpos (selsens,:); end
try, sens.chanori = sens.chanori (selsens,:); end
sens.label = sens.label(selsens);
sens.tra = sens.tra(selsens,:);
% subsequently remove the coils that do not contribute to any sensor output
selcoil = find(sum(sens.tra,1)~=0);
sens.coilpos = sens.coilpos(selcoil,:);
sens.coilori = sens.coilori(selcoil,:);
sens.tra = sens.tra(:,selcoil);
% make the same selection of coils in the localspheres model
headmodel.r = headmodel.r(selcoil);
headmodel.o = headmodel.o(selcoil,:);
case 'singleshell'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% if the forward model is computed using the code from Guido Nolte, we
% have to initialize the volume model using the gradiometer coil
% locations
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute the surface normals for each vertex point
if ~isfield(headmodel.bnd, 'nrm')
fprintf('computing surface normals\n');
headmodel.bnd.nrm = normals(headmodel.bnd.pos, headmodel.bnd.tri);
end
% estimate center and radius
[center,radius] = fitsphere(headmodel.bnd.pos);
% initialize the forward calculation (only if coils are available)
if size(sens.coilpos,1)>0 && ~isfield(headmodel, 'forwpar')
s = ft_scalingfactor(headmodel.unit, 'cm');
headmodel.forwpar = meg_ini([s*headmodel.bnd.pos headmodel.bnd.nrm], s*center', order, [s*sens.coilpos sens.coilori]);
headmodel.forwpar.scale = s;
end
case 'openmeeg'
if isfield(headmodel,'mat') & ~isempty(headmodel.mat)
warning('MEG with openmeeg only supported with NEMO lab pipeline. Please omit the mat matrix from the headmodel structure.');
end
case 'simbio'
error('MEG not yet supported with simbio');
otherwise
error('unsupported volume conductor model for MEG');
end
elseif iseeg
% the electrodes are used, the channel positions are not relevant any more
% channel positinos need to be recomputed after projecting the electrodes on the skin
if isfield(sens, 'chanpos'); sens = rmfield(sens, 'chanpos'); end
% select the desired channels from the electrode array
% order them according to the users specification
[selchan, selsens] = match_str(channel, sens.label);
Nchans = length(sens.label);
sens.label = sens.label(selsens);
try, sens.chantype = sens.chantype(selsens); end;
try, sens.chanunit = sens.chanunit(selsens); end;
if isfield(sens, 'tra')
% first only modify the linear combination of electrodes into channels
sens.tra = sens.tra(selsens,:);
% subsequently remove the electrodes that do not contribute to any channel output
selelec = any(sens.tra~=0,1);
sens.elecpos = sens.elecpos(selelec,:);
sens.tra = sens.tra(:,selelec);
else
% the electrodes and channels are identical
sens.elecpos = sens.elecpos(selsens,:);
end
switch ft_voltype(headmodel)
case {'infinite' 'infinite_monopole' 'infinite_currentdipole'}
% nothing to do
case {'halfspace', 'halfspace_monopole'}
% electrodes' all-to-all distances
numelec = size(sens.elecpos,1);
ref_el = sens.elecpos(1,:);
md = dist( (sens.elecpos-repmat(ref_el,[numelec 1]))' );
% take the min distance as reference
md = min(md(1,2:end));
pos = sens.elecpos;
% scan the electrodes and reposition the ones which are in the
% wrong halfspace (projected on the plane)... if not too far away!
for i=1:size(pos,1)
P = pos(i,:);
is_in_empty = acos(dot(headmodel.ori,(P-headmodel.pos)./norm(P-headmodel.pos))) < pi/2;
if is_in_empty
dPplane = abs(dot(headmodel.ori, headmodel.pos-P, 2));
if dPplane>md
error('Some electrodes are too distant from the plane: consider repositioning them')
else
% project point on plane
Ppr = pointproj(P,[headmodel.pos headmodel.ori]);
pos(i,:) = Ppr;
end
end
end
sens.elecpos = pos;
case {'slab_monopole'}
% electrodes' all-to-all distances
numelc = size(sens.elecpos,1);
ref_elc = sens.elecpos(1,:);
md = dist( (sens.elecpos-repmat(ref_elc,[numelc 1]))' );
% choose min distance between electrodes
md = min(md(1,2:end));
pos = sens.elecpos;
% looks for contacts outside the strip which are not too far away
% and projects them on the nearest plane
for i=1:size(pos,1)
P = pos(i,:);
instrip1 = acos(dot(headmodel.ori1,(P-headmodel.pos1)./norm(P-headmodel.pos1))) > pi/2;
instrip2 = acos(dot(headmodel.ori2,(P-headmodel.pos2)./norm(P-headmodel.pos2))) > pi/2;
is_in_empty = ~(instrip1&instrip2);
if is_in_empty
dPplane1 = abs(dot(headmodel.ori1, headmodel.pos1-P, 2));
dPplane2 = abs(dot(headmodel.ori2, headmodel.pos2-P, 2));
if dPplane1>md && dPplane2>md
error('Some electrodes are too distant from the planes: consider repositioning them')
elseif dPplane2>dPplane1
% project point on nearest plane
Ppr = pointproj(P,[headmodel.pos1 headmodel.ori1]);
pos(i,:) = Ppr;
else
% project point on nearest plane
Ppr = pointproj(P,[headmodel.pos2 headmodel.ori2]);
pos(i,:) = Ppr;
end
end
end
sens.elecpos = pos;
case {'singlesphere', 'concentricspheres'}
% ensure that the electrodes ly on the skin surface
radius = max(headmodel.r);
pos = sens.elecpos;
if isfield(headmodel, 'o')
% shift the the centre of the sphere to the origin
pos(:,1) = pos(:,1) - headmodel.o(1);
pos(:,2) = pos(:,2) - headmodel.o(2);
pos(:,3) = pos(:,3) - headmodel.o(3);
end
distance = sqrt(sum(pos.^2,2)); % to the center of the sphere
if any((abs(distance-radius)/radius)>0.005)
warning('electrodes do not lie on skin surface -> using radial projection')
end
pos = pos * radius ./ [distance distance distance];
if isfield(headmodel, 'o')
% shift the center back to the original location
pos(:,1) = pos(:,1) + headmodel.o(1);
pos(:,2) = pos(:,2) + headmodel.o(2);
pos(:,3) = pos(:,3) + headmodel.o(3);
end
sens.elecpos = pos;
case {'bem', 'dipoli', 'asa', 'bemcp', 'openmeeg'}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% do postprocessing of volume and electrodes in case of BEM model
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% project the electrodes on the skin and determine the bilinear interpolation matrix
% HACK - use NEMO lab pipeline if mat field is absent for openmeeg (i.e. don't do anything)
if ~isfield(headmodel, 'tra') && (isfield(headmodel, 'mat') && ~isempty(headmodel.mat))
% determine boundary corresponding with skin and inner_skull_surface
if ~isfield(headmodel, 'skin_surface')
headmodel.skin_surface = find_outermost_boundary(headmodel.bnd);
fprintf('determining skin compartment (%d)\n', headmodel.skin_surface);
end
if ~isfield(headmodel, 'source')
headmodel.source = find_innermost_boundary(headmodel.bnd);
fprintf('determining source compartment (%d)\n', headmodel.source);
end
if size(headmodel.mat,1)~=size(headmodel.mat,2) && size(headmodel.mat,1)==length(sens.elecpos)
fprintf('electrode transfer and system matrix were already combined\n');
else
fprintf('projecting electrodes on skin surface\n');
% compute linear interpolation from triangle vertices towards electrodes
[el, prj] = project_elec(sens.elecpos, headmodel.bnd(headmodel.skin_surface).pos, headmodel.bnd(headmodel.skin_surface).tri);
tra = transfer_elec(headmodel.bnd(headmodel.skin_surface).pos, headmodel.bnd(headmodel.skin_surface).tri, el);
% replace the original electrode positions by the projected positions
sens.elecpos = prj;
if size(headmodel.mat,1)==size(headmodel.bnd(headmodel.skin_surface).pos,1)
% construct the transfer from only the skin vertices towards electrodes
interp = tra;
else
% construct the transfer from all vertices (also inner_skull_surface/outer_skull_surface) towards electrodes
interp = [];
for i=1:length(headmodel.bnd)
if i==headmodel.skin_surface
interp = [interp, tra];
else
interp = [interp, zeros(size(el,1), size(headmodel.bnd(i).pos,1))];
end
end
end
% incorporate the linear interpolation matrix and the system matrix into one matrix
% this speeds up the subsequent repeated leadfield computations
fprintf('combining electrode transfer and system matrix\n');
if strcmp(ft_voltype(headmodel), 'openmeeg')
% check that the external toolbox is present
ft_hastoolbox('openmeeg', 1);
nb_points_external_surface = size(headmodel.bnd(headmodel.skin_surface).pos,1);
headmodel.mat = headmodel.mat((end-nb_points_external_surface+1):end,:);
headmodel.mat = interp(:,1:nb_points_external_surface) * headmodel.mat;
else
% convert to sparse matrix to speed up the subsequent multiplication
interp = sparse(interp);
headmodel.mat = interp * headmodel.mat;
% ensure that the model potential will be average referenced
avg = mean(headmodel.mat, 1);
headmodel.mat = headmodel.mat - repmat(avg, size(headmodel.mat,1), 1);
end
end
end
case 'fns'
if isfield(headmodel,'bnd')
[el, prj] = project_elec(sens.elecpos, headmodel.bnd.pos, headmodel.bnd.tri);
sens.tra = transfer_elec(headmodel.bnd.pos, headmodel.bnd.tri, el);
% replace the original electrode positions by the projected positions
sens.elecpos = prj;
end
case 'simbio'
% check that the external toolbox is present
ft_hastoolbox('simbio', 1);
% extract the outer surface
bnd = mesh2edge(headmodel);
for j=1:length(sens.label)
d = bsxfun(@minus, bnd.pos, sens.elecpos(j,:));
[d, i] = min(sum(d.^2, 2));
% replace the position of each electrode by the closest vertex
sens.elecpos(j,:) = bnd.pos(i,:);
end
headmodel.transfer = sb_transfer(headmodel,sens);
case 'interpolate'
% this is to allow moving leadfield files
if ~exist(headmodel.filename{1}, 'file')
for i = 1:length(headmodel.filename)
[p, f, x] = fileparts(headmodel.filename{i});
headmodel.filename{i} = fullfile(vpath, [f x]);
end
end
matchlab = isequal(sens.label, headmodel.sens.label);
matchpos = isequal(sens.elecpos, headmodel.sens.elecpos);
matchtra = (~isfield(sens, 'tra') && ~isfield(headmodel.sens, 'tra')) || isequal(sens.tra, headmodel.sens.tra);
if matchlab && matchpos && matchtra
% the input sensor array matches precisely with the forward model
% no further interpolation is needed
else
% interpolate the channels in the forward model to the desired channels
filename = tempname;
headmodel = ft_headmodel_interpolate(filename, sens, headmodel);
% update the sensor array with the one from the volume conductor
sens = headmodel.sens;
end % if recomputing interpolation
% for the leadfield computations the @nifti object is used to map the image data into memory
ft_hastoolbox('spm8up', 1);
for i=1:length(headmodel.sens.label)
% map each of the leadfield files into memory
headmodel.chan{i} = nifti(headmodel.filename{i});
end
otherwise
error('unsupported volume conductor model for EEG');
end
% FIXME this needs careful thought to ensure that the average referencing which is now done here and there, and that the linear interpolation in case of BEM are all dealt with consistently
% % always ensure that there is a linear transfer matrix for
% % rereferencing the EEG potential
% if ~isfield(sens, 'tra');
% sens.tra = eye(length(sens.label));
% end
% update the channel positions as the electrodes were projected to the skin surface
[pos, ori, lab] = channelposition(sens);
[selsens, selpos] = match_str(sens.label, lab);
sens.chanpos = nan(length(sens.label),3);
sens.chanpos(selsens,:) = pos(selpos,:);
end % if iseeg or ismeg
if isfield(sens, 'tra')
if issparse(sens.tra) && size(sens.tra, 1)==1
% this multiplication would result in a sparse leadfield, which is not what we want
% the effect can be demonstrated as sparse(1)*rand(1,10), see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=1169#c7
sens.tra = full(sens.tra);
elseif ~issparse(sens.tra) && size(sens.tra, 1)>1
% the multiplication of the "sensor" leadfield (electrode or coil) with the tra matrix to get the "channel" leadfield
% is faster for most cases if the pre-multiplying weighting matrix is made sparse
sens.tra = sparse(sens.tra);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Ppr = pointproj(P,plane)
% projects a point on a plane
% plane(1:3) is a point on the plane
% plane(4:6) is the ori of the plane
Ppr = [];
ori = plane(4:6);
line = [P ori];
% get indices of line and plane which are parallel
par = abs(dot(plane(4:6), line(:,4:6), 2))<1e-14;
% difference between origins of plane and line
dp = plane(1:3) - line(:, 1:3);
% Divide only for non parallel vectors (DL)
t = dot(ori(~par,:), dp(~par,:), 2)./dot(ori(~par,:), line(~par,4:6), 2);
% compute coord of intersection point
Ppr(~par, :) = line(~par,1:3) + repmat(t,1,3).*line(~par,4:6);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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
|
lcnhappe/happe-master
|
ft_headmodel_halfspace.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/ft_headmodel_halfspace.m
| 3,238 |
utf_8
|
1c182d8deabdfeefe195129d7faa2b2d
|
function headmodel = ft_headmodel_halfspace(mesh, Pc, varargin)
% FT_HEADMODEL_HALFSPACE creates an EEG volume conduction model that
% is described with an infinite conductive halfspace. You can think
% of this as a plane with on one side a infinite mass of conductive
% material (e.g. water) and on the other side non-conductive material
% (e.g. air).
%
% Use as
% headmodel = ft_headmodel_halfspace(mesh, Pc, ...)
% where
% mesh.pos = Nx3 vector specifying N points through which a plane is fitted
% Pc = 1x3 vector specifying the spatial position of a point lying in the conductive halfspace
% (this determines the plane normal's direction)
%
% Additional optional arguments should be specified as key-value pairs and can include
% 'sourcemodel' = string, 'monopole' or 'dipole' (default = 'dipole')
% 'conductivity' = number, conductivity value of the conductive halfspace (default = 1)
%
% See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD
% Copyright (C) 2012, Donders Centre for Cognitive Neuroimaging, Nijmegen, NL
%
% 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$
model = ft_getopt(varargin, 'sourcemodel', 'dipole');
cond = ft_getopt(varargin, 'conductivity');
if isempty(cond)
warning('Conductivity was not specified, using 1');
cond = 1;
end
% the description of this volume conduction model consists of the
% description of the plane, and a point in the void halfspace
if isstruct(mesh) && isfield(mesh,'pos')
pos = mesh.pos;
elseif size(mesh,2)==3
pos = mesh;
else
error('incorrect specification of the geometry');
end
% fit a plane to the points
[N,P] = fit_plane(pos);
% checks if Pc is in the conductive part. If not, flip
incond = acos(dot(N,(Pc-P)./norm(Pc-P))) > pi/2;
if ~incond
N = -N;
end
headmodel = [];
headmodel.cond = cond;
headmodel.pos = P(:)'; % a point that lies on the plane that separates the conductive tissue from the air
headmodel.ori = N(:)'; % a unit vector pointing towards the air
headmodel.ori = headmodel.ori/norm(headmodel.ori);
if strcmpi(model,'dipole')
headmodel.type = 'halfspace';
elseif strcmpi(model,'monopole')
headmodel.type = 'halfspace_monopole';
else
error('unknow method')
end
function [N,P] = fit_plane(X)
% Fits a plane through a number of points in 3D cartesian coordinates
P = mean(X,1); % the plane is spanned by this point and by a normal vector
X = bsxfun(@minus,X,P);
[u, s, v] = svd(X, 0);
N = v(:,3); % orientation of the plane, can be in either direction
|
github
|
lcnhappe/happe-master
|
ft_headmodel_dipoli.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/ft_headmodel_dipoli.m
| 7,156 |
utf_8
|
aa51271ac3c67c39dcc78a6d6937d469
|
function headmodel = ft_headmodel_dipoli(mesh, varargin)
% FT_HEADMODEL_DIPOLI creates a volume conduction model of the head
% using the boundary element method (BEM) for EEG. This function takes
% as input the triangulated surfaces that describe the boundaries and
% returns as output a volume conduction model which can be used to
% compute leadfields.
%
% This implements
% Oostendorp TF, van Oosterom A. "Source parameter estimation in
% inhomogeneous volume conductors of arbitrary shape." IEEE Trans
% Biomed Eng. 1989 Mar;36(3):382-91.
%
% The implementation of this function uses an external command-line
% executable with the name "dipoli" which is provided by Thom Oostendorp.
%
% Use as
% headmodel = ft_headmodel_dipoli(mesh, ...)
%
% The mesh is given as a boundary or a struct-array of boundaries (surfaces)
%
% Optional input arguments should be specified in key-value pairs and can
% include
% isolatedsource = string, 'yes' or 'no'
% conductivity = vector, conductivity of each compartment
%
% See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD
% $Id$
ft_hastoolbox('dipoli', 1);
% get the optional arguments
isolatedsource = ft_getopt(varargin, 'isolatedsource');
conductivity = ft_getopt(varargin, 'conductivity');
if isfield(mesh, 'bnd')
mesh = mesh.bnd;
end
% replace pnt with pos
mesh = fixpos(mesh);
% start with an empty volume conductor
headmodel = [];
headmodel.bnd = mesh;
% determine the number of compartments
numboundaries = numel(headmodel.bnd);
% % The following checks can in principle be performed, but are too
% % time-consuming. Instead the code here relies on the calling function to
% % feed in the correct geometry.
% %
% % if ~all(surface_closed(headmodel.bnd))
% % error('...');
% % end
% % if any(surface_intersection(headmodel.bnd))
% % error('...');
% % end
% % if any(surface_selfintersection(headmodel.bnd))
% % error('...');
% % end
%
% % The following checks should always be done.
% headmodel.bnd = surface_orientation(headmodel.bnd, 'outwards'); % might have to be inwards
%
% order = surface_nesting(headmodel.bnd, 'outsidefirst'); % might have to be insidefirst
% headmodel.bnd = headmodel.bnd(order);
% FIXME also the cond
%
if isempty(isolatedsource)
if numboundaries>1
% the isolated source compartment is by default the most inner one
isolatedsource = true;
else
isolatedsource = false;
end
else
% convert into a boolean
isolatedsource = istrue(isolatedsource);
end
if isolatedsource
fprintf('using isolated source approach\n');
else
fprintf('not using isolated source approach\n');
end
% determine the desired nesting of the compartments
order = surface_nesting(headmodel.bnd, 'outsidefirst');
% rearrange boundaries and conductivities
if numel(headmodel.bnd)>1
fprintf('reordering the boundaries to: ');
fprintf('%d ', order);
fprintf('\n');
% update the order of the compartments
headmodel.bnd = headmodel.bnd(order);
end
if isempty(conductivity)
warning('No conductivity is declared, Assuming standard values\n')
if numboundaries == 1
conductivity = 1;
elseif numboundaries == 3
% skin/skull/brain
conductivity = [1 1/80 1] * 0.33;
elseif numboundaries == 4
%FIXME: check for better default values here
% skin / outer skull / inner skull / brain
conductivity = [1 1/80 1 1] * 0.33;
else
error('Conductivity values are required!')
end
headmodel.cond = conductivity;
else
if numel(conductivity)~=numboundaries
error('a conductivity value should be specified for each compartment');
end
headmodel.cond = conductivity(order);
end
headmodel.skin_surface = 1;
headmodel.source = numboundaries; % this is now the last one
if isolatedsource
fprintf('using compartment %d for the isolated source approach\n', headmodel.source);
else
fprintf('not using the isolated source approach\n');
end
% find the location of the dipoli binary
str = which('dipoli.maci');
[p, f, x] = fileparts(str);
dipoli = fullfile(p, f); % without the .m extension
switch mexext
case {'mexmaci' 'mexmaci64'}
% apple computer
dipoli = [dipoli '.maci'];
case {'mexglnx86' 'mexa64'}
% linux computer
dipoli = [dipoli '.glnx86'];
otherwise
error('there is no dipoli executable for your platform');
end
fprintf('using the executable "%s"\n', dipoli);
% write the triangulations to file
prefix = tempname;
bndfile = cell(1,numboundaries);
bnddip = headmodel.bnd;
for i=1:numboundaries
bndfile{i} = sprintf('%s_%d.tri', prefix, i);
% checks if normals are inwards oriented otherwise flips them
ok = checknormals(bnddip(i));
if ~ok
fprintf('flipping normals'' direction\n')
bnddip(i).tri = fliplr(bnddip(i).tri);
end
write_tri(bndfile{i}, bnddip(i).pos, bnddip(i).tri);
end
% these will hold the shell script and the inverted system matrix
exefile = [tempname '.sh'];
amafile = [tempname '.ama'];
fid = fopen(exefile, 'w');
fprintf(fid, '#!/bin/sh\n');
fprintf(fid, '\n');
fprintf(fid, '%s -i %s << EOF\n', dipoli, amafile);
for i=1:numboundaries
if isolatedsource && headmodel.source==i
% the isolated potential approach should be applied using this compartment
fprintf(fid, '!%s\n', bndfile{i});
else
fprintf(fid, '%s\n', bndfile{i});
end
fprintf(fid, '%g\n', headmodel.cond(i));
end
fprintf(fid, '\n');
fprintf(fid, '\n');
fprintf(fid, 'EOF\n');
fclose(fid);
% ensure that the temporary shell script can be executed
dos(sprintf('chmod +x %s', exefile));
try
% execute dipoli and read the resulting file
dos(exefile);
ama = loadama(amafile);
headmodel = ama2vol(ama);
% This is to maintain the headmodel.bnd convention (outward oriented), whereas
% in terms of further calculation it shuold not really matter.
% The calculation fo the head model is done with inward normals
% (sometimes flipped from the original input). This assures that the
% outward oriented mesh is saved outward oriiented in the headmodel structure
for i=1:numel(headmodel.bnd)
isinw = checknormals(headmodel.bnd(i));
fprintf('flipping the normals outwards, after head matrix calculation\n')
if isinw
headmodel.bnd(i).tri = fliplr(headmodel.bnd(i).tri);
end
end
catch
error('an error ocurred while running the dipoli executable - please look at the screen output');
end
% delete the temporary files
for i=1:numboundaries
delete(bndfile{i})
end
delete(amafile);
delete(exefile);
% remember that it is a dipoli model
headmodel.type = 'dipoli';
function ok = checknormals(bnd)
% checks if the normals are inward oriented
ok = 0;
pos = bnd.pos;
tri = bnd.tri;
% translate to the center
org = median(pos,1);
pos(:,1) = pos(:,1) - org(1);
pos(:,2) = pos(:,2) - org(2);
pos(:,3) = pos(:,3) - org(3);
w = sum(solid_angle(pos, tri));
if w<0 && (abs(w)-4*pi)<1000*eps
% FIXME: this method is rigorous only for star shaped surfaces
warning('your normals are outwards oriented\n')
ok = 0;
elseif w>0 && (abs(w)-4*pi)<1000*eps
% warning('your normals are inwards oriented\n')
ok = 1;
else
fprintf('attention: your surface probably is irregular!')
ok = 1;
end
|
github
|
lcnhappe/happe-master
|
ft_headmodel_openmeeg.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/ft_headmodel_openmeeg.m
| 6,801 |
utf_8
|
88866540a84637e828c25e8c1d20d1ed
|
function headmodel = ft_headmodel_openmeeg(mesh, varargin)
% FT_HEADMODEL_OPENMEEG creates a volume conduction model of the
% head using the boundary element method (BEM). This function takes
% as input the triangulated surfaces that describe the boundaries and
% returns as output a volume conduction model which can be used to
% compute leadfields.
%
% This function implements
% Gramfort et al. OpenMEEG: opensource software for quasistatic
% bioelectromagnetics. Biomedical engineering online (2010) vol. 9 (1) pp. 45
% http://www.biomedical-engineering-online.com/content/9/1/45
% doi:10.1186/1475-925X-9-45
% and
% Kybic et al. Generalized head models for MEG/EEG: boundary element method
% beyond nested volumes. Phys. Med. Biol. (2006) vol. 51 pp. 1333-1346
% doi:10.1088/0031-9155/51/5/021
%
% The implementation in this function is derived from the the OpenMEEG project
% and uses external command-line executables. See http://gforge.inria.fr/projects/openmeeg
% and http://gforge.inria.fr/frs/?group_id=435.
%
% Use as
% headmodel = ft_headmodel_openmeeg(mesh, ...)
%
% Optional input arguments should be specified in key-value pairs and can
% include
% conductivity = vector, conductivity of each compartment
%
% See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD
%$Id$
ft_hastoolbox('openmeeg', 1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the first part is largely shared with the dipoli and bemcp implementation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% get the optional arguments
conductivity = ft_getopt(varargin, 'conductivity');
% copy the boundaries from the mesh into the volume conduction model
if isfield(mesh,'bnd')
mesh = mesh.bnd;
end
% start with an empty volume conductor
headmodel = [];
headmodel.bnd = mesh;
% determine the number of compartments
numboundaries = length(headmodel.bnd);
% determine the desired nesting of the compartments
order = surface_nesting(headmodel.bnd, 'outsidefirst');
% rearrange boundaries and conductivities
if numel(headmodel.bnd)>1
fprintf('reordering the boundaries to: ');
fprintf('%d ', order);
fprintf('\n');
% update the order of the compartments
headmodel.bnd = headmodel.bnd(order);
end
if isempty(conductivity)
warning('No conductivity is declared, Assuming standard values\n')
if numboundaries == 1
conductivity = 1;
elseif numboundaries == 3
% skin/skull/brain
conductivity = [1 1/80 1] * 0.33;
else
error('Conductivity values are required for 2 shells. More than 3 shells not allowed')
end
headmodel.cond = conductivity;
else
if numel(conductivity)~=numboundaries
error('a conductivity value should be specified for each compartment');
end
% update the order of the compartments
headmodel.cond = conductivity(order);
end
headmodel.skin_surface = 1;
headmodel.source = numboundaries;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this uses an implementation that was contributed by INRIA Odyssee Team
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% show the license once
% openmeeg_license
% check that the binaries are ok
om_checkombin;
% store the current path and change folder to the temporary one
tmpfolder = cd;
bndom = headmodel.bnd;
try
cd(tempdir)
% write the triangulations to file
bndfile = {};
for ii=1:length(bndom)
% check if vertices' normals are inward oriented
ok = checknormals(bndom(ii));
if ~ok
% Flip faces for openmeeg convention (inwards normals)
fprintf('flipping normals'' direction\n')
bndom(ii).tri = fliplr(bndom(ii).tri);
end
end
for ii=1:length(headmodel.bnd)
[junk,tname] = fileparts(tempname);
bndfile{ii} = [tname '.tri'];
om_save_tri(bndfile{ii}, bndom(ii).pos, bndom(ii).tri);
end
% these will hold the shell script and the inverted system matrix
[tmp,tname] = fileparts(tempname);
if ~ispc
exefile = [tname '.sh'];
else
exefile = [tname '.bat'];
end
[tmp,tname] = fileparts(tempname);
condfile = [tname '.cond'];
[tmp,tname] = fileparts(tempname);
geomfile = [tname '.mesh'];
[tmp,tname] = fileparts(tempname);
hmfile = [tname '.bin'];
[tmp,tname] = fileparts(tempname);
hminvfile = [tname '.bin'];
% write conductivity and mesh files
om_write_geom(geomfile,bndfile);
om_write_cond(condfile,headmodel.cond);
% Exe file
efid = fopen(exefile, 'w');
omp_num_threads = feature('numCores');
if ~ispc
fprintf(efid,'#!/usr/bin/env bash\n');
fprintf(efid,['export OMP_NUM_THREADS=',num2str(omp_num_threads),'\n']);
fprintf(efid,['om_assemble -HM ./' geomfile ' ./' condfile ' ./' hmfile ' 2>&1 > /dev/null\n']);
fprintf(efid,['om_minverser ./' hmfile ' ./' hminvfile ' 2>&1 > /dev/null\n']);
else
fprintf(efid,['om_assemble -HM ./' geomfile ' ./' condfile ' ./' hmfile '\n']);
fprintf(efid,['om_minverser ./' hmfile ' ./' hminvfile '\n']);
end
fclose(efid);
if ~ispc
dos(sprintf('chmod +x %s', exefile));
end
catch
cd(tmpfolder)
rethrow(lasterror)
end
try
% execute OpenMEEG and read the resulting file
if ispc
dos([exefile]);
else
version = om_getgccversion;
if version>3
dos(['./' exefile]);
else
error('non suitable GCC compiler version (must be superior to gcc3)');
end
end
headmodel.mat = om_load_sym(hminvfile,'binary');
cleaner(headmodel,bndfile,condfile,geomfile,hmfile,hminvfile,exefile)
cd(tmpfolder)
catch
warning('an error ocurred while running OpenMEEG');
disp(lasterr);
cleaner(headmodel,bndfile,condfile,geomfile,hmfile,hminvfile,exefile)
cd(tmpfolder)
end
% remember the type of volume conduction model
headmodel.type = 'openmeeg';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cleaner(headmodel,bndfile,condfile,geomfile,hmfile,hminvfile,exefile)
% delete the temporary files
for i=1:length(headmodel.bnd)
delete(bndfile{i})
end
delete(condfile);
delete(geomfile);
delete(hmfile);
delete(hminvfile);
delete(exefile);
function ok = checknormals(bnd)
% FIXME: this method is rigorous only for star shaped surfaces
ok = 0;
pos = bnd.pos;
tri = bnd.tri;
% translate to the center
org = mean(pos,1);
pos(:,1) = pos(:,1) - org(1);
pos(:,2) = pos(:,2) - org(2);
pos(:,3) = pos(:,3) - org(3);
w = sum(solid_angle(pos, tri));
if w<0 && (abs(w)-4*pi)<1000*eps
ok = 0;
warning('your normals are outwards oriented\n')
elseif w>0 && (abs(w)-4*pi)<1000*eps
ok = 1;
% warning('your normals are inwards oriented')
else
error('your surface probably is irregular\n')
ok = 0;
end
|
github
|
lcnhappe/happe-master
|
ft_datatype_sens.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/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
|
lcnhappe/happe-master
|
pinvNx2.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/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
|
lcnhappe/happe-master
|
normals.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/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
|
lcnhappe/happe-master
|
meg_ini.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/private/meg_ini.m
| 5,362 |
utf_8
|
57aac4444f8347f1d9de9ff52daf0147
|
function forwpar=meg_ini(vc,center,order,sens,refs,gradlocs,weights)
% initializes MEG-forward calculation
% usage: forwpar=meg_ini(vc,center,order,sens,refs,gradlocs,weights)
%
% input:
% vc: Nx6 matrix; N is the number of surface points
% the first three numbers in each row are the location
% and the second three are the orientation of the surface
% normal
% center: 3x1 vector denoting the center of volume the conductor
% order: desired order of spherical spherical harmonics;
% for 'real' realistic volume conductors order=10 is o.k
% sens: Mx6 matrix containing sensor location and orientation,
% format as for vc
% refs: optional argument. If provided, refs contains the location and oriantion
% (format as sens) of additional sensors which are subtracted from the original
% ones. This makes a gradiometer. One can also do this with the
% magnetometer version of this program und do the subtraction outside this program,
% but the gradiometer version is faster.
% gradlocs, weights: optional two arguments (they must come together!).
% gradlocs are the location of additional channels (e.g. to calculate
% a higher order gradiometer) and weights. The i.th row in weights contains
% the weights to correct if the i.th cannel. These extra fields are added!
% (has historical reasons).
%
% output:
% forpwar: structure containing all parameters needed for forward calculation
%
% note: it is assumed that locations are in cm.
% Copyright (C) 2003, Guido Nolte
%
% 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==4
if order>0;
coeff_sens=getcoeffs(sens,vc,center,order);
forwpar=struct('device_sens',sens,'coeff_sens',coeff_sens,'center',center,'order',order);
else
forwpar=struct('device_sens',sens,'center',center,'order',order);
end
elseif nargin==5
if order>0;
coeff_sens=getcoeffs(sens,vc,center,order);
coeff_refs=getcoeffs(refs,vc,center,order);
forwpar=struct('device_sens',sens,'device_ref',refs,'coeff_sens',coeff_sens,'coeff_ref',coeff_refs,'center',center,'order',order);
else
forwpar=struct('device_sens',sens,'device_ref',refs,'center',center,'order',order);
end
elseif nargin==7;
if order>0;
coeff_sens=getcoeffs(sens,vc,center,order);
coeff_refs=getcoeffs(refs,vc,center,order);
coeff_weights=getcoeffs(gradlocs,vc,center,order);
forwpar=struct('device_sens',sens,'device_ref',refs,'coeff_sens',coeff_sens,'coeff_ref',coeff_refs,'center',center,'order',order,'device_weights',gradlocs,'coeff_weights',coeff_weights,'weights',weights);
else
forwpar=struct('device_sens',sens,'device_ref',refs,'center',center,'order',order,'device_weights',gradlocs,'weights',weights);
end
else
error('you must provide 4,5 or 7 arguments');
end
return % main function
function coeffs=getcoeffs(device,vc,center,order)
[ndip,ndum]=size(vc);
[nchan,ndum]=size(device);
x1=vc(:,1:3)-repmat(center',ndip,1);
n1=vc(:,4:6);
x2=device(:,1:3)-repmat(center',nchan,1);
n2=device(:,4:6);
scale=10;
nbasis=(order+1)^2-1;
[bas,gradbas]=legs(x1,n1,order,scale);
bt=leadsphere_all(x1',x2',n2');
n1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan);
b=dotproduct(n1rep,bt);
ctc=gradbas'*gradbas;
warning('OFF', 'MATLAB:nearlySingularMatrix');
coeffs=inv(ctc)*gradbas'*b;
warning('ON', 'MATLAB:nearlySingularMatrix');
return
function field=getfield(source,device,coeffs,center,order)
[ndip,ndum]=size(source);
[nchan,ndum]=size(device);
x1=source(:,1:3)-repmat(center',ndip,1);
n1=source(:,4:6);
x2=device(:,1:3)-repmat(center',nchan,1);
n2=device(:,4:6);
%spherical
bt=leadsphere_all(x1',x2',n2');
n1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan);
b=dotproduct(n1rep,bt);
field=b';
%correction
if order>0
scale=10;
[bas,gradbas]=legs(x1,n1,order,scale);
nbasis=(order+1)^2-1;
coeffs=coeffs(1:nbasis,:);
fcorr=gradbas*coeffs;
field=field-fcorr';
end
return
function out=crossproduct(x,y)
% usage: out=testprog(x,y)
% testprog calculates the cross-product of vector x and y
[n,m,k]=size(x);
out=zeros(3,m,k);
out(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:);
out(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:);
out(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:);
return
function out=dotproduct(x,y)
% usage: out=dotproduct(x,y)
% testprog calculates the dotproduct of vector x and y
[n,m,k]=size(x);
outb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:);
out=reshape(outb,m,k);
return
function result=norms(x)
[n,m,k]=size(x);
resultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2);
result=reshape(resultb,m,k);
return
|
github
|
lcnhappe/happe-master
|
eeg_halfspace_monopole.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/private/eeg_halfspace_monopole.m
| 3,463 |
utf_8
|
20c31956ac04fd0bf5615016a9aec23e
|
function [lf] = eeg_halfspace_monopole(rd, elc, vol)
% EEG_HALFSPACE_MONOPOLE calculate the halfspace medium leadfield
% on positions pnt for a monopole at position rd and conductivity cond
% The halfspace solution requires a plane dividing a conductive zone of
% conductivity cond, from a non coductive zone (cond = 0)
%
% [lf] = eeg_halfspace_monopole(rd, elc, cond)
%
% Implemented from Malmivuo J, Plonsey R, Bioelectromagnetism (1993)
% http://www.bem.fi/book/index.htm
% Copyright (C) 2011, Cristiano Micheli
%
% 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$
siz = size(rd);
if any(siz==1)
% positions are specified as a single vector
Npoles = prod(siz)/3;
rd = rd(:)'; % ensure that it is a row vector
elseif siz(2)==3
% positions are specified as a Nx3 matrix -> reformat to a single vector
Npoles = siz(1);
rd = rd';
rd = rd(:)'; % ensure that it is a row vector
else
error('incorrect specification of dipole locations');
end
Nelc = size(elc,1);
lf = zeros(Nelc,Npoles);
for i=1:Npoles
% this is the position of dipole "i"
pole1 = rd((1:3) + 3*(i-1));
% distances electrodes - corrent poles
r1 = elc - ones(Nelc,1) * pole1;
% Method of mirror charges:
% Defines the position of mirror charge being symmetric to the plane
pole2 = get_mirror_pos(pole1,vol);
% distances electrodes - mirror charge
r2 = elc - ones(Nelc,1) * pole2;
% denominator
R1 = (4*pi*vol.cond) * (sum(r1' .^2 ) )';
% denominator, mirror term
R2 = -(4*pi*vol.cond) * (sum(r2' .^2 ) )';
% condition of poles falling in the non conductive halfspace
invacuum = acos(dot(vol.ori,(pole1-vol.pnt)./norm(pole1-vol.pnt))) < pi/2;
if invacuum
warning('a pole lies on the vacuum side of the plane');
lf(:,i) = NaN(Nelc,1);
elseif any(R1)==0
warning('a pole coincides with one of the electrodes');
lf(:,i) = NaN(Nelc,1);
else
lf(:,i) = (1 ./ R1) + (1 ./ R2);
end
end
function P2 = get_mirror_pos(P1,vol)
% calculates the position of a point symmetric to pnt with respect to a plane
P2 = [];
% define the plane
pnt = vol.pnt;
ori = vol.ori; % already normalized
if abs(dot(P1-pnt,ori))<eps
warning(sprintf ('point %f %f %f lies in the symmetry plane',P1(1),P1(2),P1(3)))
P2 = P1;
else
% define the plane in parametric form
% define a non colinear vector vc with respect to the plane normal
vc = [1 0 0];
if abs(cross(ori, vc, 2))<eps
vc = [0 1 0];
end
% define plane's direction vectors
v1 = cross(ori, vc, 2); v1 = v1/norm(v1);
v2 = cross(pnt, ori, 2); v2 = v2/norm(v2);
plane = [pnt v1 v2];
% distance plane-point P1
d = abs(dot(ori, plane(:,1:3)-P1(:,1:3), 2));
% symmetric point
P2 = P1 + 2*d*ori;
end
|
github
|
lcnhappe/happe-master
|
eeg_halfspace_medium_leadfield.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/private/eeg_halfspace_medium_leadfield.m
| 3,463 |
utf_8
|
b68f2792331216de0c239ced9734fe42
|
function [lf] = eeg_halfspace_medium_leadfield(rd, elc, vol)
% HALFSPACE_MEDIUM_LEADFIELD calculate the halfspace medium leadfield
% on positions pnt for a dipole at position rd and conductivity cond
% The halfspace solution requires a plane dividing a conductive zone of
% conductivity cond, from a non coductive zone (cond = 0)
%
% [lf] = halfspace_medium_leadfield(rd, elc, cond)
% Copyright (C) 2011, Cristiano Micheli and 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$
siz = size(rd);
if any(siz==1)
% positions are specified as a single vector
Ndipoles = prod(siz)/3;
rd = rd(:)'; % ensure that it is a row vector
elseif siz(2)==3
% positions are specified as a Nx3 matrix -> reformat to a single vector
Ndipoles = siz(1);
rd = rd';
rd = rd(:)'; % ensure that it is a row vector
else
error('incorrect specification of dipole locations');
end
Nelc = size(elc,1);
lf = zeros(Nelc,3*Ndipoles);
for i=1:Ndipoles
% this is the position of dipole "i"
dip1 = rd((1:3) + 3*(i-1));
% distances electrodes - dipole
r1 = elc - ones(Nelc,1) * dip1;
% Method of mirror dipoles:
% Defines the position of mirror dipoles being symmetric to the plane
dip2 = get_mirror_pos(dip1,vol);
% distances electrodes - mirror dipole
r2 = elc - ones(Nelc,1) * dip2;
% denominator
R1 = (4*pi*vol.cond) * (sum(r1' .^2 ) .^ 1.5)';
% denominator, mirror term
R2 = -(4*pi*vol.cond) * (sum(r2' .^2 ) .^ 1.5)';
% condition of dipoles falling in the non conductive halfspace
invacuum = acos(dot(vol.ori,(dip1-vol.pnt)./norm(dip1-vol.pnt))) < pi/2;
if invacuum
warning('dipole lies on the vacuum side of the plane');
lf(:,(1:3) + 3*(i-1)) = NaN(Nelc,3);
elseif any(R1)==0
warning('dipole coincides with one of the electrodes');
lf(:,(1:3) + 3*(i-1)) = NaN(Nelc,3);
else
lf(:,(1:3) + 3*(i-1)) = (r1 ./ [R1 R1 R1]) + (r2 ./ [R2 R2 R2]);
end
end
function P2 = get_mirror_pos(P1,vol)
% calculates the position of a point symmetric to pnt with respect to a plane
P2 = [];
% define the plane
pnt = vol.pnt;
ori = vol.ori; % already normalized
if abs(dot(P1-pnt,ori))<eps
warning(sprintf ('point %f %f %f lies in the symmetry plane',P1(1),P1(2),P1(3)))
P2 = P1;
else
% define the plane in parametric form
% define a non colinear vector vc with respect to the plane normal
vc = [1 0 0];
if abs(cross(ori, vc, 2))<eps
vc = [0 1 0];
end
% define plane's direction vectors
v1 = cross(ori, vc, 2); v1 = v1/norm(v1);
v2 = cross(pnt, ori, 2); v2 = v2/norm(v2);
plane = [pnt v1 v2];
% distance plane-point P1
d = abs(dot(ori, plane(:,1:3)-P1(:,1:3), 2));
% symmetric point
P2 = P1 + 2*d*ori;
end
|
github
|
lcnhappe/happe-master
|
ft_warning.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/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
|
lcnhappe/happe-master
|
leadsphere_all.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/private/leadsphere_all.m
| 2,291 |
utf_8
|
3d513e7f5d8a9f4a12ced5392ee85220
|
function out=leadsphere_chans(xloc,sensorloc,sensorori)
% usage: out=leadsphere_chans(xloc,sensorloc,sensorori)
% Copyright (C) 2003, Guido Nolte
%
% 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,nsens]=size(sensorloc); %n=3 m=?
[n,ndip]=size(xloc);
xlocrep=reshape(repmat(xloc,1,nsens),3,ndip,nsens);
sensorlocrep=reshape(repmat(sensorloc,ndip,1),3,ndip,nsens);
sensororirep=reshape(repmat(sensorori,ndip,1),3,ndip,nsens);
r2=norms(sensorlocrep);
veca=sensorlocrep-xlocrep;
a=norms(veca);
adotr2=dotproduct(veca,sensorlocrep);
gradf1=scal2vec(1./r2.*(a.^2)+adotr2./a+2*a+2*r2);
gradf2=scal2vec(a+2*r2+adotr2./a);
gradf=gradf1.*sensorlocrep-gradf2.*xlocrep;
F=a.*(r2.*a+adotr2);
A1=scal2vec(1./F);
A2=A1.^2;
A3=crossproduct(xlocrep,sensororirep);
A4=scal2vec(dotproduct(gradf,sensororirep));
A5=crossproduct(xlocrep,sensorlocrep);
out=1e-7*(A3.*A1-(A4.*A2).*A5); %%GRB change
return;
function out=crossproduct(x,y)
[n,m,k]=size(x);
out=zeros(3,m,k);
out(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:);
out(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:);
out(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:);
return;
function out=dotproduct(x,y)
[n,m,k]=size(x);
outb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:);
out=reshape(outb,m,k);
return;
function result=norms(x)
[n,m,k]=size(x);
resultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2);
result=reshape(resultb,m,k);
return;
function result=scal2vec(x)
[m,k]=size(x);
% result=zeros(3,m,k);
% for i=1:3
% result(i,:,:)=x;
% end
result=reshape(repmat(x(:)', [3 1]), [3 m k]);
return
|
github
|
lcnhappe/happe-master
|
ft_hastoolbox.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/private/ft_hastoolbox.m
| 24,831 |
utf_8
|
43bae19e25ce108f013f1c401e497630
|
function [status] = ft_hastoolbox(toolbox, autoadd, silent)
% FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally
% it will try to determine the path to the toolbox and install it
% automatically.
%
% Use as
% [status] = ft_hastoolbox(toolbox, autoadd, silent)
%
% autoadd = 0 means that it will not be added
% autoadd = 1 means that give an error if it cannot be added
% autoadd = 2 means that give a warning if it cannot be added
% autoadd = 3 means that it remains silent if it cannot be added
%
% silent = 0 means that it will give some feedback about adding the toolbox
% silent = 1 means that it will not give feedback
% Copyright (C) 2005-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$
% this function is called many times in FieldTrip and associated toolboxes
% use efficient handling if the same toolbox has been investigated before
% persistent previous previouspath
%
% if ~isequal(previouspath, path)
% previous = [];
% end
%
% if isempty(previous)
% previous = struct;
% elseif isfield(previous, fixname(toolbox))
% status = previous.(fixname(toolbox));
% return
% end
if isdeployed
% it is not possible to check the presence of functions or change the path in a compiled application
status = 1;
return
end
% this points the user to the website where he/she can download the toolbox
url = {
'AFNI' 'see http://afni.nimh.nih.gov'
'DSS' 'see http://www.cis.hut.fi/projects/dss'
'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab'
'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox'
'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm'
'SPM12' 'see http://www.fil.ion.ucl.ac.uk/spm'
'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd'
'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com'
'BIOSIG' 'see http://biosig.sourceforge.net'
'EEG' 'see http://eeg.sourceforge.net'
'EEGSF' 'see http://eeg.sourceforge.net' % alternative name
'MRI' 'see http://eeg.sourceforge.net' % alternative name
'NEUROSHARE' 'see http://www.neuroshare.org'
'BESA' 'see http://www.besa.de/downloads/matlab/ and get the "BESA MATLAB Readers"'
'MATLAB2BESA' 'see http://www.besa.de/downloads/matlab/ and get the "MATLAB to BESA Export functions"'
'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde'
'YOKOGAWA' 'this is deprecated, please use YOKOGAWA_MEG_READER instead'
'YOKOGAWA_MEG_READER' 'see http://www.yokogawa.com/me/me-login-en.htm'
'BEOWULF' 'see http://robertoostenveld.nl, or contact Robert Oostenveld'
'MENTAT' 'see http://robertoostenveld.nl, or contact Robert Oostenveld'
'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth'
'4D-VERSION' 'contact Christian Wienbruch'
'COMM' 'see http://www.mathworks.com/products/communications'
'SIGNAL' 'see http://www.mathworks.com/products/signal'
'OPTIM' 'see http://www.mathworks.com/products/optim'
'IMAGE' 'see http://www.mathworks.com/products/image' % Mathworks refers to this as IMAGES
'SPLINES' 'see http://www.mathworks.com/products/splines'
'DISTCOMP' 'see http://www.mathworks.nl/products/parallel-computing/'
'COMPILER' 'see http://www.mathworks.com/products/compiler'
'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica'
'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm'
'FILEIO' 'see http://www.fieldtriptoolbox.org'
'PREPROC' 'see http://www.fieldtriptoolbox.org'
'FORWARD' 'see http://www.fieldtriptoolbox.org'
'INVERSE' 'see http://www.fieldtriptoolbox.org'
'SPECEST' 'see http://www.fieldtriptoolbox.org'
'REALTIME' 'see http://www.fieldtriptoolbox.org'
'PLOTTING' 'see http://www.fieldtriptoolbox.org'
'SPIKE' 'see http://www.fieldtriptoolbox.org'
'CONNECTIVITY' 'see http://www.fieldtriptoolbox.org'
'PEER' 'see http://www.fieldtriptoolbox.org'
'PLOTTING' 'see http://www.fieldtriptoolbox.org'
'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne'
'BCI2000' 'see http://bci2000.org'
'NLXNETCOM' 'see http://www.neuralynx.com'
'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external'
'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php'
'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydesaeter'
'BEMCP' 'contact Christophe Phillips'
'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435'
'PRTOOLS' 'see http://www.prtools.org'
'ITAB' 'contact Stefania Della Penna'
'BSMART' 'see http://www.brain-smart.org'
'PEER' 'see http://www.fieldtriptoolbox.org/development/peer'
'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki'
'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page'
'VGRID' 'see http://www.rheinahrcampus.de/~medsim/vgrid/manual.html'
'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS'
'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti'
'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0'
'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab'
'BCT' 'see http://www.brain-connectivity-toolbox.net/'
'CCA' 'see http://www.imt.liu.se/~magnus/cca or contact Magnus Borga'
'EGI_MFF' 'see http://www.egi.com/ or contact either Phan Luu or Colin Davey at EGI'
'TOOLBOX_GRAPH' 'see http://www.mathworks.com/matlabcentral/fileexchange/5355-toolbox-graph or contact Gabriel Peyre'
'NETCDF' 'see http://www.mathworks.com/matlabcentral/fileexchange/15177'
'MYSQL' 'see http://www.mathworks.com/matlabcentral/fileexchange/8663-mysql-database-connector'
'ISO2MESH' 'see http://iso2mesh.sourceforge.net/cgi-bin/index.cgi?Home or contact Qianqian Fang'
'DATAHASH' 'see http://www.mathworks.com/matlabcentral/fileexchange/31272'
'IBTB' 'see http://www.ibtb.org'
'ICASSO' 'see http://www.cis.hut.fi/projects/ica/icasso'
'XUNIT' 'see http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework'
'PLEXON' 'available from http://www.plexon.com/assets/downloads/sdk/ReadingPLXandDDTfilesinMatlab-mexw.zip'
'MISC' 'various functions that were downloaded from http://www.mathworks.com/matlabcentral/fileexchange and elsewhere'
'35625-INFORMATION-THEORY-TOOLBOX' 'see http://www.mathworks.com/matlabcentral/fileexchange/35625-information-theory-toolbox'
'29046-MUTUAL-INFORMATION' 'see http://www.mathworks.com/matlabcentral/fileexchange/35625-information-theory-toolbox'
'14888-MUTUAL-INFORMATION-COMPUTATION' 'see http://www.mathworks.com/matlabcentral/fileexchange/14888-mutual-information-computation'
'PLOT2SVG' 'see http://www.mathworks.com/matlabcentral/fileexchange/7401-scalable-vector-graphics-svg-export-of-figures'
'BRAINSUITE' 'see http://brainsuite.bmap.ucla.edu/processing/additional-tools/'
'BRAINVISA' 'see http://brainvisa.info'
'FILEEXCHANGE' 'see http://www.mathworks.com/matlabcentral/fileexchange/'
'NEURALYNX_V6' 'see http://neuralynx.com/research_software/file_converters_and_utilities/ and take the version from Neuralynx (windows only)'
'NEURALYNX_V3' 'see http://neuralynx.com/research_software/file_converters_and_utilities/ and take the version from Ueli Rutishauser'
'NPMK' 'see https://github.com/BlackrockMicrosystems/NPMK'
'VIDEOMEG' 'see https://github.com/andreyzhd/VideoMEG'
'WAVEFRONT' 'see http://mathworks.com/matlabcentral/fileexchange/27982-wavefront-obj-toolbox'
'NEURONE' 'see http://www.megaemg.com/support/unrestricted-downloads'
};
if nargin<2
% default is not to add the path automatically
autoadd = 0;
end
if nargin<3
% default is not to be silent
silent = 0;
end
% determine whether the toolbox is installed
toolbox = upper(toolbox);
% In case SPM8 or higher not available, allow to use fallback toolbox
fallback_toolbox='';
switch toolbox
case 'AFNI'
dependency={'BrikLoad', 'BrikInfo'};
case 'DSS'
dependency={'denss', 'dss_create_state'};
case 'EEGLAB'
dependency = 'runica';
case 'NWAY'
dependency = 'parafac';
case 'SPM'
dependency = 'spm'; % any version of SPM is fine
case 'SPM99'
dependency = {'spm', get_spm_version()==99};
case 'SPM2'
dependency = {'spm', get_spm_version()==2};
case 'SPM5'
dependency = {'spm', get_spm_version()==5};
case 'SPM8'
dependency = {'spm', get_spm_version()==8};
case 'SPM8UP' % version 8 or later, but not SPM 9X
dependency = {'spm', get_spm_version()>=8, get_spm_version()<95};
%This is to avoid crashes when trying to add SPM to the path
fallback_toolbox = 'SPM8';
case 'SPM12'
dependency = {'spm', get_spm_version()==12};
case 'MEG-PD'
dependency = {'rawdata', 'channames'};
case 'MEG-CALC'
dependency = {'megmodel', 'megfield', 'megtrans'};
case 'BIOSIG'
dependency = {'sopen', 'sread'};
case 'EEG'
dependency = {'ctf_read_res4', 'ctf_read_meg4'};
case 'EEGSF' % alternative name
dependency = {'ctf_read_res4', 'ctf_read_meg4'};
case 'MRI' % other functions in the mri section
dependency = {'avw_hdr_read', 'avw_img_read'};
case 'NEUROSHARE'
dependency = {'ns_OpenFile', 'ns_SetLibrary', ...
'ns_GetAnalogData'};
case 'ARTINIS'
dependency = {'read_artinis_oxy3'};
case 'BESA'
dependency = {'readBESAavr', 'readBESAelp', 'readBESAswf'};
case 'MATLAB2BESA'
dependency = {'besa_save2Avr', 'besa_save2Elp', 'besa_save2Swf'};
case 'EEPROBE'
dependency = {'read_eep_avr', 'read_eep_cnt'};
case 'YOKOGAWA'
dependency = @()hasyokogawa('16bitBeta6');
case 'YOKOGAWA12BITBETA3'
dependency = @()hasyokogawa('12bitBeta3');
case 'YOKOGAWA16BITBETA3'
dependency = @()hasyokogawa('16bitBeta3');
case 'YOKOGAWA16BITBETA6'
dependency = @()hasyokogawa('16bitBeta6');
case 'YOKOGAWA_MEG_READER'
dependency = @()hasyokogawa('1.4');
case 'BEOWULF'
dependency = {'evalwulf', 'evalwulf', 'evalwulf'};
case 'MENTAT'
dependency = {'pcompile', 'pfor', 'peval'};
case 'SON2'
dependency = {'SONFileHeader', 'SONChanList', 'SONGetChannel'};
case '4D-VERSION'
dependency = {'read4d', 'read4dhdr'};
case {'STATS', 'STATISTICS'}
dependency = has_license('statistics_toolbox'); % check the availability of a toolbox license
case {'OPTIM', 'OPTIMIZATION'}
dependency = has_license('optimization_toolbox'); % check the availability of a toolbox license
case {'SPLINES', 'CURVE_FITTING'}
dependency = has_license('curve_fitting_toolbox'); % check the availability of a toolbox license
case 'COMM'
dependency = {has_license('communication_toolbox'), 'de2bi'}; % also check the availability of a toolbox license
case 'SIGNAL'
dependency = {has_license('signal_toolbox'), 'window'}; % also check the availability of a toolbox license
case 'IMAGE'
dependency = has_license('image_toolbox'); % check the availability of a toolbox license
case {'DCT', 'DISTCOMP'}
dependency = has_license('distrib_computing_toolbox'); % check the availability of a toolbox license
case 'COMPILER'
dependency = has_license('compiler'); % check the availability of a toolbox license
case 'FASTICA'
dependency = 'fpica';
case 'BRAINSTORM'
dependency = 'bem_xfer';
case 'DENOISE'
dependency = {'tsr', 'sns'};
case 'CTF'
dependency = {'getCTFBalanceCoefs', 'getCTFdata'};
case 'BCI2000'
dependency = {'load_bcidat'};
case 'NLXNETCOM'
dependency = {'MatlabNetComClient', 'NlxConnectToServer', ...
'NlxGetNewCSCData'};
case 'DIPOLI'
dependency = {'dipoli.maci', 'file'};
case 'MNE'
dependency = {'fiff_read_meas_info', 'fiff_setup_read_raw'};
case 'TCP_UDP_IP'
dependency = {'pnet', 'pnet_getvar', 'pnet_putvar'};
case 'BEMCP'
dependency = {'bem_Cij_cog', 'bem_Cij_lin', 'bem_Cij_cst'};
case 'OPENMEEG'
dependency = {'om_save_tri'};
case 'PRTOOLS'
dependency = {'prversion', 'dataset', 'svc'};
case 'ITAB'
dependency = {'lcReadHeader', 'lcReadData'};
case 'BSMART'
dependency = 'bsmart';
case 'FREESURFER'
dependency = {'MRIread', 'vox2ras_0to1'};
case 'FNS'
dependency = 'elecsfwd';
case 'SIMBIO'
dependency = {'calc_stiff_matrix_val', 'sb_transfer'};
case 'VGRID'
dependency = 'vgrid';
case 'GIFTI'
dependency = 'gifti';
case 'XML4MAT'
dependency = {'xml2struct', 'xml2whos'};
case 'SQDPROJECT'
dependency = {'sqdread', 'sqdwrite'};
case 'BCT'
dependency = {'macaque71.mat', 'motif4funct_wei'};
case 'CCA'
dependency = {'ccabss'};
case 'EGI_MFF'
dependency = {'mff_getObject', 'mff_getSummaryInfo'};
case 'TOOLBOX_GRAPH'
dependency = 'toolbox_graph';
case 'NETCDF'
dependency = {'netcdf'};
case 'MYSQL'
% not sure if 'which' would work fine here, so use 'exist'
dependency = has_mex('mysql'); % this only consists of a single mex file
case 'ISO2MESH'
dependency = {'vol2surf', 'qmeshcut'};
case 'QSUB'
dependency = {'qsubfeval', 'qsubcellfun'};
case 'ENGINE'
dependency = {'enginefeval', 'enginecellfun'};
case 'DATAHASH'
dependency = {'DataHash'};
case 'IBTB'
dependency = {'make_ibtb','binr'};
case 'ICASSO'
dependency = {'icassoEst'};
case 'XUNIT'
dependency = {'initTestSuite', 'runtests'};
case 'PLEXON'
dependency = {'plx_adchan_gains', 'mexPlex'};
case '35625-INFORMATION-THEORY-TOOLBOX'
dependency = {'conditionalEntropy', 'entropy', 'jointEntropy',...
'mutualInformation' 'nmi' 'nvi' 'relativeEntropy'};
case '29046-MUTUAL-INFORMATION'
dependency = {'MI', 'license.txt'};
case '14888-MUTUAL-INFORMATION-COMPUTATION'
dependency = {'condentropy', 'demo_mi', 'estcondentropy.cpp',...
'estjointentropy.cpp', 'estpa.cpp', ...
'findjointstateab.cpp', 'makeosmex.m',...
'mutualinfo.m', 'condmutualinfo.m',...
'entropy.m', 'estentropy.cpp',...
'estmutualinfo.cpp', 'estpab.cpp',...
'jointentropy.m' 'mergemultivariables.m' };
case 'PLOT2SVG'
dependency = {'plot2svg.m', 'simulink2svg.m'};
case 'BRAINSUITE'
dependency = {'readdfs.m', 'writedfc.m'};
case 'BRAINVISA'
dependency = {'loadmesh.m', 'plotmesh.m', 'savemesh.m'};
case 'NEURALYNX_V6'
dependency = has_mex('Nlx2MatCSC');
case 'NEURALYNX_V3'
dependency = has_mex('Nlx2MatCSC_v3');
case 'NPMK'
dependency = {'OpenNSx' 'OpenNEV'};
case 'VIDEOMEG'
dependency = {'comp_tstamps' 'load_audio0123', 'load_video123'};
case 'WAVEFRONT'
dependency = {'write_wobj' 'read_wobj'};
case 'NEURONE'
dependency = {'readneurone' 'readneuronedata' 'readneuroneevents'};
% the following are FieldTrip modules/toolboxes
case 'FILEIO'
dependency = {'ft_read_header', 'ft_read_data', ...
'ft_read_event', 'ft_read_sens'};
case 'FORWARD'
dependency = {'ft_compute_leadfield', 'ft_prepare_vol_sens'};
case 'PLOTTING'
dependency = {'ft_plot_topo', 'ft_plot_mesh', 'ft_plot_matrix'};
case 'PEER'
dependency = {'peerslave', 'peermaster'};
case 'CONNECTIVITY'
dependency = {'ft_connectivity_corr', 'ft_connectivity_granger'};
case 'SPIKE'
dependency = {'ft_spiketriggeredaverage', 'ft_spiketriggeredspectrum'};
case 'FILEEXCHANGE'
dependency = is_subdir_in_fieldtrip_path('/external/fileexchange');
case {'INVERSE', 'REALTIME', 'SPECEST', 'PREPROC', ...
'COMPAT', 'STATFUN', 'TRIALFUN', 'UTILITIES/COMPAT', ...
'FILEIO/COMPAT', 'PREPROC/COMPAT', 'FORWARD/COMPAT', ...
'PLOTTING/COMPAT', 'TEMPLATE/LAYOUT', 'TEMPLATE/ANATOMY' ,...
'TEMPLATE/HEADMODEL', 'TEMPLATE/ELECTRODE', ...
'TEMPLATE/NEIGHBOURS', 'TEMPLATE/SOURCEMODEL'}
dependency = is_subdir_in_fieldtrip_path(toolbox);
otherwise
if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end
dependency = false;
end
status = is_present(dependency);
if ~status && ~isempty(fallback_toolbox)
% in case of SPM8UP
toolbox = fallback_toolbox;
end
% try to determine the path of the requested toolbox
if autoadd>0 && ~status
% for core FieldTrip modules
prefix = fileparts(which('ft_defaults'));
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for external FieldTrip modules
prefix = fullfile(fileparts(which('ft_defaults')), 'external');
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
licensefile = [lower(toolbox) '_license'];
if status && exist(licensefile, 'file')
% this will execute openmeeg_license and mne_license
% which display the license on screen for three seconds
feval(licensefile);
end
end
% for contributed FieldTrip extensions
prefix = fullfile(fileparts(which('ft_defaults')), 'contrib');
if ~status
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
licensefile = [lower(toolbox) '_license'];
if status && exist(licensefile, 'file')
% this will execute openmeeg_license and mne_license
% which display the license on screen for three seconds
feval(licensefile);
end
end
% for linux computers in the Donders Centre for Cognitive Neuroimaging
prefix = '/home/common/matlab';
if ~status && isdir(prefix)
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% for windows computers in the Donders Centre for Cognitive Neuroimaging
prefix = 'h:\common\matlab';
if ~status && isdir(prefix)
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
% use the MATLAB subdirectory in your homedirectory, this works on linux and mac
prefix = fullfile(getenv('HOME'), 'matlab');
if ~status && isdir(prefix)
status = myaddpath(fullfile(prefix, lower(toolbox)), silent);
end
if ~status
% the toolbox is not on the path and cannot be added
sel = find(strcmp(url(:,1), toolbox));
if ~isempty(sel)
msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2});
else
msg = sprintf('the %s toolbox is not installed', toolbox);
end
if autoadd==1
error(msg);
elseif autoadd==2
ft_warning(msg);
else
% fail silently
end
end
end
% this function is called many times in FieldTrip and associated toolboxes
% use efficient handling if the same toolbox has been investigated before
if status
previous.(fixname(toolbox)) = status;
end
% remember the previous path, allows us to determine on the next call
% whether the path has been modified outise of this function
previouspath = path;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = myaddpath(toolbox, silent)
if isdeployed
warning('cannot change path settings for %s in a compiled application', toolbox);
status = 1;
elseif exist(toolbox, 'dir')
if ~silent,
ws = warning('backtrace', 'off');
warning('adding %s toolbox to your MATLAB path', toolbox);
warning(ws); % return to the previous warning level
end
addpath(toolbox);
status = 1;
elseif (~isempty(regexp(toolbox, 'spm5$', 'once')) || ~isempty(regexp(toolbox, 'spm8$', 'once')) || ~isempty(regexp(toolbox, 'spm12$', 'once'))) && exist([toolbox 'b'], 'dir')
status = myaddpath([toolbox 'b'], silent);
else
status = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function path = unixpath(path)
%path(path=='\') = '/'; % replace backward slashes with forward slashes
path = strrep(path,'\','/');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = hasfunction(funname, toolbox)
try
% call the function without any input arguments, which probably is inapropriate
feval(funname);
% it might be that the function without any input already works fine
status = true;
catch
% either the function returned an error, or the function is not available
% availability is influenced by the function being present and by having a
% license for the function, i.e. in a concurrent licensing setting it might
% be that all toolbox licenses are in use
m = lasterror;
if strcmp(m.identifier, 'MATLAB:license:checkouterror')
if nargin>1
warning('the %s toolbox is available, but you don''t have a license for it', toolbox);
else
warning('the function ''%s'' is available, but you don''t have a license for it', funname);
end
status = false;
elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction')
status = false;
else
% the function seems to be available and it gave an unknown error,
% which is to be expected with inappropriate input arguments
status = true;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = is_subdir_in_fieldtrip_path(toolbox_name)
fttrunkpath = unixpath(fileparts(which('ft_defaults')));
fttoolboxpath = fullfile(fttrunkpath, lower(toolbox_name));
needle=[pathsep fttoolboxpath pathsep];
haystack = [pathsep path() pathsep];
status = ~isempty(findstr(needle, haystack));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = has_mex(name)
full_name=[name '.' mexext];
status = (exist(full_name, 'file')==3);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function v = get_spm_version()
if ~is_present('spm')
v=NaN;
return
end
version_str = spm('ver');
token = regexp(version_str,'(\d*)','tokens');
v = str2num([token{:}{:}]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = has_license(toolbox_name)
status = license('checkout', toolbox_name)==1;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = is_present(dependency)
if iscell(dependency)
% use recursion
status = all(cellfun(@is_present,dependency));
elseif islogical(dependency)
% boolean
status = all(dependency);
elseif ischar(dependency)
% name of a function
status = is_function_present_in_search_path(dependency);
elseif isa(dependency, 'function_handle')
status = dependency();
else
assert(false,'this should not happen');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = is_function_present_in_search_path(function_name)
w = which(function_name);
% must be in path and not a variable
status = ~isempty(w) && ~isequal(w, 'variable');
|
github
|
lcnhappe/happe-master
|
mesh2edge.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/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
|
lcnhappe/happe-master
|
project_elec.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/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
|
lcnhappe/happe-master
|
eeg_slab_monopole.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/private/eeg_slab_monopole.m
| 4,375 |
utf_8
|
1ffef5225bbeaf47b2a91906c7df7b3a
|
function [lf] = eeg_slab_monopole(rd, elc, vol)
% EEG_SLAB_MONOPOLE calculate the strip medium leadfield
% on positions pnt for a monopole at position rd and conductivity cond
% The halfspace solution requires a plane dividing a conductive zone of
% conductivity cond, from a non coductive zone (cond = 0)
%
% [lf] = eeg_slab_monopole(rd, elc, cond)
%
% Implemented from Malmivuo J, Plonsey R, Bioelectromagnetism (1993)
% http://www.bem.fi/book/index.htm
% Copyright (C) 2011, Cristiano Micheli
%
% 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$
siz = size(rd);
if any(siz==1)
% positions are specified as a single vector
Npoles = prod(siz)/3;
rd = rd(:)'; % ensure that it is a row vector
elseif siz(2)==3
% positions are specified as a Nx3 matrix -> reformat to a single vector
Npoles = siz(1);
rd = rd';
rd = rd(:)'; % ensure that it is a row vector
else
error('incorrect specification of pole locations');
end
Nelc = size(elc,1);
lf = zeros(Nelc,Npoles);
for i=1:Npoles
% this is the position of dipole "i"
pole1 = rd((1:3) + 3*(i-1));
% distances electrodes - corrent poles
r1 = elc - ones(Nelc,1) * pole1;
% Method of mirror charges:
% Defines the position of mirror charge being symmetric to the plane
[pole2,pole3,pole4] = get_mirror_pos(pole1,vol);
% distances electrodes - mirror charge
r2 = elc - ones(Nelc,1) * pole2;
r3 = elc - ones(Nelc,1) * pole3;
r4 = elc - ones(Nelc,1) * pole4;
% denominator
R1 = (4*pi*vol.cond) * sqrt(sum(r1' .^2 ) )';
% denominator, mirror term
R2 = -(4*pi*vol.cond) * sqrt(sum(r2' .^2 ) )';
% denominator, mirror term of P1, plane 2
R3 = -(4*pi*vol.cond) * sqrt(sum(r3' .^2 ) )';
% denominator, mirror term of P2, plane 2
R4 = (4*pi*vol.cond) * sqrt(sum(r4' .^2 ) )';
% condition of poles falling in the non conductive halfspace
instrip1 = acos(dot(vol.ori1,(pole1-vol.pnt1)./norm(pole1-vol.pnt1))) > pi/2;
instrip2 = acos(dot(vol.ori2,(pole1-vol.pnt2)./norm(pole1-vol.pnt2))) > pi/2;
invacuum = ~(instrip1&instrip2);
if invacuum
warning('a pole lies on the vacuum side of the plane');
lf(:,i) = NaN(Nelc,1);
elseif any(R1)==0
warning('a pole coincides with one of the electrodes');
lf(:,i) = NaN(Nelc,1);
else
lf(:,i) = (1 ./ R1) + (1 ./ R2) + (1 ./ R3);% + (1 ./ R4);
end
end
function [P2,P3,P4] = get_mirror_pos(P1,vol)
% calculates the position of a point symmetric to the pole, with respect to plane1
% and two points symmetric to the last ones, with respect to plane2
P2 = []; P3 = []; P4 = [];
% define the planes
pnt1 = vol.pnt1;
ori1 = vol.ori1;
pnt2 = vol.pnt2;
ori2 = vol.ori2;
if abs(dot(P1-pnt1,ori1))<eps || abs(dot(P1-pnt2,ori2))<eps
warning(sprintf ('point %f %f %f lies on the plane',P1(1),P1(2),P1(3)))
P2 = P1;
else
% define the planes
plane1 = def_plane(pnt1,ori1);
plane2 = def_plane(pnt2,ori2);
% distance plane1-point P1
d = abs(dot(ori1, plane1(:,1:3)-P1(:,1:3), 2));
% symmetric point
P2 = P1 + 2*d*ori1;
% distance plane2-point P1
d = abs(dot(ori2, plane2(:,1:3)-P1(:,1:3), 2));
% symmetric point
P3 = P1 + 2*d*ori2;
% distance plane2-point P2
d = abs(dot(ori2, plane2(:,1:3)-P2(:,1:3), 2));
% symmetric point
P4 = P2 + 2*d*ori2;
end
function plane = def_plane(pnt,ori)
% define the plane in parametric form
% define a non colinear vector vc with respect to the plane normal
vc = [1 0 0];
if abs(cross(ori, vc, 2))<eps
vc = [0 1 0];
end
% define plane's direction vectors
v1 = cross(ori, vc, 2); v1 = v1/norm(v1);
v2 = cross(pnt, ori, 2); v2 = v2/norm(v2);
plane = [pnt v1 v2];
|
github
|
lcnhappe/happe-master
|
eeg_leadfield1.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/private/eeg_leadfield1.m
| 3,868 |
utf_8
|
84a91d4f1daf6dc32450398058ef4c3c
|
function lf = eeg_leadfield1(R, elc, vol)
% EEG_LEADFIELD1 electric leadfield for a dipole in a single sphere
%
% [lf] = eeg_leadfield1(R, elc, vol)
%
% with input arguments
% R position dipole (vector of length 3)
% elc position electrodes
% and vol being a structure with the elements
% vol.r radius of sphere
% vol.cond conductivity of sphere
%
% The center of the sphere should be at the origin.
%
% This implementation is adapted from
% Luetkenhoener, Habilschrift '92
% The original reference is
% R. Kavanagh, T. M. Darccey, D. Lehmann, and D. H. Fender. Evaluation of methods for three-dimensional localization of electric sources in the human brain. IEEE Trans Biomed Eng, 25:421-429, 1978.
% Copyright (C) 2002, 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$
Nchans = size(elc, 1);
lf = zeros(Nchans,3);
% always take the outermost sphere, this makes comparison with the 4-sphere computation easier
[vol.r, indx] = max(vol.r);
vol.cond = vol.cond(indx);
% check whether the electrode ly on the sphere, allowing 0.5% tolerance
dist = sqrt(sum(elc.^2,2));
if any(abs(dist-vol.r)>vol.r*0.005)
warning('electrodes do not ly on sphere surface -> using projection')
end
elc = vol.r * elc ./ [dist dist dist];
% check whether the dipole is inside the brain [disabled for EEGLAB]
% if sqrt(sum(R.^2))>=vol.r
% error('dipole is outside the brain compartment');
% end
c0 = norm(R);
c1 = vol.r;
c2 = 4*pi*c0^2*vol.cond;
if c0==0
% the dipole is in the origin, this can and should be handeled as an exception
[phi, el] = cart2sph(elc(:,1), elc(:,2), elc(:,3));
theta = pi/2 - el;
lf(:,1) = sin(theta).*cos(phi);
lf(:,2) = sin(theta).*sin(phi);
lf(:,3) = cos(theta);
% the potential in a homogenous sphere is three times the infinite medium potential
lf = 3/(c1^2*4*pi*vol.cond)*lf;
else
for i=1:Nchans
% use another name for the electrode, in accordance with lutkenhoner1992
r = elc(i,:);
c3 = r-R;
c4 = norm(c3);
c5 = c1^2 * c0^2 - dot(r,R)^2; % lutkenhoner A.11
c6 = c0^2*r - dot(r,R)*R; % lutkenhoner, just after A.17
% the original code reads (cf. lutkenhoner1992 equation A.17)
% lf(i,:) = ((dot(R, r/norm(r) - (r-R)/norm(r-R))/(norm(cross(r,R))^2) + 2/(norm(r-R)^3)) * cross(R, cross(r, R)) + ((norm(r)^2-norm(R)^2)/(norm(r-R)^3) - 1/norm(r)) * R) / (4*pi*vol.cond(1)*norm(R)^2);
% but more efficient execution of the code is achieved by some precomputations
if c5<1000*eps
% the dipole lies on a single line with the electrode
lf(i,:) = (2/c4^3 * c6 + ((c1^2-c0^2)/c4^3 - 1/c1) * R) / c2;
else
% nothing wrong, do the complete computation
lf(i,:) = ((dot(R, r/c1 - c3/c4)/c5 + 2/c4^3) * c6 + ((c1^2-c0^2)/c4^3 - 1/c1) * R) / c2;
end
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fast cross product
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)];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% fast dot product
function [c] = dot(a,b)
c = sum(a.*b);
|
github
|
lcnhappe/happe-master
|
meg_forward.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/private/meg_forward.m
| 3,954 |
utf_8
|
e674beba8b799e44fadd7b5e0ee82b9a
|
function field=meg_forward(dip_par,forwpar)
% calculates the magnetic field of n dipoles
% in a realistic volume conductor
% usage: field=meg_forward(dip_par,forwpar)
%
% input:
% dip_par nx6 matrix where each row contains location (first 3 numbers)
% and moment (second 3 numbers) of a dipole
% forwpar structure containing all information relevant for this
% calculation; forwpar is calculated with meg_ini
% You have here an option to include linear transformations in
% the forward model by specifying forpwar.lintrafo=A
% where A is an NxM matrix. Then field -> A field
% You can use that, e.g., if you can write the forward model
% with M magnetometer-channels plus a matrix multiplication
% transforming this to a (eventually higher order) gradiometer.
%
% output:
% field mxn matrix where the i.th column is the field in m channels
% of the i.th dipole
%
% note: No assumptions about units are made (i.e. no scaling factors)
%
% Copyright (C) 2003, Guido Nolte
%
% 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$
device_sens=forwpar.device_sens;
field_sens_sphere=getfield_sphere(dip_par,forwpar.device_sens,forwpar.center);
field=field_sens_sphere;clear field_sens_sphere;
if isfield(forwpar,'device_ref')
field=field-getfield_sphere(dip_par,forwpar.device_ref,forwpar.center);
end
if isfield(forwpar,'device_weights')
field=field+forwpar.weights*getfield_sphere(dip_par,forwpar.device_weights,forwpar.center);
end
if forwpar.order>0
coeff=forwpar.coeff_sens;
if isfield(forwpar,'device_ref')
coeff=coeff-forwpar.coeff_ref;
end
if isfield(forwpar,'device_weights')
coeff=coeff+forwpar.coeff_weights*forwpar.weights';
end
field=field+getfield_corr(dip_par,coeff,forwpar.center,forwpar.order);
end
if isfield(forwpar,'lintrafo');
field=forwpar.lintrafo*field;
end
return % main function
function field=getfield_sphere(source,device,center)
[ndip,ndum]=size(source);
[nchan,ndum]=size(device);
x1=source(:,1:3)-repmat(center',ndip,1);
n1=source(:,4:6);
x2=device(:,1:3)-repmat(center',nchan,1);
n2=device(:,4:6);
%spherical
bt=leadsphere_all(x1',x2',n2');
n1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan);
b=dotproduct(n1rep,bt);
field=b';
return
function field=getfield_corr(source,coeffs,center,order)
[ndip,ndum]=size(source);
x1=source(:,1:3)-repmat(center',ndip,1);
n1=source(:,4:6);
%correction
if order>0
scale=10;
[bas,gradbas]=legs(x1,n1,order,scale);
nbasis=(order+1)^2-1;
coeffs=coeffs(1:nbasis,:);
field=-(gradbas*coeffs)';
end
return
function out=crossproduct(x,y)
% usage: out=testprog(x,y)
% testprog calculates the cross-product of vector x and y
[n,m,k]=size(x);
out=zeros(3,m,k);
out(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:);
out(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:);
out(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:);
return
function out=dotproduct(x,y)
% usage: out=dotproduct(x,y)
% testprog calculates the dotproduct of vector x and y
[n,m,k]=size(x);
outb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:);
out=reshape(outb,m,k);
return
function result=norms(x)
[n,m,k]=size(x);
resultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2);
result=reshape(resultb,m,k);
return
|
github
|
lcnhappe/happe-master
|
leadfield_openmeeg.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/forward/private/leadfield_openmeeg.m
| 16,073 |
utf_8
|
59380282979799a30ccf58093f1bc3d8
|
function [lp, voxels_in] = leadfield_openmeeg ( voxels, vol, sens, varargin )
% FT_OM_COMPUTE_LEAD uses OpenMEEG to compute the lead fields / potentials
% using the boundary element method (BEM).
% The inputs are as follows:
% voxels = an [Nx3] array of voxel locations.
% vol = the volume structure containing bnd and cond fields. In
% order to save the matrices computed by OpenMEEG, the
% fields 'path' and 'basefile' should also be provided.
% Matrices will be stored under the directory specified by
% 'path' and 'basefile' will be used to generate the
% filename. If FT_OM_COMPUTE_LEAD is run with the same
% 'path' and 'basefile' parameters and detects the
% corresponding files from the OpenMEEG process, it will
% use those files for further processing rather than
% creating/calculating them again.
% sens = the sens structure (elec for EEG or grad for MEG)
%
% Additional parameters can be specified by setting the following vol
% fields:
% vol.ecog = "yes"/["no"] allows the computation of lead potentials
% for ECoG grids. (sens must be an EEG elec structure)
% vol.method = ["hminv"]/"adjoint" to use the adjoint method instead of
% the inverse head matrix.
%
% By default, the BEM will be computed using the inverse head matrix
% method. This is slower than the adjoint method, but more efficient if the
% BEM needs to be computed multiple times when sensor positions have
% moved relative to fixed head coordinates. To implement this type of
% computation:
% 1) vol.path and vol.basefile should be specified so that OpenMEEG
% matrices will be saved.
% 2) Once the first BEM is computed, copy the following files to a second
% working directory:
% - *_hm.bin
% - *_hminv.bin
% - *_dsm#.bin (where # is a number)
% 3) vol.path should be changed to the second working directory and
% vol.basefile should remain the same.
% 4) Recompute the BEM with the new set of sensor positions and/or voxels.
%
% Copyright (C) 2013, Daniel D.E. Wong, Sarang S. Dalal
%
% 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/>.
%
vol = fixpos(vol); % renames old subfield 'pnt' to 'pos', if necessary
% Variable declarations
CPU_LIM = feature('numCores');
VOXCHUNKSIZE = 30000; % if OpenMEEG uses too much memory for a given computer, try reducing VOXCHUNKSIZE
om_format = 'binary'; % note that OpenMEEG's mat-file supported is limited in file size (2GB?)
switch(om_format)
case 'matlab'
om_ext = '.mat';
case 'binary'
om_ext = '.bin';
otherwise
error('invalid OpenMEEG output type requested');
end
OPENMEEG_PATH = []; % '/usr/local/bin/'; % In case OpenMEEG executables omitted from PATH variable
persistent ldLibraryPath0;
if ispc
warning('Sorry, Windows is not yet tested');
elseif isunix
setenv('OMP_NUM_THREADS',num2str(CPU_LIM));
if(~ismac) % MacOS doesn't use LD_LIBRARY_PATH; in case of problems, look into "DYLD_LIBRARY_PATH"
if isempty(ldLibraryPath0)
ldLibraryPath0 = getenv('LD_LIBRARY_PATH'); % We'll restore this at the end
end
UNIX_LDLIBRARYPATH = '/usr/lib:/usr/local/lib';
setenv('LD_LIBRARY_PATH',UNIX_LDLIBRARYPATH); % MATLAB changes the default LD_LIBRARY_PATH variable
end
end
[om_status,om_errmsg] = system(fullfile(OPENMEEG_PATH,'om_assemble')); % returns 0 if om_assemble is not happy
if(om_status ~= 0)
error([om_errmsg 'Unable to properly execute OpenMEEG. Please configure variable declarations and paths in this file as needed.']);
else
clear om_status
end
% Extra options
method = ft_getopt(vol,'method','hminv');
ecog = ft_getopt(vol,'ecog','no');
% Use basefile and basepath for saving files
if isfield(vol,'basefile')
basefile = vol.basefile;
else
basefile = tempname;
end
if isfield(vol,'path')
path = vol.path;
cleanup_flag = false;
else
path = fullfile(tempdir,'ft-om');
cleanup_flag = true;
end
mkdir(path);
sensorFile = fullfile(path, [basefile '_sensorcoords.txt']);
if exist(sensorFile,'file')
disp('Sensor coordinate file already exists. Skipping...')
else
disp('Writing sensor coordinates...')
fid = fopen(sensorFile,'w');
if ft_senstype(sens, 'eeg')
for ii=1:size(sens.chanpos,1)
fprintf(fid,'%s\t%.15f\t%.15f\t%.15f\n', sens.label{ii}, sens.chanpos(ii,:));
end
else % MEG
% Find channel labels for each coil -- non-trivial for MEG gradiometers!
% Note that each coil in a gradiometer pair will receive the same label
[chanlabel_idx,coilpos_idx]=find(abs(sens.tra)==1);
newchanlabelmethod = true
if(newchanlabelmethod)
for ii=1:size(sens.coilpos,1)
fprintf(fid,'%.15f\t%.15f\t%.15f\t%.15f\t%.15f\t%.15f\n',sens.coilpos(ii,:),sens.coilori(ii,:));
end
else
if(size(sens.tra,1) < max(chanlabel_idx) | size(sens.tra,2) ~= length(coilpos_idx) | length(coilpos_idx) ~= size(sens.coilpos,1))
% These dimensions should match; if not, some channels may have been
% removed, or there's unexpected handling of MEG reference coils
error('Mismatch between number of rows in sens.tra and number of channels... possibly some channels removed or unexpected MEG reference coil configuration');
end
for ii=1:length(coilpos_idx)
coilpair_idx = find(chanlabel_idx(ii) == chanlabel_idx);
if(length(coilpair_idx)==2)
whichcoil = find(ii == coilpair_idx);
switch(whichcoil)
case 1
labelsuffix = 'A';
case 2
labelsuffix = 'B';
end
else
labelsuffix = '';
end
label = [sens.label{chanlabel_idx(ii)} labelsuffix];
fprintf(fid,'%s\t%.15f\t%.15f\t%.15f\t%.15f\t%.15f\t%.15f\n',label,sens.coilpos(ii,:),sens.coilori(ii,:));
end
end
end
fclose(fid);
end
condFile = fullfile(path, [basefile '.cond']);
if exist(condFile,'file')
disp('Conductivity file already exists. Skipping...')
else
disp('Writing conductivity file...')
write_cond(vol,condFile);
end
geomFile = fullfile(path, [basefile '.geom']);
if exist(geomFile,'file')
disp('Geometry descriptor file already exists. Skipping...')
else
disp('Writing geometry descriptor file...')
write_geom(vol,geomFile,basefile);
end
disp('Writing OpenMEEG mesh files...')
write_mesh(vol,path,basefile);
disp('Validating mesh...')
[om_status om_msg] = system([fullfile(OPENMEEG_PATH, 'om_check_geom'), ' -g ', geomFile])
if(om_status ~= 0) % status = 0 if successful
error([om_msg, 'Aborting OpenMEEG pipeline due to above error.']);
end
disp('Writing dipole file...')
chunks = ceil(size(voxels,1)/VOXCHUNKSIZE);
dipFile = cell(chunks,1);
for ii = 1:chunks
dipFile{ii} = fullfile(path, [basefile '_voxels' num2str(ii) om_ext]);
if exist(dipFile{ii},'file')
fprintf('\t%s already exists. Skipping...\n', dipFile{ii});
else
voxidx = ((ii-1)*VOXCHUNKSIZE + 1) : (min((ii)*VOXCHUNKSIZE,size(voxels,1)));
writevoxels = [kron(voxels(voxidx,:),ones(3,1)) , kron(ones(length(voxidx),1),eye(3))];
om_save_full(writevoxels,dipFile{ii},om_format);
end
end
hmFile = fullfile(path, [basefile '_hm' om_ext]);
if exist(hmFile,'file')
disp('Head matrix already exists. Skipping...')
else
disp('Building head matrix')
[om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_assemble'), ' -hm ', geomFile, ' ', condFile, ' ', hmFile])
if(om_status ~= 0) % status = 0 if successful
error([om_msg, 'Aborting OpenMEEG pipeline due to above error.']);
end
end
if strcmp(method,'hminv')
hminvFile = fullfile(path, [basefile '_hminv' om_ext]);
if exist(hminvFile,'file')
disp('Inverse head matrix already exists. Skipping...');
else
disp('Computing inverse head matrix');
if(CPU_LIM >= 4) % Matlab's inverse function is multithreaded and performs faster with at least 4 cores
om_save_sym(inv(om_load_sym(hmFile,om_format)),hminvFile,om_format);
else
[om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_minverser'), ' ', hmFile, ' ', hminvFile])
if(om_status ~= 0) % status = 0 if successful
error([om_msg, 'Aborting OpenMEEG pipeline due to above error.']);
end
end
end
end
dsmFile = cell(chunks,1);
for ii = 1:chunks
dsmFile{ii} = fullfile(path, [basefile '_dsm' num2str(ii) om_ext]);
if exist(dsmFile{ii},'file')
fprintf('\t%s already exists. Skipping...\n', dsmFile{ii});
else
disp('Assembling source matrix');
[om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_assemble'), ' -dsm ', geomFile, ' ', condFile, ' ', dipFile{ii}, ' ' dsmFile{ii}])
if(om_status ~= 0) % status = 0 if successful
error([om_msg, 'Aborting OpenMEEG pipeline due to above error. If 4-layer BEM attempted, try 3-layer BEM (scalp, skull, brain).']);
end
end
end
disp('--------------------------------------')
if ft_senstype(sens, 'eeg')
if strcmp(ecog,'yes')
ohmicFile = fullfile(path, [basefile '_h2ecogm']);
cmd = '-h2ecogm';
else
ohmicFile = fullfile(path, [basefile '_h2em' om_ext]);
cmd = '-h2em';
end
else
ohmicFile = fullfile(path, [basefile '_h2mm' om_ext]);
cmd = '-h2mm';
end
if exist(ohmicFile,'file')
disp('Ohmic current file already exists. Skipping...')
else
disp('Calculating Contribution of Ohmic Currents')
[om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_assemble'), ' ', cmd, ' ', geomFile, ' ', condFile, ' ' , sensorFile, ' ' , ohmicFile])
if(om_status ~= 0) % status = 0 if successful
error([om_msg, 'Aborting OpenMEEG pipeline due to above error.']);
end
end
if ft_senstype(sens, 'meg')
disp('Contribution of all sources to the MEG sensors')
scFile = cell(chunks,1);
for ii = 1:chunks
scFile{ii} = fullfile(path, [basefile '_ds2mm' num2str(ii) om_ext]);
if exist(scFile{ii},'file')
fprintf('\t%s already exists. Skipping...\n',scFile{ii})
else
[om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_assemble'), ' -ds2mm ', dipFile{ii} ,' ', sensorFile, ' ' , scFile{ii}])
if(om_status ~= 0) % status = 0 if successful
error([om_msg, 'Aborting OpenMEEG pipeline due to above error.']);
end
end
end
end
disp('Putting it all together.')
bemFile = cell(chunks,1);
for ii = 1:chunks
if ft_senstype(sens, 'eeg')
bemFile{ii} = fullfile(path, [basefile '_eeggain' num2str(ii) om_ext]);
else
bemFile{ii} = fullfile(path, [basefile '_meggain' num2str(ii) om_ext]);
end
if exist(bemFile{ii},'file')
fprintf('/t%s already exists. Skipping...\n', bemFile{ii});
continue;
end
if strcmp(method,'hminv')
if ft_senstype(sens, 'eeg')
[om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_gain'), ' -EEG ', hminvFile, ' ', dsmFile{ii}, ' ', ohmicFile, ' ', bemFile{ii}]);
else
[om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_gain'), ' -MEG ', hminvFile, ' ', dsmFile{ii}, ' ', ohmicFile,' ', scFile{ii}, ' ',bemFile{ii}]);
end
else % Adjoint method
if ft_senstype(sens, 'eeg')
[om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_gain'), ' -EEGadjoint ', geomFile, ' ', condFile, ' ', dipFile{ii},' ', hmFile, ' ', ohmicFile, ' ', bemFile{ii}]);
else
[om_status, om_msg] = system([fullfile(OPENMEEG_PATH, 'om_gain'), ' -MEGadjoint ', geomFile, ' ', condFile, ' ', dipFile{ii},' ', hmFile, ' ', ohmicFile, ' ', scFile{ii}, ' ',bemFile{ii}]);
end
end
if(om_status ~= 0) % status = 0 if successful
error([om_msg, 'Aborting OpenMEEG pipeline due to above error.']);
end
end
% Import lead field/potential
[g, voxels_in] = import_gain(path, basefile, ft_senstype(sens, 'eeg'));
if (voxels_in ~= voxels) & (nargout == 1); warning('Imported voxels from OpenMEEG process not the same as function input.'); end;
lp = sens.tra*g; % Mchannels x (3 orientations x Nvoxels)
% Cleanup
if cleanup_flag
rmdir(basepath,'s')
end
if (isunix & ~ismac)
setenv('LD_LIBRARY_PATH',ldLibraryPath0);
end
function write_cond(vol,filename)
fid=fopen(filename,'w');
fprintf(fid,'# Properties Description 1.0 (Conductivities)\n');
tissues = {'Scalp\t%f\n'; 'Skull\t%f\n'; 'CSF\t%f\n'; 'Brain\t%f\n'};
if length(vol.cond)==3; tissues = tissues([1 2 4]); end;
fprintf(fid,'Air\t0\n');
for ii=1:length(vol.cond)
fprintf(fid,tissues{ii},vol.cond(ii));
end
fclose(fid);
function write_geom(vol,filename,basepathfile)
fid=fopen(filename,'w');
fprintf(fid,'# Domain Description 1.0\n');
fprintf(fid,'Interfaces %i Mesh\n',length(vol.cond));
tissues={'_scalp.tri\n'; '_skull.tri\n'; '_csf.tri\n'; '_brain.tri\n'};
if length(vol.cond)==3; tissues = tissues([1 2 4]); end;
for ii = 1:length(vol.cond)
fprintf(fid,[basepathfile tissues{ii}]);
end
fprintf('\n');
fprintf(fid,'Domains %i\n',length(vol.cond)+1);
domains={'Scalp'; 'Skull'; 'CSF'; 'Brain'};
if length(vol.cond)==3; domains = domains([1 2 4]); end;
fprintf(fid,'Domain Air %i\n',1);
for ii = 1:length(vol.cond)
if ii < length(vol.cond)
fprintf(fid,['Domain ' domains{ii} ' %i -%i\n'],ii+1,ii);
else
fprintf(fid,['Domain ' domains{ii} ' -%i\n'],ii);
end
end
fclose(fid);
function write_mesh(vol,path,basefile)
tissues={'_scalp'; '_skull'; '_csf'; '_brain'};
if length(vol.cond)==3; tissues = tissues([1 2 4]); end;
for ii = 1:length(vol.cond)
meshFile = fullfile(path, [basefile tissues{ii} '.tri']);
if exist(meshFile,'file')
fprintf('\t%s already exists. Skipping...\n', meshFile);
break;
else
om_save_tri(fullfile(path, [basefile tissues{ii} '.tri']),vol.bnd(ii).pos,vol.bnd(ii).tri);
%savemesh([path basefile tissues{ii} '.mesh'],vol.bnd(ii).vertices/1000,vol.bnd(ii).faces-1,-vol.bnd(ii).normals);
end
end
function [g, voxels] = import_gain(path, basefile, eegflag)
om_format = 'binary';
switch(om_format)
case 'matlab'
om_ext = '.mat';
case 'binary'
om_ext = '.bin';
otherwise
error('invalid OpenMEEG output type requested');
end
if eegflag
omgainfiles = dir(fullfile(path, [basefile '_eeggain*' om_ext]));
else
omgainfiles = dir(fullfile(path, [basefile '_meggain*' om_ext]));
end
omvoxfiles = dir(fullfile(path, [basefile '_voxels*' om_ext]));
g=[];
voxels=[];
% join gain/voxel files
% [openmeeg calculation may have been split for memory reasons]
for ii=1:length(omgainfiles)
g = [g om_load_full(fullfile(path, omgainfiles(ii).name),om_format)];
voxels = [voxels;om_load_full(fullfile(path, omvoxfiles(ii).name),om_format)];
end
voxels = voxels(1:3:end,1:3);
|
github
|
lcnhappe/happe-master
|
firwsord.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/preproc/private/firwsord.m
| 2,973 |
utf_8
|
a2d4fcfe22b1570834add343cd9b6bc0
|
% firwsord() - Estimate windowed sinc FIR filter order depending on
% window type and requested transition band width
%
% Usage:
% >> [m, dev] = firwsord(wtype, fs, df);
% >> m = firwsord('kaiser', fs, df, dev);
%
% Inputs:
% wtype - char array window type. 'rectangular', 'bartlett', 'hann',
% 'hamming', 'blackman', or 'kaiser'
% fs - scalar sampling frequency
% df - scalar requested transition band width
% dev - scalar maximum passband deviation/ripple (Kaiser window
% only)
%
% Output:
% m - scalar estimated filter order
% dev - scalar maximum passband deviation/ripple
%
% References:
% [1] Smith, S. W. (1999). The scientist and engineer's guide to
% digital signal processing (2nd ed.). San Diego, CA: California
% Technical Publishing.
% [2] Proakis, J. G., & Manolakis, D. G. (1996). Digital Signal
% Processing: Principles, Algorithms, and Applications (3rd ed.).
% Englewood Cliffs, NJ: Prentice-Hall
% [3] Ifeachor E. C., & Jervis B. W. (1993). Digital Signal
% Processing: A Practical Approach. Wokingham, UK: Addison-Wesley
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% firws, invfirwsord
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005-2014 Andreas Widmann, University of Leipzig, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
% $Id$
function [ m, dev ] = firwsord(wintype, fs, df, dev)
winTypeArray = {'rectangular', 'bartlett', 'hann', 'hamming', 'blackman', 'kaiser'};
winDfArray = [0.9 2.9 3.1 3.3 5.5];
winDevArray = [0.089 0.056 0.0063 0.0022 0.0002];
% Check arguments
if nargin < 3 || isempty(fs) || isempty(df) || isempty(wintype)
error('Not enough input arguments.')
end
% Window type
wintype = find(strcmp(wintype, winTypeArray));
if isempty(wintype)
error('Unknown window type.')
end
df = df / fs; % Normalize transition band width
if wintype == 6 % Kaiser window
if nargin < 4 || isempty(dev)
error('Not enough input arguments.')
end
devdb = -20 * log10(dev);
m = 1 + (devdb - 8) / (2.285 * 2 * pi * df);
else
m = winDfArray(wintype) / df;
dev = winDevArray(wintype);
end
m = ceil(m / 2) * 2; % Make filter order even (FIR type I)
end
|
github
|
lcnhappe/happe-master
|
minphaserceps.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/preproc/private/minphaserceps.m
| 2,151 |
utf_8
|
57715581f54dbcadc7e0a0bda70ce5c9
|
% rcepsminphase() - Convert FIR filter coefficient to minimum phase
%
% Usage:
% >> b = minphaserceps(b);
%
% Inputs:
% b - FIR filter coefficients
%
% Outputs:
% bMinPhase - minimum phase FIR filter coefficients
%
% Author: Andreas Widmann, University of Leipzig, 2013
%
% References:
% [1] Smith III, O. J. (2007). Introduction to Digital Filters with Audio
% Applications. W3K Publishing. Retrieved Nov 11 2013, from
% https://ccrma.stanford.edu/~jos/fp/Matlab_listing_mps_m.html
% [2] Vetter, K. (2013, Nov 11). Long FIR filters with low latency.
% Retrieved Nov 11 2013, from
% http://www.katjaas.nl/minimumphase/minimumphase.html
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2013 Andreas Widmann, University of Leipzig, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
% $Id$
function [bMinPhase] = minphaserceps(b)
% Line vector
b = b(:)';
n = length(b);
upsamplingFactor = 1e3; % Impulse response upsampling/zero padding to reduce time-aliasing
nFFT = 2^ceil(log2(n * upsamplingFactor)); % Power of 2
clipThresh = 1e-8; % -160 dB
% Spectrum
s = abs(fft(b, nFFT));
s(s < clipThresh) = clipThresh; % Clip spectrum to reduce time-aliasing
% Real cepstrum
c = real(ifft(log(s)));
% Fold
c = [c(1) [c(2:nFFT / 2) 0] + conj(c(nFFT:-1:nFFT / 2 + 1)) zeros(1, nFFT / 2 - 1)];
% Minimum phase
bMinPhase = real(ifft(exp(fft(c))));
% Remove zero-padding
bMinPhase = bMinPhase(1:n);
end
|
github
|
lcnhappe/happe-master
|
firws.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/preproc/private/firws.m
| 3,217 |
utf_8
|
c683c72e05eaadd0e53428ab481f880a
|
%firws() - Designs windowed sinc type I linear phase FIR filter
%
% Usage:
% >> b = firws(m, f);
% >> b = firws(m, f, w);
% >> b = firws(m, f, t);
% >> b = firws(m, f, t, w);
%
% Inputs:
% m - filter order (mandatory even)
% f - vector or scalar of cutoff frequency/ies (-6 dB;
% pi rad / sample)
%
% Optional inputs:
% w - vector of length m + 1 defining window {default blackman}
% t - 'high' for highpass, 'stop' for bandstop filter {default low-/
% bandpass}
%
% Output:
% b - filter coefficients
%
% Example:
% fs = 500; cutoff = 0.5; df = 1;
% m = firwsord('hamming', fs, df);
% b = firws(m, cutoff / (fs / 2), 'high', windows('hamming', m + 1));
%
% References:
% Smith, S. W. (1999). The scientist and engineer's guide to digital
% signal processing (2nd ed.). San Diego, CA: California Technical
% Publishing.
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% firwsord, invfirwsord, kaiserbeta, windows
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005 Andreas Widmann, University of Leipzig, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
% $Id$
function [b, a] = firws(m, f, t, w)
a = 1;
if nargin < 2
error('Not enough input arguments');
end
if length(m) > 1 || ~isnumeric(m) || ~isreal(m) || mod(m, 2) ~= 0 || m < 2
error('Filter order must be a real, even, positive integer.');
end
f = f / 2;
if any(f <= 0) || any(f >= 0.5)
error('Frequencies must fall in range between 0 and 1.');
end
if nargin < 3 || isempty(t)
t = '';
end
if nargin < 4 || isempty(w)
if ~isempty(t) && ~ischar(t)
w = t;
t = '';
else
w = windows('blackman', (m + 1));
end
end
w = w(:)'; % Make window row vector
b = fkernel(m, f(1), w);
if length(f) == 1 && strcmpi(t, 'high')
b = fspecinv(b);
end
if length(f) == 2
b = b + fspecinv(fkernel(m, f(2), w));
if isempty(t) || ~strcmpi(t, 'stop')
b = fspecinv(b);
end
end
% Compute filter kernel
function b = fkernel(m, f, w)
m = -m / 2 : m / 2;
b(m == 0) = 2 * pi * f; % No division by zero
b(m ~= 0) = sin(2 * pi * f * m(m ~= 0)) ./ m(m ~= 0); % Sinc
b = b .* w; % Window
b = b / sum(b); % Normalization to unity gain at DC
% Spectral inversion
function b = fspecinv(b)
b = -b;
b(1, (length(b) - 1) / 2 + 1) = b(1, (length(b) - 1) / 2 + 1) + 1;
|
github
|
lcnhappe/happe-master
|
kaiserbeta.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/preproc/private/kaiserbeta.m
| 1,569 |
utf_8
|
18e3b152604b8dd8d1bb7052e720f3a6
|
% kaiserbeta() - Estimate Kaiser window beta
%
% Usage:
% >> beta = pop_kaiserbeta(dev);
%
% Inputs:
% dev - scalar maximum passband deviation/ripple
%
% Output:
% beta - scalar Kaiser window beta
%
% References:
% [1] Proakis, J. G., & Manolakis, D. G. (1996). Digital Signal
% Processing: Principles, Algorithms, and Applications (3rd ed.).
% Englewood Cliffs, NJ: Prentice-Hall
%
% Author: Andreas Widmann, University of Leipzig, 2005
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005-2014 Andreas Widmann, University of Leipzig, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
% $Id$
function [ beta ] = kaiserbeta(dev)
devdb = -20 * log10(dev);
if devdb > 50
beta = 0.1102 * (devdb - 8.7);
elseif devdb >= 21
beta = 0.5842 * (devdb - 21)^0.4 + 0.07886 * (devdb - 21);
else
beta = 0;
end
end
|
github
|
lcnhappe/happe-master
|
invfirwsord.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/preproc/private/invfirwsord.m
| 2,900 |
utf_8
|
1ede4ed306eda03dcaa8daffa9426079
|
% invfirwsord() - Estimate windowed sinc FIR filter transition band width
% depending on filter order and window type
%
% Usage:
% >> [df, dev] = invfirwsord(wtype, fs, m);
% >> df = invfirwsord('kaiser', fs, m, dev);
%
% Inputs:
% wtype - char array window type. 'rectangular', 'bartlett', 'hann',
% 'hamming', 'blackman', or 'kaiser'
% fs - scalar sampling frequency}
% m - scalar filter order
% dev - scalar maximum passband deviation/ripple (Kaiser window
% only)
%
% Output:
% df - scalar estimated transition band width
% dev - scalar maximum passband deviation/ripple
%
% References:
% [1] Smith, S. W. (1999). The scientist and engineer's guide to
% digital signal processing (2nd ed.). San Diego, CA: California
% Technical Publishing.
% [2] Proakis, J. G., & Manolakis, D. G. (1996). Digital Signal
% Processing: Principles, Algorithms, and Applications (3rd ed.).
% Englewood Cliffs, NJ: Prentice-Hall
% [3] Ifeachor E. C., & Jervis B. W. (1993). Digital Signal
% Processing: A Practical Approach. Wokingham, UK: Addison-Wesley
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% firws, firwsord
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005-2014 Andreas Widmann, University of Leipzig, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
% $Id$
function [ df, dev ] = invfirwsord(wintype, fs, m, dev)
winTypeArray = {'rectangular', 'bartlett', 'hann', 'hamming', 'blackman', 'kaiser'};
winDfArray = [0.9 2.9 3.1 3.3 5.5];
winDevArray = [0.089 0.056 0.0063 0.0022 0.0002];
% Check arguments
if nargin < 3 || isempty(fs) || isempty(m) || isempty(wintype)
error('Not enough input arguments.')
end
% Window type
wintype = find(strcmp(wintype, winTypeArray));
if isempty(wintype)
error('Unknown window type.')
end
if wintype == 6 % Kaiser window
if nargin < 4 || isempty(dev)
error('Not enough input arguments.')
end
devdb = -20 * log10(dev);
df = (devdb - 8) / (2.285 * 2 * pi * (m - 1));
else
df = winDfArray(wintype) / m;
dev = winDevArray(wintype);
end
% df is normalized
df = df * fs;
end
|
github
|
lcnhappe/happe-master
|
windows.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/preproc/private/windows.m
| 3,152 |
utf_8
|
13d9e2d7d608f7550b77f84278c89184
|
% windows() - Symmetric window functions
%
% Usage:
% >> h = windows(t, m);
% >> h = windows(t, m, a);
%
% Inputs:
% t - char array 'rectangular', 'bartlett', 'hann', 'hamming',
% 'blackman', 'blackmanharris', 'kaiser', or 'tukey'
% m - scalar window length
%
% Optional inputs:
% a - scalar or vector with window parameter(s)
%
% Output:
% w - column vector window
%
% Author: Andreas Widmann, University of Leipzig, 2014
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2014 Andreas Widmann, University of Leipzig, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
% $Id$
function w = windows(t, m, a)
if nargin < 2 || isempty(t) || isempty(m)
error('Not enough input arguments.');
end
% Check window length
if m ~= round(m)
m = round(m);
warning('firws:nonIntegerWindowLength', 'Non-integer window length. Rounding to integer.')
end
if m < 1
error('Invalid window length.')
end
% Length 1
if m == 1
w = 1;
return;
end
% Even/odd?
isOddLength = mod(m, 2);
if isOddLength
x = (0:(m - 1) / 2)' / (m - 1);
else
x = (0:m / 2 - 1)' / (m - 1);
end
switch t
case 'rectangular'
w = ones(length(x), 1);
case 'bartlett'
w = 2 * x;
case 'hann'
a = 0.5;
w = a - (1 - a) * cos(2 * pi * x);
case 'hamming'
a = 0.54;
w = a - (1 - a) * cos(2 * pi * x);
case 'blackman'
a = [0.42 0.5 0.08 0];
w = a(1) - a(2) * cos (2 * pi * x) + a(3) * cos(4 * pi * x) - a(4) * cos(6 * pi * x);
case 'blackmanharris'
a = [0.35875 0.48829 0.14128 0.01168];
w = a(1) - a(2) * cos (2 * pi * x) + a(3) * cos(4 * pi * x) - a(4) * cos(6 * pi * x);
case 'kaiser'
if nargin < 3 || isempty(a)
a = 0.5;
end
w = besseli(0, a * sqrt(1 - (2 * x - 1).^2)) / besseli(0, a);
case 'tukey'
if nargin < 3 || isempty(a)
a = 0.5;
end
if a <= 0 % Rectangular
w = ones(length(x), 1);
elseif a >= 1 % Hann
w = 0.5 - (1 - 0.5) * cos(2 * pi * x);
else
mTaper = floor((m - 1) * a / 2) + 1;
xTaper = 2 * (0:mTaper - 1)' / (a * (m - 1)) - 1;
w = [0.5 * (1 + cos(pi * xTaper)); ones(length(x) - mTaper, 1)];
end
otherwise
error('Unkown window type')
end
% Make symmetric
if isOddLength
w = [w; w(end - 1:-1:1)];
else
w = [w; w(end:-1:1)];
end
end
|
github
|
lcnhappe/happe-master
|
ft_warning.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/preproc/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
|
lcnhappe/happe-master
|
fir_filterdcpadded.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/preproc/private/fir_filterdcpadded.m
| 2,934 |
utf_8
|
a5287ea8667b904280539687a04797ca
|
% fir_filterdcpadded() - Pad data with DC constant and filter
%
% Usage:
% >> data = fir_filterdcpadded(b, a, data, causal);
%
% Inputs:
% b - vector of filter coefficients
% a - 1
% data - raw data (times x chans)
% causal - boolean perform causal filtering {default 0}
% usefftfilt - boolean use fftfilt instead of filter
%
% Outputs:
% data - smoothed data
%
% Note:
% firfiltdcpadded always operates (pads, filters) along first dimension.
% Not memory optimized.
%
% Author: Andreas Widmann, University of Leipzig, 2014
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2013 Andreas Widmann, University of Leipzig, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
% $Id$
function [ data ] = fir_filterdcpadded(b, a, data, causal, usefftfilt)
% Defaults
if nargin < 4 || isempty(usefftfilt)
usefftfilt = 0;
end
if nargin < 3 || isempty(causal)
causal = 0;
end
% Check arguments
if nargin < 2
error('Not enough input arguments.');
end
% Is FIR?
if ~isscalar(a) || a ~= 1
error('Not a FIR filter. onepass-zerophase and onepass-minphase filtering is available for FIR filters only.')
end
% Group delay
if mod(length(b), 2) ~= 1
error('Filter order is not even.');
end
groupDelay = (length(b) - 1) / 2;
% Filter symmetry
isSym = all(b(1:groupDelay) == b(end:-1:groupDelay + 2));
isAntisym = all([b(1:groupDelay) == -b(end:-1:groupDelay + 2) b(groupDelay + 1) == 0]);
if causal == 0 && ~(isSym || isAntisym)
error('Filter is not anti-/symmetric. For onepass-zerophase filtering the filter must be anti-/symmetric.')
end
% Padding
if causal
startPad = repmat(data(1, :), [2 * groupDelay 1]);
endPad = [];
else
startPad = repmat(data(1, :), [groupDelay 1]);
endPad = repmat(data(end, :), [groupDelay 1]);
end
% Filter data (with double precision)
isSingle = isa(data, 'single');
if usefftfilt
data = fftfilt(double(b), double([startPad; data; endPad]));
else
data = filter(double(b), 1, double([startPad; data; endPad])); % Pad and filter with double precision
end
% Convert to single
if isSingle
data = single(data);
end
% Remove padded data
data = data(2 * groupDelay + 1:end, :);
end
|
github
|
lcnhappe/happe-master
|
plotfresp.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/preproc/private/plotfresp.m
| 5,213 |
utf_8
|
02ff3bdc63f5c3410460734e2a7378fe
|
% plotfresp() - Plot a filter's impulse, step, magnitude, and phase response
%
% Usage:
% >> plotfresp(b, a, nfft, fs, causal);
%
% Inputs:
% b - vector numerator coefficients
%
% Optional inputs:
% a - scalar or vector denominator coefficients (IIR support is
% experimental!) {default 1}
% nfft - scalar number of points {default 512}
% fs - scalar sampling frequency {default 1}
% dir - string filter direction {default 'onepass'}
%
% Author: Andreas Widmann, University of Leipzig, 2005
%
% See also:
% firws
%123456789012345678901234567890123456789012345678901234567890123456789012
% Copyright (C) 2005-2014 Andreas Widmann, University of Leipzig, [email protected]
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 2 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
%
% $Id$
function plotfresp(b, a, nfft, fs, dir)
if nargin < 5 || isempty(dir)
dir = 'onepass';
end
if nargin < 4 || isempty(fs)
fs = 1;
end
if nargin < 3 || isempty(nfft)
nfft = 512;
end
if nargin < 2 || isempty(a)
a = 1;
end
if nargin < 1
error('Not enough input arguments.');
end
% FIR?
if isscalar(a) && a == 1
isFIR = true;
else
isFIR = false;
end
% Linear phase FIR
if isFIR && all(b(:)' == fliplr(b(:)')) % TODO: antisymmetric
isLinPhaseFir = true;
else
isLinPhaseFir = false;
end
% Twopass/zerophase?
if strncmp('twopass', dir, 7)
isTwopass = true;
isZerophase = true;
elseif strcmp('onepass-zerophase', dir)
if ~isLinPhaseFir
error('Onepass-zerophase filtering is only allowed for linear-phase FIR filters.')
end
isTwopass = false;
isZerophase = true;
else
isTwopass = false;
isZerophase = false;
end
% Impulse response
if isFIR
impresp = b(:)';
else
if ~exist('impz', 'file')
warning('Plotting IIR filter responses requires signal processing toolbox.')
return
end
impresp = impz(b, a)';
end
% Twopass
if isTwopass
impresp = conv(impresp, fliplr(impresp));
end
n = length(impresp);
% Zerophase
if isZerophase
groupdelay = (n - 1) / 2;
x = -groupdelay:groupdelay;
else
x = 0:n - 1;
end
nfft = max([2^ceil(log2(n)) nfft]); % Do not truncate impulse response
f = linspace(0, fs / 2, nfft / 2 + 1);
z = fft(impresp, nfft);
z = z(1:nfft / 2 + 1);
% Find open figure window
H = findobj('Tag', 'plotfiltresp', 'type', 'figure');
if ~isempty(H)
figure(H);
else
H = figure;
set(H, 'Tag', 'plotfiltresp');
posArray = get(H, 'Position');
posArray(3) = posArray(4) * 1.6;
set(H, 'Position', posArray);
end
% Formatting
titlePropArray = {'Fontweight', 'bold'};
axisPropArray = {'NextPlot', 'add', 'XGrid', 'on', 'YGrid', 'on', 'Box', 'on'};
% Impulse resonse
ax(1) = subplot(2, 3, 1, axisPropArray{:});
stem(x, impresp, 'fill')
title('Impulse response', titlePropArray{:});
ylabel('Amplitude');
% Step response
ax(4) = subplot(2, 3, 4, axisPropArray{:});
stem(x, cumsum(impresp), 'fill');
title('Step response', titlePropArray{:});
ylimArray = ylim;
if ylimArray(2) < -ylimArray(1) + 1;
ylimArray(2) = -ylimArray(1) + 1;
ylim(ylimArray);
end
xMin = []; xMax = [];
childrenArray = get(ax(4), 'Children');
for iChild =1:length(childrenArray)
xData = get(childrenArray(iChild), 'XData');
xMin = min([xMin min(xData)]);
xMax = max([xMax max(xData)]);
end
set(ax([1 4]), 'XLim', [xMin xMax]);
ylabel('Amplitude');
% Magnitude response
ax(2) = subplot(2, 3, 2, axisPropArray{:});
plot(f, abs(z));
title('Magnitude response', titlePropArray{:});
ylabel('Magnitude (linear)');
ax(5) = subplot(2, 3, 5, axisPropArray{:});
plot(f, 20 * log10(abs(z)));
title('Magnitude response', titlePropArray{:});
ylimArray = ylim;
if ylimArray(1) < -200
ylimArray(1) = -200;
ylim(ylimArray);
end
ylabel('Magnitude (dB)');
% Phase response
ax(3) = subplot(2, 3, 3, axisPropArray{:});
phaseresp = unwrap(angle(z));
if isZerophase % Correct delay for zero-phase FIR filter?
delay = -f / fs * groupdelay * 2 * pi;
phaseresp = phaseresp - delay;
phaseresp = mod(round(phaseresp / pi), 2) * pi; % Avoid rounding errors; linear-phase FIR only!
end
plot(f, phaseresp);
title('Phase response', titlePropArray{:});
ylabel('Phase (rad)');
% Formatting
xlabelArray = get(ax(1:5), 'XLabel');
if fs == 1
set([xlabelArray{[2 3 5]}], 'String', 'Normalized frequency (2 \pi rad / sample)');
else
set([xlabelArray{[2 3 5]}], 'String', 'Frequency (Hz)');
end
set([xlabelArray{[1 4]}], 'String', 'n (samples)');
set(ax([2 3 5]), 'XLim', [0 fs / 2]);
set(ax(1:5), 'ColorOrder', circshift(get(ax(1), 'ColorOrder'), -1));
end
|
github
|
lcnhappe/happe-master
|
qsublist.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/qsub/qsublist.m
| 8,076 |
utf_8
|
d9f7d454a9f8d6bc5991aa409e239c11
|
function retval = qsublist(cmd, jobid, pbsid)
% QSUBLIST is a helper function that is used to keep track of all the jobs in a
% submitted batch. specifically, it is used to maintain the mapping between the
% job identifier in the batch queueing system and MATLAB.
%
% Use as
% qsublist('list')
% qsublist('killall')
% qsublist('kill', jobid)
% qsublist('getjobid', pbsid)
% qsublist('getpbsid', jobid)
%
% The jobid is the identifier that is used within MATLAB for the file names,
% for example 'roboos_mentat242_p4376_b2_j453'.
%
% The pbsid is the identifier that is used within the batch queueing system,
% for example '15260.torque'.
%
% The following commands can be used by the end-user.
% 'list' display all jobs
% 'kill' kill a specific job, based on the jobid
% 'killall' kill all jobs
% 'getjobid' return the mathing jobid, given the pbsid
% 'getpbsid' return the mathing pbsid, given the jobid
%
% The following low-level commands are used by QSUBFEVAL and QSUBGET for job
% maintenance and monitoring.
% 'add'
% 'del'
% 'completed'
%
% See also QSUBCELLFUN, QSUBFEVAL, QSUBGET
% -----------------------------------------------------------------------
% Copyright (C) 2011-2015, 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$
% -----------------------------------------------------------------------
persistent list_jobid list_pbsid
% this function should stay in memory to keep the persistent variables for a long time
% locking it ensures that it does not accidentally get cleared if the m-file on disk gets updated
mlock
if ~isempty(list_jobid) && isequal(list_jobid, list_pbsid)
% it might also be system, but torque, sge, slurm and lsf will have other job identifiers
backend = 'local';
else
% use the environment variables to determine the backend
backend = defaultbackend;
end
if nargin<1
cmd = 'list';
end
if nargin<2
jobid = [];
end
if nargin<3
pbsid = [];
end
if isempty(jobid) && ~isempty(pbsid)
% get it from the persistent list
sel = find(strcmp(pbsid, list_pbsid));
if length(sel)==1
jobid = list_jobid{sel};
else
warning('cannot determine the jobid that corresponds to pbsid %s', pbsid);
end
end
if isempty(pbsid) && ~isempty(jobid)
% get it from the persistent list
sel = find(strcmp(jobid, list_jobid));
if length(sel)==1
pbsid = list_pbsid{sel};
else
warning('cannot determine the pbsid that corresponds to jobid %s', jobid);
end
end
switch cmd
case 'add'
% add it to the persistent lists
list_jobid{end+1} = jobid;
list_pbsid{end+1} = pbsid;
case 'del'
sel = strcmp(jobid, list_jobid);
% remove the job from the persistent lists
list_jobid(sel) = [];
list_pbsid(sel) = [];
case 'kill'
sel = strcmp(jobid, list_jobid);
if any(sel)
% remove it from the batch queue
switch backend
case 'torque'
system(sprintf('qdel %s', pbsid));
case 'sge'
system(sprintf('qdel %s', pbsid));
case 'slurm'
system(sprintf('scancel --name %s', jobid));
case 'lsf'
system(sprintf('bkill %s', pbsid));
case 'local'
% cleaning up of local jobs is not supported
case 'system'
% cleaning up of system jobs is not supported
end
% remove the corresponing files from the shared storage
system(sprintf('rm -f %s*', jobid));
% remove it from the persistent lists
list_jobid(sel) = [];
list_pbsid(sel) = [];
end
case 'killall'
if ~isempty(list_jobid)
% give an explicit warning, because chances are that the user will see messages from qdel
% about jobs that have just completed and hence cannot be deleted any more
fprintf('cleaning up all scheduled and running jobs, don''t worry if you see warnings from "qdel"\n');
end
% start at the end, work towards the begin of the list
for i=length(list_jobid):-1:1
qsublist('kill', list_jobid{i}, list_pbsid{i});
end
case 'completed'
% cmd = 'completed' returns whether the job is completed as a boolean
%
% It first determines whether the output files exist. If so, it might be that the
% batch queueing system is still writing to them, hence the next system-specific
% check also polls the status of the job. First checking the files and then the
% job status ensures that we don't saturate the torque server with job-status
% requests.
curPwd = getcustompwd();
outputfile = fullfile(curPwd, sprintf('%s_output.mat', jobid)); % if the job is aborted to a resource violation, there will not be an output file
logout = fullfile(curPwd, sprintf('%s.o*', jobid)); % note the wildcard in the file name
logerr = fullfile(curPwd, sprintf('%s.e*', jobid)); % note the wildcard in the file name
% poll the job status to confirm that the job truely completed
if isfile(logout) && isfile(logerr) && ~isempty(pbsid)
% only perform the more expensive check once the log files exist
switch backend
case 'torque'
[dum, jobstatus] = system(['qstat ' pbsid ' -f1 | grep job_state | grep -o "= [A-Z]" | grep -o "[A-Z]"']);
if isempty(jobstatus)
warning('cannot determine the status for pbsid %s', pbsid);
retval = 1;
else
retval = strcmp(strtrim(jobstatus) ,'C');
end
case 'lsf'
[dum, jobstatus] = system(['bjobs ' pbsid ' | awk ''NR==2'' | awk ''{print $3}'' ']);
retval = strcmp(strtrim(jobstatus), 'DONE');
case 'sge'
[dum, jobstatus] = system(['qstat -s z | grep ' pbsid ' | awk ''{print $5}''']);
retval = strcmp(strtrim(jobstatus), 'z') | strcmp(strtrim(jobstatus), 'qw');
case 'slurm'
% only return the status based on the presence of the output files
% FIXME it would be good to implement a proper check for slurm as well
retval = 1;
case {'local','system'}
% only return the status based on the presence of the output files
% there is no way polling the batch execution system
retval = 1;
end
elseif isfile(logout) && isfile(logerr) && isempty(pbsid)
% we cannot locate the job in the PBS/torque backend (weird, but it happens), hence we have to rely on the e and o files
% note that the mat file still might be missing, e.g. when the job was killed due to a resource violation
retval = 1;
else
retval = 0;
end
case 'list'
for i=1:length(list_jobid)
fprintf('%s %s\n', list_jobid{i}, list_pbsid{i});
end
case 'getjobid'
% return the mathing jobid, given the pbsid
retval = jobid;
case 'getpbsid'
% return the mathing pbsid, given the jobid
retval = pbsid;
otherwise
error('unsupported command (%s)', cmd);
end % switch
if length(list_jobid)~=length(list_pbsid)
error('jobid and pbsid lists are inconsistent');
end
if mislocked && isempty(list_jobid) && isempty(list_pbsid)
% it is now safe to unload the function and persistent variables from memory
munlock
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function that detects a file, even with a wildcard in the filename
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = isfile(name)
tmp = dir(name);
status = length(tmp)==1 && ~tmp.isdir;
|
github
|
lcnhappe/happe-master
|
qsubcellfun.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/qsub/qsubcellfun.m
| 19,264 |
utf_8
|
ed7719203341c9d8668d006d2ffc44bb
|
function varargout = qsubcellfun(fname, varargin)
% QSUBCELLFUN applies a function to each element of a cell-array. The
% function execution is done in parallel using the Torque, SGE, PBS or
% SLURM batch queue system.
%
% Use as
% argout = qsubcellfun(fname, x1, x2, ...)
%
% This function has a number of optional arguments that have to passed
% as key-value pairs at the end of the list of input arguments. All other
% input arguments (including other key-value pairs) will be passed to the
% function to be evaluated.
% UniformOutput = boolean (default = false)
% StopOnError = boolean (default = true)
% diary = string, can be 'always', 'never', 'warning', 'error' (default = 'error')
% timreq = number, the time in seconds required to run a single job
% timoverhead = number in seconds, how much time to allow MATLAB to start (default = 180 seconds)
% memreq = number, the memory in bytes required to run a single job
% memoverhead = number in bytes, how much memory to account for MATLAB itself (default = 1024^3, i.e. 1GB)
% stack = number, stack multiple jobs in a single qsub job (default = 'auto')
% backend = string, can be 'torque', 'sge', 'slurm', 'lsf', 'system', 'local' (default is automatic)
% batchid = string, to identify the jobs in the queue (default is user_host_pid_batch)
% compile = string, can be 'auto', 'yes', 'no' (default = 'no')
% queue = string, which queue to submit the job in (default is empty)
% options = string, additional options that will be passed to qsub/srun (default is empty)
% matlabcmd = string, the Linux command line to start MATLAB on the compute nodes (default is automatic
% display = 'yes' or 'no', whether the nodisplay option should be passed to MATLAB (default = 'no', meaning nodisplay)
% jvm = 'yes' or 'no', whether the nojvm option should be passed to MATLAB (default = 'yes', meaning with jvm)
% rerunable = 'yes' or 'no', whether the job can be restarted on a torque/maui/moab cluster (default = 'no')
%
% It is required to give an estimate of the time and memory requirements of
% the individual jobs. The memory requirement of the MATLAB executable
% itself will automatically be added, just as the time required to start
% up a new MATLAB process. If you don't know what the memory and time
% requirements of your job are, you can get an estimate for them using
% TIC/TOC and MEMTIC/MEMTOC around a single execution of one of the jobs in
% your interactive MATLAB session. You can also start with very large
% estimates, e.g. 4*1024^3 bytes for the memory (which is 4GB) and 28800
% seconds for the time (which is 8 hours) and then run a single job through
% qsubcellfun. When the job returns, it will print the memory and time it
% required.
%
% Example
% fname = 'power';
% x1 = {1, 2, 3, 4, 5};
% x2 = {2, 2, 2, 2, 2};
% y = qsubcellfun(fname, x1, x2, 'memreq', 1024^3, 'timreq', 300);
%
% Using the compile=yes or compile=auto option, you can compile your
% function into a stand-alone executable that can be executed on the cluster
% without requiring additional MATLAB licenses. You can also call the
% QSUBCOMPILE function prior to calling QSUBCELLFUN. If you plan multiple
% batches of the same function, compiling it prior to QSUBCELLFUN is more
% efficient. In that case you will have to delete the compiled executable
% yourself once you are done.
%
% In case you abort your call to qsubcellfun by pressing ctrl-c,
% the already submitted jobs will be canceled. Some small temporary
% files might remain in your working directory.
%
% To check the the status and healthy execution of the jobs on the Torque
% batch queuing system, you can use
% qstat
% qstat -an1
% qstat -Q
% comands on the linux command line. To delete jobs from the Torque batch
% queue and to abort already running jobs, you can use
% qdel <jobnumber>
% qdel all
%
% See also QSUBCOMPILE, QSUBFEVAL, CELLFUN, PEERCELLFUN, FEVAL, DFEVAL, DFEVALASYNC
% -----------------------------------------------------------------------
% Copyright (C) 2011-2015, 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
% remove the persistent lists with job and pbs identifiers
clear qsublist
stopwatch = tic;
% 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'
timreq = ft_getopt(optarg, 'timreq');
memreq = ft_getopt(optarg, 'memreq');
timoverhead = ft_getopt(optarg, 'timoverhead', 180); % allow some overhead to start up the MATLAB executable
memoverhead = ft_getopt(optarg, 'memoverhead', 1024*1024*1024); % allow some overhead for the MATLAB executable in memory
stack = ft_getopt(optarg, 'stack', 'auto'); % 'auto' or a number
compile = ft_getopt(optarg, 'compile', 'no'); % can be 'auto', 'yes' or 'no'
backend = ft_getopt(optarg, 'backend', []); % the default will be determined by qsubfeval
queue = ft_getopt(optarg, 'queue', []);
submitoptions = ft_getopt(optarg, 'options', []);
batch = ft_getopt(optarg, 'batch', getbatch()); % this is a number that is automatically incremented
batchid = ft_getopt(optarg, 'batchid', generatebatchid(batch)); % this is a string like user_host_pid_batch
display = ft_getopt(optarg, 'display', 'no');
matlabcmd = ft_getopt(optarg, 'matlabcmd', []);
jvm = ft_getopt(optarg, 'jvm', 'yes');
whichfunction = ft_getopt(optarg, 'whichfunction'); % the complete filename to the function, including path
rerunable = ft_getopt(optarg, 'rerunable'); % the default is determined in qsubfeval
% skip the optional key-value arguments
if ~isempty(optbeg)
varargin = varargin(1:(optbeg-1));
end
if isstruct(fname)
% the function has been compiled by qsubcompile
fcomp = fname;
% continue with the original function name
fname = fcomp.fname;
else
fcomp = [];
end
% determine which function it is
if isempty(whichfunction)
if ischar(fname)
whichfunction = which(fname);
elseif isa(fname, 'function_handle')
whichfunction = which(func2str(fname));
end
end
% if the first attempt failed, it might be due a function that is private to the calling function
if isempty(whichfunction)
s = dbstack('-completenames');
s = s(2); % qsubcellfun is the first, the calling function is the second
if ischar(fname)
whichfunction = which(fullfile(fileparts(s.file), 'private', fname));
elseif isa(fname, 'function_handle')
whichfunction = which(fullfile(fileparts(s.file), 'private', func2str(fname)));
end
if ~isempty(whichfunction)
warning('assuming %s as full function name', whichfunction);
end
clear s
end
% there are potentially errors to catch from the which() function
if isempty(whichfunction) && ischar(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});
% determine the number of MATLAB jobs to "stack" together into seperate qsub jobs
if isequal(stack, 'auto')
if ~isempty(timreq)
stack = floor(180/timreq);
else
stack = 1;
end
end
% ensure that the stacking is not higher than the number of jobs
stack = min(stack, numjob);
% give some feedback about the stacking
if stack>1
fprintf('stacking %d MATLAB jobs in each qsub job\n', stack);
end
% prepare some arrays that are used for bookkeeping
jobid = cell(1, numjob);
puttime = nan(1, numjob);
timused = nan(1, numjob);
memused = nan(1, numjob);
submitted = false(1, numjob);
collected = false(1, numjob);
submittime = inf(1, numjob);
collecttime = inf(1, numjob);
% it can be difficult to determine the number of output arguments
try
if isequal(fname, 'cellfun') || isequal(fname, @cellfun)
if isa(varargin{1}{1}, 'char') || isa(varargin{1}{1}, 'function_handle')
numargout = nargout(varargin{1}{1});
elseif isa(varargin{1}{1}, 'struct')
% the function to be executed has been compiled
fcomp = varargin{1}{1};
numargout = nargout(fcomp.fname);
end
else
numargout = nargout(fname);
end
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
% running a compiled version in parallel takes no MATLAB licenses
% auto compilation will be attempted if the total batch takes more than 30 minutes
if (strcmp(compile, 'auto') && (numjob*timreq/3600)>0.5) || istrue(compile)
try
% try to compile into a stand-allone application
fcomp = qsubcompile(fname, 'batch', batch, 'batchid', batchid);
catch
if istrue(compile)
% the error that was caught is critical
rethrow(lasterror);
elseif strcmp(compile, 'auto')
% compilation was only optional, the caught error is not critical
warning(lasterr);
end
end % try-catch
end % if compile
if stack>1
% combine multiple jobs in one, the idea is to use recursion like this
% a = {{@plus, @plus}, {{1}, {2}}, {{3}, {4}}}
% b = cellfun(@cellfun, a{:})
% these options will be passed to the recursive call after being modified further down
if ~any(strcmpi(optarg, 'timreq'))
optarg{end+1} = 'timreq';
optarg{end+1} = timreq;
end
if ~any(strcmpi(optarg, 'stack'))
optarg{end+1} = 'stack';
optarg{end+1} = stack;
end
if ~any(strcmpi(optarg, 'UniformOutput'))
optarg{end+1} = 'UniformOutput';
optarg{end+1} = UniformOutput;
end
if ~any(strcmpi(optarg, 'whichfunction'))
optarg{end+1} = 'whichfunction';
optarg{end+1} = whichfunction;
end
if ~any(strcmpi(optarg, 'compile'))
optarg{end+1} = 'compile';
optarg{end+1} = compile;
end
% update these settings for the recursive call
optarg{find(strcmpi(optarg, 'timreq'))+1} = timreq*stack;
optarg{find(strcmpi(optarg, 'stack'))+1} = 1;
optarg{find(strcmpi(optarg, 'UniformOutput'))+1} = false;
optarg{find(strcmpi(optarg, 'compile'))+1} = false;
% FIXME the partitioning can be further perfected
partition = floor((0:numjob-1)/stack)+1;
numpartition = partition(end);
stackargin = cell(1,numargin+3); % include the fname, uniformoutput, false
if istrue(compile)
if ischar(fcomp.fname)
% it should contain function handles, not strings
stackargin{1} = repmat({str2func(fcomp.fname)}, 1, numpartition);
else
stackargin{1} = repmat({fcomp.fname}, 1, numpartition);
end
else
if ischar(fname)
% it should contain function handles, not strings
stackargin{1} = repmat({str2func(fname)}, 1, numpartition);
else
stackargin{1} = repmat({fname}, 1, numpartition);
end
end
stackargin{end-1} = repmat({'uniformoutput'},1,numpartition); % uniformoutput
stackargin{end} = repmat({false},1,numpartition); % false
% reorganize the original input into the stacked format
for i=1:numargin
tmp = cell(1,numpartition);
for j=1:numpartition
tmp{j} = {varargin{i}{partition==j}};
end
stackargin{i+1} = tmp; % note that the first element is the fname
clear tmp
end
stackargout = cell(1,numargout);
[stackargout{:}] = qsubcellfun(@cellfun, stackargin{:}, optarg{:});
% reorganise the stacked output into the original format
for i=1:numargout
tmp = cell(size(varargin{1}));
for j=1:numpartition
tmp(partition==j) = stackargout{i}{j};
end
varargout{i} = tmp;
clear tmp
end
if numargout>0 && UniformOutput
[varargout{:}] = makeuniform(varargout{:});
end
return;
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
for submit=1:numjob
% redistribute the input arguments
argin = cell(1, numargin);
for j=1:numargin
argin{j} = varargin{j}{submit};
end
% submit the job
if ~isempty(fcomp)
% use the compiled version
[curjobid curputtime] = qsubfeval(fcomp, argin{:}, 'memreq', memreq, 'timreq', timreq, 'memoverhead', memoverhead, 'timoverhead', timoverhead, 'diary', diary, 'batch', batch, 'batchid', batchid, 'backend', backend, 'options', submitoptions, 'queue', queue, 'matlabcmd', matlabcmd, 'display', display, 'jvm', jvm, 'nargout', numargout, 'whichfunction', whichfunction, 'rerunable', rerunable);
else
% use the non-compiled version
[curjobid curputtime] = qsubfeval(fname, argin{:}, 'memreq', memreq, 'timreq', timreq, 'memoverhead', memoverhead, 'timoverhead', timoverhead, 'diary', diary, 'batch', batch, 'batchid', batchid, 'backend', backend, 'options', submitoptions, 'queue', queue, 'matlabcmd', matlabcmd, 'display', display, 'jvm', jvm, 'nargout', numargout, 'whichfunction', whichfunction, 'rerunable', rerunable);
end
% fprintf('submitted job %d\n', submit);
jobid{submit} = curjobid;
puttime(submit) = curputtime;
submitted(submit) = true;
submittime(submit) = toc(stopwatch);
clear curjobid curputtime
end % for
while (~all(collected))
% try to collect the jobs that have finished
for collect=find(~collected)
% this will return empty arguments if the job has not finished
ws = warning('off', 'FieldTrip:qsub:jobNotAvailable');
[argout, options] = qsubget(jobid{collect}, 'output', 'cell', 'diary', diary, 'StopOnError', StopOnError);
warning(ws);
if ~isempty(argout) || ~isempty(options)
% fprintf('collected job %d\n', collect);
collected(collect) = true;
collecttime(collect) = toc(stopwatch);
if isempty(argout) && StopOnError==false
% this happens if an error was detected in qsubget and StopOnError is false
% replace the output of the failed jobs with []
argout = repmat({[]}, 1, numargout);
end
% 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 % if
end % for
pausejava(0.1);
end % while
% 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
if numargout>0 && UniformOutput
[varargout{:}] = makeuniform(varargout{:});
end
% clean up the remains of the compilation
if (strcmp(compile, 'yes') || strcmp(compile, 'auto')) && ~isempty(fcomp)
% the extension might be .app or .exe or none
system(sprintf('rm -rf %s', fcomp.batchid)); % on Linux
system(sprintf('rm -rf %s.app', fcomp.batchid)); % on Apple OS X
system(sprintf('rm -rf %s.exe', fcomp.batchid)); % on Windows
system(sprintf('rm -rf run_%s*.sh', fcomp.batchid));
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)
warning('the job submission took more time than the actual execution');
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = makeuniform(varargin)
varargout = varargin;
numargout = numel(varargin);
% 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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% 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);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cleanupfun
% the qsublist function maintains a persistent list with all jobs
% request it to kill all the jobs and to cleanup all the files
qsublist('killall');
|
github
|
lcnhappe/happe-master
|
qsublisten.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/qsub/qsublisten.m
| 4,326 |
utf_8
|
6ac189cba48025bdbd36f682f9b258cc
|
function num = qsublisten(callback, varargin)
% QSUBLISTEN checks whether jobs, submitted by qsubfeval, have been
% completed. Whenever a job returns, it executes the provided callback function
% (should be a function handle), with the job ID as an input argument. Results
% can then be retrieved by calling QSUBGET. If a cell array is provided as
% a the 'filter' option (see below), the second input argument passed to the
% callback function will be an index into this cell array (to facilitate
% checking which job returned in the callback function).
%
% Note that this function is blocking; i.e., it only returns after a
% certain criterion has been met.
%
% Arguments can be supplied with key-value pairs:
% maxnum = maximum number of jobs to collect, function will return
% after this is reached. Default = Inf; so it is highly
% recommended you provide something here, since with
% maxnum=Inf the function will never return.
% filter = regular expression filter for job IDs to respond to.
% The default tests for jobs generated from the current
% MATLAB process. A cell array of strings can be
% provided; in that case, exact match is required.
% sleep = number of seconds to sleep between checks (default=0)
%
% This function returns the number of jobs that were collected and for
% which the callback function was called.
% Copyright (C) 2012, 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$
maxnum = ft_getopt(varargin, 'maxnum', Inf);
filter = ft_getopt(varargin, 'filter', [generatesessionid '.*']);
sleep = ft_getopt(varargin, 'sleep', 0);
if ischar(filter)
regexpFilt = 1;
elseif iscellstr(filter)
regexpFilt = 0;
else
error('filter should either be a regexp string or cell array of exact-match strings');
end
% keep track of which job IDs we have already recognized and fired the callback for
foundJobs = [];
curPwd = getcustompwd();
num = 0;
while (num < maxnum)
files = dir();
for k = 1:numel(files)
% preliminary filter to get just the qsub-specific output files
jobid = regexp(files(k).name, '^(.*)\.o.*$', 'tokens');
if ~isempty(jobid) && isempty(findstr(foundJobs, jobid{1}{1}))
jobid = jobid{1}{1};
% wait until not only the stdout file exists, but also the stderr and
% _output.mat. If we fire the callback before all three files are
% present, a subsequent call to qsubget will fail
outputfile = fullfile(curPwd, sprintf('%s_output.mat', jobid));
logerr = fullfile(curPwd, sprintf('%s.e*', jobid));
while ~exist(outputfile,'file') || ~isfile(logerr)
pausejava(0.01);
end
if (regexpFilt && ~isempty(regexp(jobid, filter, 'once'))) || (~regexpFilt && ~isempty(find(strcmp(jobid, filter))))
if (~regexpFilt && nargin(callback)>1)
% also provide an index into the filter array
callback(jobid, find(strcmp(jobid, filter)));
else
callback(jobid);
end
num = num+1;
foundJobs = [foundJobs '|' jobid];
end
end
end
if (sleep > 0)
pausejava(sleep);
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% helper function that detects a file, even with a wildcard in the filename
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function status = isfile(name)
tmp = dir(name);
status = length(tmp)==1 && ~tmp.isdir;
end
end
|
github
|
lcnhappe/happe-master
|
ft_platform_supports.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/qsub/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
|
lcnhappe/happe-master
|
ft_warning.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/qsub/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
|
lcnhappe/happe-master
|
ft_checkopt.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/qsub/private/ft_checkopt.m
| 5,085 |
utf_8
|
c8bce4359cc4a8be5591788b5984166d
|
function opt = ft_checkopt(opt, key, allowedtype, allowedval)
% FT_CHECKOPT does a validity test on the types and values of a configuration
% structure or cell-array with key-value pairs.
%
% Use as
% opt = ft_checkopt(opt, key)
% opt = ft_checkopt(opt, key, allowedtype)
% opt = ft_checkopt(opt, key, allowedtype, allowedval)
%
% For allowedtype you can specify a string or a cell-array with multiple
% strings. All the default MATLAB types can be specified, such as
% 'double'
% 'logical'
% 'char'
% 'single'
% 'float'
% 'int16'
% 'cell'
% 'struct'
% 'function_handle'
% Furthermore, the following custom types can be specified
% 'doublescalar'
% 'doublevector'
% 'doublebivector' i.e. [1 1] or [1 2]
% 'ascendingdoublevector' i.e. [1 2 3 4 5], but not [1 3 2 4 5]
% 'ascendingdoublebivector' i.e. [1 2], but not [2 1]
% 'doublematrix'
% 'numericscalar'
% 'numericvector'
% 'numericmatrix'
% 'charcell'
%
% For allowedval you can specify a single value or a cell-array
% with multiple values.
%
% This function will give an error or it returns the input configuration
% structure or cell-array without modifications. A match on any of the
% allowed types and any of the allowed values is sufficient to let this
% function pass.
%
% See also FT_GETOPT, FT_SETOPT
% Copyright (C) 2011-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$
if nargin<3
allowedtype = {};
end
if ~iscell(allowedtype)
allowedtype = {allowedtype};
end
if nargin<4
allowedval = {};
end
if ~iscell(allowedval)
allowedval = {allowedval};
end
% get the value that belongs to this key
val = ft_getopt(opt, key); % the default will be []
if isempty(val) && ~any(strcmp(allowedtype, 'empty'))
if isnan(ft_getopt(opt, key, nan))
error('the option "%s" was not specified or was empty', key);
end
end
% check that the type of the option is allowed
ok = isempty(allowedtype);
for i=1:length(allowedtype)
switch allowedtype{i}
case 'empty'
ok = isempty(val);
case 'charcell'
ok = isa(val, 'cell') && all(cellfun(@ischar, val(:)));
case 'doublescalar'
ok = isa(val, 'double') && numel(val)==1;
case 'doublevector'
ok = isa(val, 'double') && sum(size(val)>1)==1;
case 'ascendingdoublevector'
ok = isa(val,'double') && issorted(val);
case 'doublebivector'
ok = isa(val,'double') && sum(size(val)>1)==1 && length(val)==2;
case 'ascendingdoublebivector'
ok = isa(val,'double') && sum(size(val)>1)==1 && length(val)==2 && val(2)>val(1);
case 'doublematrix'
ok = isa(val, 'double') && sum(size(val)>1)>1;
case 'numericscalar'
ok = isnumeric(val) && numel(val)==1;
case 'numericvector'
ok = isnumeric(val) && sum(size(val)>1)==1;
case 'numericmatrix'
ok = isnumeric(val) && sum(size(val)>1)>1;
otherwise
ok = isa(val, allowedtype{i});
end
if ok
% no reason to do additional checks
break
end
end % for allowedtype
% construct a string that describes the type of the input variable
if isnumeric(val) && numel(val)==1
valtype = sprintf('%s scalar', class(val));
elseif isnumeric(val) && numel(val)==length(val)
valtype = sprintf('%s vector', class(val));
elseif isnumeric(val) && length(size(val))==2
valtype = sprintf('%s matrix', class(val));
elseif isnumeric(val)
valtype = sprintf('%s array', class(val));
else
valtype = class(val);
end
if ~ok
if length(allowedtype)==1
error('the type of the option "%s" is invalid, it should be "%s" instead of "%s"', key, allowedtype{1}, valtype);
else
error('the type of the option "%s" is invalid, it should be any of %s instead of "%s"', key, printcell(allowedtype), valtype);
end
end
% check that the type of the option is allowed
ok = isempty(allowedval);
for i=1:length(allowedval)
ok = isequal(val, allowedval{i});
if ok
% no reason to do additional checks
break
end
end % for allowedtype
if ~ok
error('the value of the option "%s" is invalid', key);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [s] = printcell(c)
if ~isempty(c)
s = sprintf('%s, ', c{:});
s = sprintf('{%s}', s(1:end-2));
else
s = '{}';
end
|
github
|
lcnhappe/happe-master
|
ft_statfun_roc.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/statfun/ft_statfun_roc.m
| 5,415 |
utf_8
|
a8e88fc1a733545abfe4d0608e309d53
|
function [s, cfg] = ft_statfun_roc(cfg, dat, design)
% FT_STATFUN_ROC computes the area under the curve (AUC) of the
% Receiver Operator Characteristic (ROC). This is a measure of the
% separability of the data divided over two conditions. The AUC can
% be used to test statistical significance of being able to predict
% on a single observation basis to which condition the observation
% belongs.
%
% Use this function by calling one of the high-level statistics
% functions as
% [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...)
% [stat] = ft_freqstatistics(cfg, freq1, freq2, ...)
% [stat] = ft_sourcestatistics(cfg, source1, source2, ...)
% with the following configuration option
% cfg.statistic = 'ft_statfun_roc'
%
% Configuration options that are relevant for this function are
% cfg.ivar = number, index into the design matrix with the independent variable
% cfg.logtransform = 'yes' or 'no' (default = 'no')
%
% Note that this statfun performs a one sided test in which condition "1"
% is assumed to be larger than condition "2".
% A low-level example for this function is
% a = randn(1,1000) + 1;
% b = randn(1,1000);
% design = [1*ones(1,1000) 2*ones(1,1000)];
% auc = ft_statfun_roc([], [a b], design);
% 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$
if ~isfield(cfg, 'ivar'), cfg.ivar = 1; end
if ~isfield(cfg, 'logtransform'), cfg.logtransform = 'no'; end
if strcmp(cfg.logtransform, 'yes'),
dat = log10(dat);
end
if isfield(cfg, 'numbins')
% this function was completely reimplemented on 21 July 2008 by Robert Oostenveld
% the old function had a positive bias in the AUC (i.e. the expected value was not 0.5)
error('the option cfg.numbins is not supported any more');
end
% start with a quick test to see whether there appear to be NaNs
if any(isnan(dat(1,:)))
% exclude trials that contain NaNs for all observed data points
sel = all(isnan(dat),1);
dat = dat(:,~sel);
design = design(:,~sel);
end
% logical indexing is faster than using find(...)
selA = (design(cfg.ivar,:)==1);
selB = (design(cfg.ivar,:)==2);
% select the data in the two classes
datA = dat(:, selA);
datB = dat(:, selB);
nobs = size(dat,1);
na = size(datA,2);
nb = size(datB,2);
auc = zeros(nobs, 1);
for k = 1:nobs
% compute the area under the curve for each channel/time/frequency
a = datA(k,:);
b = datB(k,:);
% to speed up the AUC, the critical value is determined by the actual
% values in class B, which also ensures a regular sampling of the False Alarms
b = sort(b);
ca = zeros(nb+1,1);
ib = zeros(nb+1,1);
% cb = zeros(nb+1,1);
% ia = zeros(nb+1,1);
for i=1:nb
% for the first approach below, the critval could also be choosen based on e.g. linspace(min,max,n)
critval = b(i);
% for each of the two distributions, determine the number of correct and incorrect assignments given the critical value
% ca(i) = sum(a>=critval);
% ib(i) = sum(b>=critval);
% cb(i) = sum(b<critval);
% ia(i) = sum(a<critval);
% this is a much faster approach, which works due to using the sorted values in b as the critical values
ca(i) = sum(a>=critval); % correct assignments to class A
ib(i) = nb-i+1; % incorrect assignments to class B
end
% add the end point
ca(end) = 0;
ib(end) = 0;
% cb(end) = nb;
% ia(end) = na;
hits = ca/na;
fa = ib/nb;
% the numerical integration is faster if the points are sorted
hits = fliplr(hits);
fa = fliplr(fa);
if false
% this part is optional and should only be used when exploring the data
figure
plot(fa, hits, '.-')
xlabel('false positive');
ylabel('true positive');
title('ROC-curve');
end
% compute the area under the curve using numerical integration
auc(k) = numint(fa, hits);
end
% return the area under the curve as the statistic of interest
s = struct('auc', auc);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% NUMINT computes a numerical integral of a set of sampled points using
% linear interpolation. Alugh the algorithm works for irregularly sampled points
% along the x-axis, it will perform best for regularly sampled points
%
% Use as
% z = numint(x, y)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function z = numint(x, y)
if ~all(diff(x)>=0)
% ensure that the points are sorted along the x-axis
[x, i] = sort(x);
y = y(i);
end
n = length(x);
z = 0;
for i=1:(n-1)
x0 = x(i);
y0 = y(i);
dx = x(i+1)-x(i);
dy = y(i+1)-y(i);
z = z + (y0 * dx) + (dy*dx/2);
end
|
github
|
lcnhappe/happe-master
|
ft_warning.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/statfun/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
|
lcnhappe/happe-master
|
ft_realtime_ouunpod.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/online_eeg/ft_realtime_ouunpod.m
| 20,299 |
utf_8
|
e7df0f8c5ebb142a8a4f339bb345f448
|
function ft_realtime_ouunpod(cfg)
% FT_REALTIME_OUUNPOD is an example realtime application for online power
% estimation and visualisation. It is designed for use with the OuUnPod, an
% OpenEEG based low cost EEG system with two channels, but in principle
% should work for any EEG or MEG system.
%
% Use as
% ft_realtime_ouunpod(cfg)
% with the following configuration options
% cfg.channel = cell-array, see FT_CHANNELSELECTION (default = 'all')
% cfg.foilim = [Flow Fhigh] (default = [1 45])
% cfg.blocksize = number, size of the blocks/chuncks that are processed (default = 1 second)
% cfg.bufferdata = whether to start on the 'first or 'last' data that is available (default = 'last')
%
% The source of the data is configured as
% cfg.dataset = string
% or alternatively to obtain more low-level control as
% cfg.datafile = string
% cfg.headerfile = string
% cfg.eventfile = string
% cfg.dataformat = string, default is determined automatic
% cfg.headerformat = string, default is determined automatic
% cfg.eventformat = string, default is determined automatic
%
% To stop the realtime function, you have to press Ctrl-C
%
% See also http://ouunpod.blogspot.com
% Copyright (C) 2008-2012, Robert Oostenveld
% Copyright (C) 2012-2014, Stephen Whitmarsh
%
% 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$
% set the default configuration options
if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end % default is detected automatically
if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end % default is detected automatically
if ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end % default is detected automatically
if ~isfield(cfg, 'blocksize'), cfg.blocksize = 0.05; end % stepsize, in seconds
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'bufferdata'), cfg.bufferdata = 'last'; end % first or last
if ~isfield(cfg, 'dataset'), cfg.dataset = 'buffer:\\localhost:1972'; end;
if ~isfield(cfg, 'foilim'), cfg.foilim = [1 45]; end
if ~isfield(cfg, 'windowsize'), cfg.windowsize = 2; end % length of sliding window, in seconds
if ~isfield(cfg, 'scale'), cfg.scale = 1; end % can be used to fix the calibration
if ~isfield(cfg, 'feedback'), cfg.feedback = 'no'; end % use neurofeedback with MIDI, yes or no
% translate dataset into datafile+headerfile
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes');
cfg = ft_checkconfig(cfg, 'required', {'datafile' 'headerfile'});
if strcmp(cfg.feedback, 'yes')
% setup MIDI, see http://en.wikipedia.org/wiki/General_MIDI
beatdrum = true;
m = midiOut; % Microsoft GS Wavetable Synth = device number 2
midiOut('O', 2); % o for output; 2 for device nr 2
midiOut('.', 1); % all off
midiOut('.', 2); % all off
% midiOut('P', 2, 20); organ
midiOut('P', 1, 53);
midiOut('P', 2, 53);
midiOut('+', 1, [64 65], [127 127]); % command, channelnr, key, velocity
midiOut('+', 2, [64 65 67], [127 127 127]); % command, channelnr, key, velocity
midiOut(uint8([175+1, 7, 0])); % change volume
midiOut(uint8([175+2, 7, 0]));
end % if MIDI feedback
% these are used by the GUI callbacks
clear global vaxis hdr chanindx
global vaxis hdr chanindx
% this specifies the vertical axis for each of the 6 subplots
vaxis = [
-300 300
-300 300
0 1000
0 1000
0 1000
0 1000
];
b2clicked = false;
% schemerlamp = Lamp('com9');
% ensure that the persistent variables related to caching are cleared
clear ft_read_header
% start by reading the header from the realtime buffer
hdr = ft_read_header(cfg.headerfile, 'cache', true, 'retry', true);
% define a subset of channels for reading
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chanindx = match_str(hdr.label, cfg.channel);
nchan = length(chanindx);
if nchan>2
chanindx = [1 2];
nchan = 2;
warning('exactly two channels should be selected');
end
if nchan<2
error('exactly two channels should be selected');
end
nhistory = 100;
% determine the size of blocks to process
blocksize = round(cfg.blocksize * hdr.Fs);
prevSample = 0;
count = 0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is the general BCI loop where realtime incoming data is handled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
left_thresh_ampl = -100;
left_thresh_time = nan; % [cfg.blockmem*blocksize-blocksize*4 cfg.blockmem*blocksize];
% FIXME these are hardcoded, but might be incompatible with the cfg and data settings
right_freq = [40 45];
right_offset = 0.5;
right_mult = 127/0.5;
TFR = zeros(2, (cfg.foilim(2)-cfg.foilim(1)+1), 100);
f1 = nan;
% these are handles used in drawing
u1=[]; u2=[]; u3=[]; u4=[]; u5=[]; u6=[]; p1=[]; p2=[]; p3=[]; p4=[]; p5=[]; p6=[]; c1=[]; c2=[]; b2=[];
while true
if isempty(f1) || ~ishandle(f1)
close all;
f1 = figure;
set(f1, 'resizeFcn', 'u1=[]; u2=[]; u3=[]; u4=[]; u5=[]; u6=[]; p1=[]; p2=[]; p3=[]; p4=[]; p5=[]; p6=[]; c1=[]; c2=[]; b2=[];');
u1=[]; u2=[]; u3=[]; u4=[]; u5=[]; u6=[]; p1=[]; p2=[]; p3=[]; p4=[]; p5=[]; p6=[]; c1=[]; c2=[]; b2=[];
end
% determine number of samples available in buffer
hdr = ft_read_header(cfg.headerfile, 'cache', true);
% see whether new samples are available
newsamples = (hdr.nSamples*hdr.nTrials-prevSample);
if newsamples>=blocksize && (hdr.nSamples*hdr.nTrials/hdr.Fs)>cfg.windowsize
% determine the samples to process
if strcmp(cfg.bufferdata, 'last')
begsample = hdr.nSamples*hdr.nTrials - round(cfg.windowsize*hdr.Fs) + 1;
endsample = hdr.nSamples*hdr.nTrials;
elseif strcmp(cfg.bufferdata, 'first')
begsample = prevSample+1;
endsample = prevSample+blocksize ;
else
error('unsupported value for cfg.bufferdata');
end
% remember up to where the data was read
prevSample = endsample;
count = count + 1;
fprintf('processing segment %d from sample %d to %d\n', count, begsample, endsample);
% read the data segment from buffer
dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false);
dat = cfg.scale * dat;
% construct a matching time axis
time = ((begsample:endsample)-1)/hdr.Fs;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% from here onward it is specific to the power estimation from the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% apply some preprocessing to the data
dat = ft_preproc_polyremoval(dat, 1);
dat = ft_preproc_highpassfilter(dat, hdr.Fs, 3, 1, 'but', 'twopass');
dat = ft_preproc_lowpassfilter (dat, hdr.Fs, 35, 3, 'but', 'twopass');
if hdr.Fs<11025
% sampling range is low, assume it is EEG
if hdr.Fs>110
% apply line noise filter
dat = ft_preproc_bandstopfilter(dat, hdr.Fs, [45 55], 4, 'but', 'twopass');
end
if hdr.Fs>230
% apply line noise filter
dat = ft_preproc_bandstopfilter(dat, hdr.Fs, [95 115], 4, 'but', 'twopass');
end
[spec, ntaper, freqoi] = ft_specest_mtmfft(dat, time, 'taper', 'dpss', 'tapsmofrq', 2, 'freqoi', cfg.foilim(1):cfg.foilim(2));
else
% sampling range is high, assume it is audio
[spec, ntaper, freqoi] = ft_specest_mtmfft(dat, time, 'taper', 'hanning', 'freqoi', cfg.foilim(1):cfg.foilim(2));
end
pow = squeeze(mean(abs(spec.^2), 1)); % compute power, average over tapers
if ~exist('TFR', 'var')
TFR = nan(length(chanindx), length(freqoi), nhistory);
end
TFR(:,:,1:nhistory-1) = TFR(:,:,2:nhistory);
TFR(:,:,end) = pow;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% translate channel 1 into a neurofeedback command
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(cfg.feedback, 'yes')
% compute the average power in the specified frequency range
fbeg = nearest(freqoi, cfg.feedback1.foilim(1));
fend = nearest(freqoi, cfg.feedback1.foilim(2));
value1 = mean(pow(1, fbeg:fend));
% scale the value between 0 and 1
historicalmean = mean(nanmean(TFR(1,fbeg:fend,:),3),2);
historicalmin = min (nanmin (TFR(1,fbeg:fend,:),3),2);
historicalmax = max (nanmax (TFR(1,fbeg:fend,:),3),2);
% the value can be larger than expected from the history
value1 = (value1 - historicalmin) ./ (historicalmax - historicalmin);
controlfunction(cfg.feedback1, value1);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% translate channel 2 into a neurofeedback command
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(cfg.feedback, 'yes')
% if value2>threshold
% controlfunction(cfg.feedback2);
% end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% make the GUI elements
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
try
if isempty(c1) || ~ishandle(c1)
pos = [0.25 0.95 0.1 0.05];
c1 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_channel, 'BackgroundColor', 'white');
set(c1, 'position', pos);
set(c1, 'string', chanindx(1));
set(c1, 'tag', 'c1');
end
if isempty(c2) || ~ishandle(c2)
pos = [0.70 0.95 0.1 0.05];
c2 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_channel, 'BackgroundColor', 'white');
set(c2, 'position', pos);
set(c2, 'string', chanindx(2));
set(c2, 'tag', 'c2');
end
if isempty(u1) || ~ishandle(u1)
pos = get(p1, 'position'); % link the position to the subplot
pos(1) = pos(1)-0.1;
pos(2) = pos(2)-0.05;
pos(3) = 0.1;
pos(4) = 0.05;
u1 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white');
set(u1, 'position', pos);
set(u1, 'string', num2str(vaxis(1,2)));
set(u1, 'tag', 'u1');
end
if isempty(u2) || ~ishandle(u2)
pos = get(p2, 'position'); % link the position to the subplot
pos(1) = pos(1)-0.1;
pos(2) = pos(2)-0.05;
pos(3) = 0.1;
pos(4) = 0.05;
u2 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white');
set(u2, 'position', pos);
set(u2, 'string', num2str(vaxis(2,2)));
set(u2, 'tag', 'u2');
end
if isempty(u3) || ~ishandle(u3)
pos = get(p3, 'position'); % link the position to the subplot
pos(1) = pos(1)-0.1;
pos(2) = pos(2)-0.05;
pos(3) = 0.1;
pos(4) = 0.05;
u3 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white');
set(u3, 'position', pos);
set(u3, 'position', pos);
set(u3, 'string', num2str(vaxis(3,2)));
set(u3, 'tag', 'u3');
end
if isempty(u4) || ~ishandle(u4)
pos = get(p4, 'position'); % link the position to the subplot
pos(1) = pos(1)-0.1;
pos(2) = pos(2)-0.05;
pos(3) = 0.1;
pos(4) = 0.05;
u4 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white');
set(u4, 'position', pos);
set(u4, 'string', num2str(vaxis(4,2)));
set(u4, 'tag', 'u4');
end
if isempty(u5) || ~ishandle(u5)
pos = get(p5, 'position'); % link the position to the subplot
pos(1) = pos(1)-0.1;
pos(2) = pos(2)-0.05;
pos(3) = 0.1;
pos(4) = 0.05;
u5 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white');
set(u5, 'position', pos);
set(u5, 'string', num2str(vaxis(5,2)));
set(u5, 'tag', 'u5');
end
if isempty(u6) || ~ishandle(u6)
pos = get(p6, 'position'); % link the position to the subplot
pos(1) = pos(1)-0.1;
pos(2) = pos(2)-0.05;
pos(3) = 0.1;
pos(4) = 0.05;
u6 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white');
set(u6, 'position', pos);
set(u6, 'string', num2str(vaxis(6,2)));
set(u6, 'tag', 'u6');
end
if isempty(b2) || ~ishandle(b2)
pos = [0.88 0.01 0.1 0.05];
b2 = uicontrol('style', 'pushbutton', 'units', 'normalized', 'callback', 'evalin(''caller'', ''b2clicked = true;'')');
set(b2, 'position', pos);
set(b2, 'string', 'quit');
set(b2, 'tag', 'b2');
end
end % try
if b2clicked
close all
return
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% visualize the data in 2*3 subplots
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
try
if isempty(p1) || ~ishandle(p1)
p1 = subplot(3, 2, 1);
else
subplot(p1);
h1 = plot(time, dat(1, :));
axis([min(time) max(time) vaxis(1, 1) vaxis(1, 2)]);
set(p1, 'XTickLabel', []);
ylabel('amplitude (uV)');
xlabel(sprintf('time: %d seconds', cfg.windowsize));
grid on
if strcmp(cfg.feedback, 'yes')
ax = axis;
line([ax(1) ax(2)], [left_thresh_ampl left_thresh_ampl], 'color', 'red');
line([ax(1) + left_thresh_time(1)/hdr.Fs ax(1) + left_thresh_time(1)/hdr.Fs], [-300 300], 'color', 'green');
line([ax(1) + left_thresh_time(2)/hdr.Fs ax(1) + left_thresh_time(2)/hdr.Fs], [-300 300], 'color', 'green');
end
end
if isempty(p2) || ~ishandle(p2)
p2 = subplot(3, 2, 2);
else
subplot(p2);
h2 = plot(time, dat(2, :));
axis([min(time) max(time) vaxis(2, 1) vaxis(2, 2)]);
set(p2, 'XTickLabel', []);
ylabel('amplitude (uV)');
xlabel(sprintf('time: %d seconds', cfg.windowsize));
grid on
end
if isempty(p3) || ~ishandle(p3)
p3 = subplot(3, 2, 3);
else
subplot(p3)
h3 = bar(1:length(freqoi), pow(1, :), 0.5);
% plot(pow(1).Frequencies, pow(1).Data);
% bar(pow(1).Frequencies, pow(1).Data);
axis([cfg.foilim(1) cfg.foilim(2) vaxis(3, 1) vaxis(3, 2)]);
% str = sprintf('time = %d s\n', round(mean(time)));
% title(str);
xlabel('frequency (Hz)');
ylabel('power');
end
if isempty(p4) || ~ishandle(p4)
p4 = subplot(3, 2, 4);
else
subplot(p4)
h4 = bar(1:length(freqoi), pow(2, :), 0.5);
% plot(pow(2).Frequencies, pow(2).Data);
% bar(pow(2).Frequencies, pow(2).Data);
ax = axis;
axis([cfg.foilim(1) cfg.foilim(2) vaxis(4, 1) vaxis(4, 2)]);
if strcmp(cfg.feedback, 'yes')
line([right_freq(1) right_freq(1)], [ax(3) ax(4)]);
line([right_freq(2) right_freq(2)], [ax(3) ax(4)]);
line([right_freq(1) right_freq(2)], [right_offset right_offset]);
end
xlabel('frequency (Hz)');
ylabel('power');
end
if isempty(p5) || ~ishandle(p5)
p5 = subplot(3, 2, 5);
else
subplot(p5)
h5 = surf(squeeze(TFR(1, :, :)));
axis([1 100 cfg.foilim(1) cfg.foilim(2) vaxis(5, 1) vaxis(5, 2)]);
view(110, 45);
xlabel(''); % this is the historical time
ylabel('frequency (Hz)');
zlabel('power');
set(p5, 'XTickLabel', []);
set(h5, 'EdgeColor', 'none');
shading interp
box off
end
if isempty(p6) || ~ishandle(p6)
p6 = subplot(3, 2, 6);
else
subplot(p6)
h6 = surf(squeeze(TFR(2, :, :)));
axis([1 100 cfg.foilim(1) cfg.foilim(2) vaxis(6, 1) vaxis(6, 2)]);
view(110, 45);
xlabel(''); % this is the historical time
ylabel('frequency (Hz)');
zlabel('power');
set(p6, 'XTickLabel', []);
set(h6, 'EdgeColor', 'none');
shading interp
box off
end
end % try
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% present MIDI feedback if the data exceeds the specified limits
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if strcmp(cfg.feedback, 'yes')
if left_thresh_ampl < 0
if min((dat(1, left_thresh_time(1):left_thresh_time(2)))) < left_thresh_ampl
if beatdrum == true
% midiOut('+', 10, 64, 127);
beatdrum = false;
else
% midiOut('+', 10, 31, 127);
beatdrum = true;
end
else
midiOut('.', 1);
end;
elseif max((dat(left_thresh_time(1):left_thresh_time(2)))) > left_thresh_ampl
if beatdrum == true
% midiOut('+', 10, 64, 127);
beatdrum = false;
else
% midiOut('+', 10, 31, 127);
beatdrum = true;
end
else
% midiOut('.', 1);
end;
% schemerlamp.setLevel(round(TFR(1, 60, end) / mean(TFR(1, 60, :)))*5);
volume_right = round((mean(TFR(2, right_freq, end)) - right_offset) * right_mult);
% midiOut(uint8([175+1, 7, volume_left]));
% midiOut(uint8([16*14+1-1, 0, volume_left])); % ptich
midiOut(uint8([175+2, 7, volume_right]));
midiOut(uint8([16*14+2-1, 0, volume_right])); % ptich
% schemerlamp.setLevel(9);
end % if MIDI feedback
% force an update of the figure
drawnow
end % if enough new samples
end % while true
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function update_channel(h, varargin)
global hdr chanindx
val = abs(str2num(get(h, 'string')));
val = max(1, min(val, hdr.nChans));
if ~isempty(val)
switch get(h, 'tag')
case 'c1'
chanindx(1) = val;
set(h, 'string', num2str(val));
case 'c2'
chanindx(2) = val;
set(h, 'string', num2str(val));
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function update_axis(h, varargin)
global vaxis
val = abs(str2num(get(h, 'string')));
if ~isempty(val)
switch get(h, 'tag')
case 'u1'
vaxis(1,:) = [-val val];
case 'u2'
vaxis(2,:) = [-val val];
case 'u3'
vaxis(3,:) = [0 val];
case 'u4'
vaxis(4,:) = [0 val];
case 'u5'
vaxis(5,:) = [0 val];
case 'u6'
vaxis(6,:) = [0 val];
end
end
|
github
|
lcnhappe/happe-master
|
ft_realtime_oddball.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/online_eeg/ft_realtime_oddball.m
| 13,163 |
utf_8
|
d5a3400a1168a9e53bccbb79f889bebb
|
function ft_realtime_oddball(cfg)
% FT_REALTIME_ODDBALL is an realtime application that computes an online
% average for a standard and deviant condition. The ERPs/ERFs are plotted,
% together with the difference as t-values. It should work both for EEG and
% MEG, as long as there are two triggers present
%
% Use as
% ft_realtime_oddball(cfg)
% with the following configuration options
% cfg.channel = cell-array, see FT_CHANNELSELECTION (default = 'all')
% cfg.trialfun = string with the trial function
%
% The source of the data is configured as
% cfg.dataset = string
% or alternatively to obtain more low-level control as
% cfg.datafile = string
% cfg.headerfile = string
% cfg.eventfile = string
% cfg.dataformat = string, default is determined automatic
% cfg.headerformat = string, default is determined automatic
% cfg.eventformat = string, default is determined automatic
%
% To stop the realtime function, you have to press Ctrl-C
% Copyright (C) 2008-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$
% set the default configuration options
if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end % default is detected automatically
if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end % default is detected automatically
if ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end % default is detected automatically
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'bufferdata'), cfg.bufferdata = 'last'; end % first or last
if ~isfield(cfg, 'jumptoeof'), cfg.jumptoeof = 'no'; end % jump to end of file at initialization
% translate dataset into datafile+headerfile
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes');
cfg = ft_checkconfig(cfg, 'required', {'datafile' 'headerfile'});
% these are used by the GUI callbacks
clear global chansel chanindx vaxis hdr
global chansel chanindx vaxis hdr
b1clicked = false;
b2clicked = false;
chansel = 1; % this is the subselection out of chanindx
vaxis = [
-6 6
-3 3
];
% ensure that the persistent variables related to caching are cleared
clear ft_read_header
% start by reading the header from the realtime buffer
hdr = ft_read_header(cfg.headerfile, 'cache', true);
% define a subset of channels for reading
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chanindx = match_str(hdr.label, cfg.channel);
nchan = length(chanindx);
if nchan==0
error('no channels were selected');
end
if strcmp(cfg.jumptoeof, 'yes')
prevSample = hdr.nSamples * hdr.nTrials;
else
prevSample = 0;
end
count = 0;
f1 = nan;
% initialize the timelock cell-array, each cell will hold the average in one condition
timelock = {};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is the general BCI loop where realtime incoming data is handled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while true
% determine latest header and event information
event = ft_read_event(cfg.dataset, 'minsample', prevSample+1); % only consider events that are later than the data processed sofar
hdr = ft_read_header(cfg.dataset, 'cache', true); % the trialfun might want to use this, but it is not required
cfg.event = event; % store it in the configuration, so that it can be passed on to the trialfun
cfg.hdr = hdr; % store it in the configuration, so that it can be passed on to the trialfun
% evaluate the trialfun, note that the trialfun should not re-read the events and header
fprintf('evaluating ''%s'' based on %d events\n', cfg.trialfun, length(event));
trl = feval(cfg.trialfun, cfg);
% the code below assumes that the 4th column of the trl matrix contains the condition index
% set the default condition to one if no condition index was given
if size(trl,1)>0 && size(trl,2)<4
trl(:,4) = 1;
end
fprintf('processing %d trials\n', size(trl,1));
for trllop=1:size(trl,1)
begsample = trl(trllop,1);
endsample = trl(trllop,2);
offset = trl(trllop,3);
condition = trl(trllop,4); % it is important that the 4th column is returned with the condition number
% remember up to where the data was read
prevSample = endsample;
count = count + 1;
fprintf('processing segment %d from sample %d to %d, condition = %d\n', count, begsample, endsample, condition);
while (hdr.nSamples*hdr.nTrials < endsample)
% wait until all data up to the endsample has arrived
hdr = ft_read_header(cfg.headerfile, 'cache', true);
end
% read the selected data segment from the buffer
dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% from here onward it is specific to the processing of the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% apply some preprocessing options
dat = ft_preproc_lowpassfilter(dat, hdr.Fs, 45);
dat = ft_preproc_baselinecorrect(dat, 1, -offset);
% put the data in a fieldtrip-like raw structure
data.trial{1} = dat;
data.time{1} = offset2time(offset, hdr.Fs, endsample-begsample+1);
data.label = hdr.label(chanindx);
data.hdr = hdr;
data.fsample = hdr.Fs;
if length(timelock)<condition || isempty(timelock{condition})
% this is the first occurence of this condition, initialize an empty timelock structure
timelock{condition}.label = data.label;
timelock{condition}.time = data.time{1};
timelock{condition}.avg = [];
timelock{condition}.var = [];
timelock{condition}.dimord = 'chan_time';
nchans = size(data.trial{1}, 1);
nsamples = size(data.trial{1}, 2);
% the following elements are for the cumulative computation
timelock{condition}.n = 0; % number of trials
timelock{condition}.s = zeros(nchans, nsamples); % sum
timelock{condition}.ss = zeros(nchans, nsamples); % sum of squares
end
% add the new data to the accumulated data
timelock{condition}.n = timelock{condition}.n + 1;
timelock{condition}.s = timelock{condition}.s + data.trial{1};
timelock{condition}.ss = timelock{condition}.ss + data.trial{1}.^2;
% compute the average and variance on the fly
timelock{condition}.avg = timelock{condition}.s ./ timelock{condition}.n;
timelock{condition}.var = (timelock{condition}.ss - (timelock{condition}.s.^2)./timelock{condition}.n) ./ (timelock{condition}.n-1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% from here onward the GUI is constructed
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
try
if ~ishandle(f1)
close all;
f1 = figure;
clear u1 u2
clear p1 p2
clear c1
set(f1, 'resizeFcn', 'clear u1 u2 p1 p2 c1 b1 b2')
end
if ~exist('p1')
p1 = subplot(2,1,1);
end
if ~exist('p2')
p2 = subplot(2,1,2);
end
if ~exist('c1')
pos = [0.75 0.93 0.1 0.05];
c1 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_channel, 'BackgroundColor', 'white');
set(c1, 'position', pos);
set(c1, 'string', chanindx(chansel));
set(c1, 'tag', 'c1');
end
if ~exist('u1')
pos = get(p1, 'position'); % link the position to the subplot
pos(1) = pos(1)-0.1;
pos(2) = pos(2)-0.05;
pos(3) = 0.1;
pos(4) = 0.05;
u1 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white');
set(u1, 'position', pos);
set(u1, 'string', num2str(vaxis(1,2)));
set(u1, 'tag', 'u1');
end
if ~exist('u2')
pos = get(p2, 'position'); % link the position to the subplot
pos(1) = pos(1)-0.1;
pos(2) = pos(2)-0.05;
pos(3) = 0.1;
pos(4) = 0.05;
u2 = uicontrol('style', 'edit', 'units', 'normalized', 'callback', @update_axis, 'BackgroundColor', 'white');
set(u2, 'position', pos);
set(u2, 'string', num2str(vaxis(2,2)));
set(u2, 'tag', 'u1');
end
if ~exist('b1')
pos = [0.75 0.01 0.1 0.05];
b1 = uicontrol('style', 'pushbutton', 'units', 'normalized', 'callback', 'evalin(''caller'', ''b1clicked = true'')');
set(b1, 'position', pos);
set(b1, 'string', 'reset');
set(b1, 'tag', 'b1');
end
if ~exist('b2')
pos = [0.88 0.01 0.1 0.05];
b2 = uicontrol('style', 'pushbutton', 'units', 'normalized', 'callback', 'evalin(''caller'', ''b2clicked = true'')');
set(b2, 'position', pos);
set(b2, 'string', 'quit');
set(b2, 'tag', 'b2');
end
end % try
if b1clicked
timelock = {};
try, cla(p1); end
try, cla(p2); end
b1clicked = false;
end
if b2clicked
return
b2clicked = false;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% from here onward the data is plotted
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
try
if length(timelock)>1
sel = ~cellfun(@isempty, timelock);
sel = find(sel, 2, 'first');
if length(sel)~=2
break
end
standard = timelock{sel(1)};
deviant = timelock{sel(2)};
tscore = (deviant.avg - standard.avg) ./ sqrt(standard.var./standard.n + deviant.var./deviant.n);
time = standard.time; % deviant is the same
if exist('p1')
subplot(p1)
cla
hold on
hs = plot(time, standard.avg(chansel,:), 'b-');
hd = plot(time, deviant.avg(chansel,:), 'r-');
set(hs, 'lineWidth', 1.5)
set(hd, 'lineWidth', 1.5)
grid on
axis([time(1) time(end) vaxis(1,1) vaxis(1,2)])
legend(sprintf('standard (n=%d)', standard.n), sprintf('deviant (n=%d)', deviant.n));
xlabel('time (s)');
ylabel('amplitude (uV)');
title(sprintf('channel "%s"', hdr.label{chanindx(chansel)}));
end
if exist('p2')
subplot(p2)
cla
hold on
ht = plot(time, tscore(chansel,:), 'g-');
set(ht, 'lineWidth', 1.5)
grid on
axis([time(1) time(end) vaxis(2,1) vaxis(2,2)])
legend('difference');
xlabel('time (s)');
ylabel('t-score (a.u.)');
end
end % two conditions are available
end % try
% force matlab to redraw the figure
drawnow
end % looping over new trials
end % while true
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [time] = offset2time(offset, fsample, nsamples)
offset = double(offset);
nsamples = double(nsamples);
time = (offset + (0:(nsamples-1)))/fsample;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function update_channel(h, varargin)
global chansel chanindx hdr
val = abs(str2num(get(h, 'string')));
val = max(1, min(val, length(chanindx)));
if ~isempty(val)
switch get(h, 'tag')
case 'c1'
chansel = val;
set(h, 'string', num2str(val));
fprintf('switching to channel "%s"', hdr.label{chanindx(chansel)});
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function update_axis(h, varargin)
global vaxis
val = abs(str2num(get(h, 'string')));
if ~isempty(val)
switch get(h, 'tag')
case 'u1'
vaxis(1,:) = [-val val];
case 'u2'
vaxis(2,:) = [-val val];
end
end
|
github
|
lcnhappe/happe-master
|
ft_omri_info_from_header.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/online_mri/ft_omri_info_from_header.m
| 4,361 |
utf_8
|
97589ff2ee8f9fa7ee376b4b628de647
|
function S = ft_omri_info_from_header(hdr)
% function S = ft_omri_info_from_header(hdr)
%
% Convenience function to retrieve most important MR information
% from a given header (H) as retrieved from a FieldTrip buffer.
% Will look at both NIFTI-1 and SiemensAP fields, if present, and
% give preference to SiemensAP info.
%
% Returns empty array if no information could be found.
% Copyright (C) 2012, Stefan Klanke
%
% 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$
SNif = [];
SSap = [];
if isfield(hdr,'nifti_1')
try
SNif = mri_info_from_nifti(hdr.nifti_1);
catch
warning('Errors occured while inspecting NIFTI-1 header.');
end
end
if isfield(hdr,'siemensap')
try
SSap = mri_info_from_sap(hdr.siemensap);
catch
warning('Errors occured while inspecting SiemensAP header.');
end
end
if ~isempty(SSap)
S = SSap;
if ~isempty(SNif)
if ~isequal(SNif.voxels,SSap.voxels)
warning('Conflicting information in NIFTI and SiemensAP - trusting SiemensAP...');
end
S.mat0 = SNif.mat0;
end
else
if ~isempty(SNif)
S = SNif;
else
S = [];
end
end
function S = mri_info_from_nifti(NH)
S.vx = double(NH.dim(1));
S.vy = double(NH.dim(2));
S.vz = double(NH.dim(3));
S.voxels = [S.vx S.vy S.vz];
S.voxdim = double(NH.pixdim(1:3));
S.size = S.voxels .* S.voxdim;
VoxToWorld = double([NH.srow_x; NH.srow_y; NH.srow_z]);
M = VoxToWorld(1:3,1:3);
P = VoxToWorld(1:3,4);
% correct Mat0 in the same way SPM does (voxel index starts at 1)
S.mat0 = [M (P-M*[1;1;1]); 0 0 0 1];
S.numEchos = 1; % can't detect this from NIFTI :-(
switch NH.slice_code
% Long-term TODO: look at slice_start and slice_end for padded slices
case 1 % NIFTI_SLICE_SEQ_INC
inds = 1:S.vz;
case 2 % NIFTI_SLICE_SEQ_DEC
inds = S.vz:-1:1;
case 3 % NIFTI_SLICE_ALT_INC
inds = [(1:2:S.vz) (2:2:S.vz)];
case 4 % NIFTI_SLICE_ALT_DEC
inds = [(S.vz:-2:1) ((S.vz-1):-2:1)];
case 5 % NIFTI_SLICE_ALT_INC2
inds = [(2:2:S.vz) (1:2:S.vz)];
case 6 % NIFTI_SLICE_ALT_DEC2
inds = [((S.vz-1):-2:1) (S.vz:-2:1)];
otherwise
warning('Unrecognized slice order - using default');
inds = 1:S.vz;
end
if NH.slice_duration > 0
S.TR = double(NH.slice_duration * S.vz);
% first set up linear
S.deltaT = (0:(S.vz-1))*double(NH.slice_duration)
% then re-shuffle
S.deltaT(inds) = S.deltaT;
else
% what can we do here?
S.TR = 2;
S.deltaT = (0:(S.vz-1))*S.TR/S.vz;
S.deltaT(inds) = S.deltaT;
end
function S = mri_info_from_sap(SP)
phaseFOV = SP.sSliceArray.asSlice{1}.dPhaseFOV;
readoutFOV = SP.sSliceArray.asSlice{1}.dReadoutFOV;
sliceThick = SP.sSliceArray.asSlice{1}.dThickness;
distFactor = SP.sGroupArray.asGroup{1}.dDistFact;
S.vx = double(SP.sKSpace.lBaseResolution);
S.vy = S.vx * phaseFOV / readoutFOV;
S.vz = double(SP.sSliceArray.lSize);
S.voxels = [S.vx S.vy S.vz];
% this only takes care of the scaling, not the proper orientation
sx = readoutFOV/S.vx;
sy = phaseFOV/S.vy; % should always be == sx
sz = sliceThick * (1.0 + distFactor);
S.size = [readoutFOV phaseFOV S.vz*sz];
S.mat0 = [sx 0 0 0; 0 sy 0 0; 0 0 sz 0; 0 0 0 1];
S.voxdim = [sx sy sz];
S.numEchos = double(SP.lContrasts);
S.TR = double(SP.alTR) * 1e-6; % originally in microseconds
switch SP.sSliceArray.ucMode
case 1 % == NIFTI_SLICE_SEQ_INC
inds = 1:S.vz;
case 2 % == NIFTI_SLICE_SEQ_DEC
inds = S.vz:-1:1;
case 4 % odd:ALT_INC or even:ALT_INC2
if mod(S.vz,2) == 1
inds = [(1:2:S.vz) (2:2:S.vz)];
else
inds = [(2:2:S.vz) (1:2:S.vz)];
end
otherwise
warning('Unrecognized slice order - using default');
inds = 1:S.vz;
end
% first set up linear
S.deltaT = (0:(S.vz-1))*S.TR/S.vz
% then re-shuffle
S.deltaT(inds) = S.deltaT;
|
github
|
lcnhappe/happe-master
|
encode_nifti1.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/online_mri/private/encode_nifti1.m
| 4,870 |
utf_8
|
9cf92a03587c511a5cec2c8c76a3c2c3
|
function blob = encode_nifti1(H)
%function blob = encode_nifti1(H)
%
% Encodes a NIFTI-1 header (=> raw 348 bytes (uint8)) from a Matlab structure
% that matches the C struct defined in nifti1.h.
%
% WARNING: This function currently ignores endianness !!!
% (C) 2010 S.Klanke
blob = uint8(zeros(1,348));
if ~isstruct(H)
error 'Input must be a structure';
end
% see nift1.h for information on structure
sizeof_hdr = int32(348);
blob(1:4) = typecast(sizeof_hdr, 'uint8');
blob = setString(blob, 5, 14, H, 'data_type');
blob = setString(blob, 15, 32, H, 'db_name');
blob = setInt32( blob, 33, 36, H, 'extents');
blob = setInt16( blob, 37, 38, H, 'session_error');
blob = setInt8( blob, 39, 39, H, 'regular');
blob = setInt8( blob, 40, 40, H, 'dim_info');
dim = int16(H.dim(:)');
ndim = numel(dim);
if ndim<1 || ndim>7
error 'Field "dim" must have 1..7 elements';
end
dim = [int16(ndim) dim];
blob(41:(42+2*ndim)) = typecast(dim,'uint8');
blob = setSingle(blob, 57, 60, H, 'intent_p1');
blob = setSingle(blob, 61, 64, H, 'intent_p2');
blob = setSingle(blob, 65, 68, H, 'intent_p3');
blob = setInt16( blob, 69, 70, H, 'intent_code');
blob = setInt16( blob, 71, 72, H, 'datatype');
blob = setInt16( blob, 73, 74, H, 'bitpix');
blob = setInt16( blob, 75, 76, H, 'slice_start');
blob = setSingle(blob, 77, 80, H, 'qfac');
if isfield(H,'pixdim')
pixdim = single(H.pixdim(:)');
ndim = numel(pixdim);
if ndim<1 || ndim>7
error 'Field "pixdim" must have 1..7 elements';
end
blob(81:(80+4*ndim)) = typecast(pixdim,'uint8');
end
blob = setSingle(blob, 109, 112, H, 'vox_offset');
blob = setSingle(blob, 113, 116, H, 'scl_scope');
blob = setSingle(blob, 117, 120, H, 'scl_inter');
blob = setInt16( blob, 121, 122, H, 'slice_end');
blob = setInt8( blob, 123, 123, H, 'slice_code');
blob = setInt8( blob, 124, 124, H, 'xyzt_units');
blob = setSingle(blob, 125, 128, H, 'cal_max');
blob = setSingle(blob, 129, 132, H, 'cal_min');
blob = setSingle(blob, 133, 136, H, 'slice_duration');
blob = setSingle(blob, 137, 140, H, 'toffset');
blob = setInt32( blob, 141, 144, H, 'glmax');
blob = setInt32( blob, 145, 148, H, 'glmin');
blob = setString(blob, 149, 228, H, 'descrip');
blob = setString(blob, 229, 252, H, 'aux_file');
blob = setInt16( blob, 253, 254, H, 'qform_code');
blob = setInt16( blob, 255, 256, H, 'sform_code');
blob = setSingle(blob, 257, 260, H, 'quatern_b');
blob = setSingle(blob, 261, 264, H, 'quatern_c');
blob = setSingle(blob, 265, 268, H, 'quatern_d');
blob = setSingle(blob, 269, 272, H, 'quatern_x');
blob = setSingle(blob, 273, 276, H, 'quatern_y');
blob = setSingle(blob, 277, 280, H, 'quatern_z');
blob = setSingle(blob, 281, 296, H, 'srow_x');
blob = setSingle(blob, 297, 312, H, 'srow_y');
blob = setSingle(blob, 313, 328, H, 'srow_z');
blob = setString(blob, 329, 344, H, 'intent_name');
if ~isfield(H,'magic')
blob(345:347) = uint8('ni1');
else
blob = setString(blob, 345, 347, H, 'magic');
end
function blob = setString(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = getfield(H, fieldname);
ne = numel(F);
mx = endidx - begidx +1;
if ne > 0
if ~ischar(F) || ne > mx
errmsg = sprintf('Field "data_type" must be a string of maximally %i characters.', mx);
error(errmsg);
end
blob(begidx:(begidx+ne-1)) = uint8(F(:)');
end
% set 32-bit integers (check #elements)
function blob = setInt32(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = int32(getfield(H, fieldname));
ne = numel(F);
sp = (endidx - begidx +1) / 4;
if ne~=sp
errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp);
error(errmsg);
end
blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8');
% set 16-bit integers (check #elements)
function blob = setInt16(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = int16(getfield(H, fieldname));
ne = numel(F);
sp = (endidx - begidx +1) / 2;
if ne~=sp
errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp);
error(errmsg);
end
blob(begidx:(begidx+2*ne-1)) = typecast(F(:)', 'uint8');
% just 8-bit integers (check #elements)
function blob = setInt8(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = int8(getfield(H, fieldname));
ne = numel(F);
sp = (endidx - begidx +1);
if ne~=sp
errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp);
error(errmsg);
end
blob(begidx:(begidx+ne-1)) = typecast(F(:)', 'uint8');
% single precision floats
function blob = setSingle(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = single(getfield(H, fieldname));
ne = numel(F);
sp = (endidx - begidx +1) / 4;
if ne~=sp
errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp);
error(errmsg);
end
blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8');
|
github
|
lcnhappe/happe-master
|
reslice_vol.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/online_mri/private/reslice_vol.m
| 942 |
utf_8
|
081ab7897d7a4e33ecb3ade31f6263c0
|
function [Va, Mask] = reslice_vol(Vo, M, interp)
% function [Va, Mask] = reslice_vol(Vo, M, interp)
% Ripped out of SPM 8 and modified (2010, S.Klanke)
dim = size(Vo);
wrap = [1;1;0];
d = [interp*[1;1;1] wrap];
[x1,x2] = ndgrid(1:dim(1), 1:dim(2));
C = spm_bsplinc(Vo, d);
Va = zeros(dim);
Mask = zeros(dim);
for x3 = 1:dim(3)
[msk_x3,y1,y2,y3] = getmask(M,x1,x2,x3,dim,wrap);
Mask(:,:,x3) = msk_x3;
Va(:,:,x3) = spm_bsplins(C, y1,y2,y3, d);
end
return;
function [Mask,y1,y2,y3] = getmask(M,x1,x2,x3,dim,wrp)
tiny = 5e-2; % From spm_vol_utils.c
y1 = M(1,1)*x1+M(1,2)*x2+(M(1,3)*x3+M(1,4));
y2 = M(2,1)*x1+M(2,2)*x2+(M(2,3)*x3+M(2,4));
y3 = M(3,1)*x1+M(3,2)*x2+(M(3,3)*x3+M(3,4));
Mask = true(size(y1));
if ~wrp(1), Mask = Mask & (y1 >= (1-tiny) & y1 <= (dim(1)+tiny)); end;
if ~wrp(2), Mask = Mask & (y2 >= (1-tiny) & y2 <= (dim(2)+tiny)); end;
if ~wrp(3), Mask = Mask & (y3 >= (1-tiny) & y3 <= (dim(3)+tiny)); end;
return;
|
github
|
lcnhappe/happe-master
|
ft_realtime_signalviewer.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/example/ft_realtime_signalviewer.m
| 9,980 |
utf_8
|
80b047f2f1e4ef4fbb3c7f3a8124588a
|
function ft_realtime_signalviewer(cfg)
% FT_REALTIME_SIGNALVIEWER is an example realtime application for online viewing of
% the data. It should work both for EEG and MEG.
%
% Use as
% ft_realtime_signalviewer(cfg)
% with the following configuration options
% cfg.blocksize = number, size of the blocks/chuncks that are processed (default = 1 second)
% cfg.channel = cell-array, see FT_CHANNELSELECTION (default = 'all')
% cfg.jumptoeof = whether to skip to the end of the stream/file at startup (default = 'yes')
% cfg.bufferdata = whether to start on the 'first or 'last' data that is available (default = 'first')
% cfg.readevent = whether or not to copy events (default = 'no')
% cfg.demean = 'no' or 'yes', whether to apply baseline correction (default = 'yes')
%
% The source of the data is configured as
% cfg.dataset = string
% or alternatively to obtain more low-level control as
% cfg.datafile = string
% cfg.headerfile = string
% cfg.eventfile = string
% cfg.dataformat = string, default is determined automatic
% cfg.headerformat = string, default is determined automatic
% cfg.eventformat = string, default is determined automatic
%
% Some notes about skipping data and catching up with the data stream:
%
% cfg.jumptoeof='yes' causes the realtime function to jump to the end when the
% function _starts_. It causes all data acquired prior to starting the realtime
% function to be skipped.
%
% cfg.bufferdata='last' causes the realtime function to jump to the last available data
% while _running_. If the realtime loop is not fast enough, it causes some data to be
% dropped.
%
% If you want to skip all data that was acquired before you start the RT function,
% but don't want to miss any data that was acquired while the realtime function is
% started, then you should use jumptoeof=yes and bufferdata=first. If you want to
% analyse data from a file, then you should use jumptoeof=no and bufferdata=first.
%
% To stop this realtime function, you have to press Ctrl-C
% 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$
% set the default configuration options
cfg.dataformat = ft_getopt(cfg, 'dataformat', []); % default is detected automatically
cfg.headerformat = ft_getopt(cfg, 'headerformat', []); % default is detected automatically
cfg.eventformat = ft_getopt(cfg, 'eventformat', []); % default is detected automatically
cfg.blocksize = ft_getopt(cfg, 'blocksize', 1); % in seconds
cfg.overlap = ft_getopt(cfg, 'overlap', 0); % in seconds
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.readevent = ft_getopt(cfg, 'readevent', 'no'); % capture events?
cfg.bufferdata = ft_getopt(cfg, 'bufferdata', 'first'); % first or last
cfg.jumptoeof = ft_getopt(cfg, 'jumptoeof', 'yes'); % jump to end of file at initialization
cfg.demean = ft_getopt(cfg, 'demean', 'yes'); % baseline correction
cfg.detrend = ft_getopt(cfg, 'detrend', 'no');
cfg.olfilter = ft_getopt(cfg, 'olfilter', 'no'); % continuous online filter
cfg.olfiltord = ft_getopt(cfg, 'olfiltord', 4);
cfg.olfreq = ft_getopt(cfg, 'olfreq', [2 45]);
cfg.offset = ft_getopt(cfg, 'offset', []); % in units of the data, e.g. uV for the OpenBCI board
cfg.dftfilter = ft_getopt(cfg, 'dftfilter', 'no');
cfg.dftfreq = ft_getopt(cfg, 'dftfreq', [50 100 150]);
if ~isfield(cfg, 'dataset') && ~isfield(cfg, 'header') && ~isfield(cfg, 'datafile')
cfg.dataset = 'buffer://localhost:1972';
end
% translate dataset into datafile+headerfile
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes');
cfg = ft_checkconfig(cfg, 'required', {'datafile' 'headerfile'});
% ensure that the persistent variables related to caching are cleared
clear ft_read_header
% start by reading the header from the realtime buffer
hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat, 'cache', true, 'retry', true);
% define a subset of channels for reading
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chanindx = match_str(hdr.label, cfg.channel);
nchan = length(chanindx);
if nchan==0
error('no channels were selected');
end
if numel(cfg.offset)==0
% it will be determined on the first data segment
elseif numel(cfg.offset)==1
cfg.offset = repmat(cfg.offset, size(cfg.channel));
end
% determine the size of blocks to process
blocksize = round(cfg.blocksize * hdr.Fs);
overlap = round(cfg.overlap*hdr.Fs);
if strcmp(cfg.jumptoeof, 'yes')
prevSample = hdr.nSamples * hdr.nTrials;
else
prevSample = 0;
end
count = 0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is the general BCI loop where realtime incoming data is handled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while true
% determine the samples to process
if strcmp(cfg.bufferdata, 'last')
% determine number of samples available in buffer
hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat, 'cache', true);
begsample = hdr.nSamples*hdr.nTrials - blocksize + 1;
endsample = hdr.nSamples*hdr.nTrials;
elseif strcmp(cfg.bufferdata, 'first')
begsample = prevSample+1;
endsample = prevSample+blocksize ;
else
error('unsupported value for cfg.bufferdata');
end
% this allows overlapping data segments
if overlap && (begsample>overlap)
begsample = begsample - overlap;
endsample = endsample - overlap;
end
% remember up to where the data was read
prevSample = endsample;
count = count + 1;
fprintf('processing segment %d from sample %d to %d\n', count, begsample, endsample);
% read data segment from buffer
dat = ft_read_data(cfg.datafile, 'header', hdr, 'dataformat', cfg.dataformat, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false, 'blocking', true);
% make a matching time axis
time = ((begsample:endsample)-1)/hdr.Fs;
% it only makes sense to read those events associated with the currently processed data
if strcmp(cfg.readevent, 'yes')
evt = ft_read_event(cfg.eventfile, 'header', hdr, 'minsample', begsample, 'maxsample', endsample);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% from here onward it is specific to the display of the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert the data to a FieldTrip-like raw structure
% data = [];
% data.trial{1} = double(dat);
% data.time{1} = time;
% data.label = hdr.label(chanindx);
% data.hdr = hdr;
% data.fsample = hdr.Fs;
% apply some preprocessing options
if strcmp(cfg.demean, 'yes')
% demean using the first sample
dat = ft_preproc_baselinecorrect(dat, 1, 1);
end
if strcmp(cfg.detrend, 'yes')
dat = ft_preproc_detrend(dat);
end
if strcmp(cfg.dftfilter, 'yes')
dat = ft_preproc_dftfilter(dat, hdr.Fs, cfg.dftfreq);
end
if strcmp(cfg.olfilter, 'yes')
if count==1
if cfg.olfreq(1)==0
fprintf('using online low-pass filter\n');
[B, A] = butter(cfg.olfiltord, cfg.olfreq(2)/hdr.Fs);
elseif cfg.olfreq(2)>=hdr.Fs/2
fprintf('using online high-pass filter\n');
[B, A] = butter(cfg.olfiltord, cfg.olfreq(1)/hdr.Fs, 'high');
else
fprintf('using online band-pass filter\n');
[B, A] = butter(cfg.olfiltord, cfg.olfreq/hdr.Fs);
end % use one sample to initialize
FM = ft_preproc_online_filter_init(B, A, dat(:,1));
end
[FM, dat] = ft_preproc_online_filter_apply(FM, dat);
end
if isempty(cfg.offset)
cfg.offset = ((1:nchan)-1) .* mean(max(abs(dat),[],2));
end
% shift each of the channels with a given offset
nchan = size(dat,1);
for i=1:nchan
dat(i,:) = dat(i,:) + (nchan-i-1)*cfg.offset(i);
end
% plot the data
plot(time, dat);
xlim([time(1) time(end)]);
if strcmp(cfg.readevent, 'yes')
for i=1:length(evt)
% draw a line and some text to indicate the event
time = offset2time(evt(i).sample, hdr.Fs, 1);
if ischar(evt(i).type) && isempty(evt(i).type)
description = sprintf('%s', evt(i).type);
elseif ischar(evt(i).type) && ischar(evt(i).type)
description = sprintf('%s %s', evt(i).type, evt(i).value);
elseif ischar(evt(i).type) && isnumeric(evt(i).type)
description = sprintf('%s %s', evt(i).type, num2str(evt(i).value));
else
description = 'event';
end
h = line([time time], ylim);
set(h, 'LineWidth', 2, 'LineStyle', ':', 'Color', 'k');
y = ylim; y = y(1);
h = text(time, y, description, 'VerticalAlignment', 'bottom');
end
end
% force Matlab to update the figure
drawnow
end % while true
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [time] = offset2time(offset, fsample, nsamples)
offset = double(offset);
nsamples = double(nsamples);
time = (offset + (0:(nsamples-1)))/fsample;
|
github
|
lcnhappe/happe-master
|
ft_realtime_packettimer.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/example/ft_realtime_packettimer.m
| 2,522 |
utf_8
|
ce7334780040a70c9e396dd0e8aa858d
|
function ft_realtime_packettimer(cfg)
% FT_REALTIME_PACKETTIMER can be used to time the rate at which data can be processed
%
% Use as
% ft_realtime_packettimer(cfg)
% with the following configuration options
% cfg.bcifun = processing of the data (default = @bcifun_timer)
% cfg.npackets = the number of packets shown in one plot (default=1000)
% after reaching the end
% cfg.saveplot = if path is specified, first plot is saved (default=[]);
% cfg.rellim = y limits of subplot 1 (default = [-100 100])
%
% SEE ALSO:
% FT_REALTIME_PROCESS
% TO DO:
% jitter in het binnenhalen van de data; scatterplot!
% triggers sturen en herhalen (loop closen)
% tijd schatten waarin matlab nog kan processen
% Copyright (C) 2009, Marcel van Gerven
%
% $Id$
if ~isfield(cfg,'bcifun'), cfg.bcifun = @bcifun_timer; end
if ~isfield(cfg,'npackets'), cfg.npackets = 10^2; end
if ~isfield(cfg,'rellim'), cfg.rellim = [-1 1]; end
if ~isfield(cfg,'saveplot'), cfg.saveplot= []; end
close all;
f1 = figure();
set(f1,'units','normalized','outerposition',[0 0 1 1]);
% reset persistent variables
cfg.bcifun();
try
ft_realtime_process(cfg);
catch
fprintf('%s\n',lasterr);
close;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% BCIFUN_TIMER plots real time versus packet time
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function bcifun_timer(cfg,data)
persistent startsample;
persistent olddf;
persistent idx;
if nargin == 0
idx = []; % reset persistent
return;
end
if isempty(idx)
tic;
startsample = data.endsample;
idx = 1;
olddf = 0;
return;
end
if mod(idx,cfg.npackets) == 1
xl = [floor(idx/cfg.npackets)*cfg.npackets+1 (floor(idx/cfg.npackets)+1)*cfg.npackets];
hold off
plot(xl,[0 0],'k--');
xlim(xl);
ylim(cfg.rellim);
xlabel('packet number');
ylabel('delay (sample time - real time)');
hold on;
end
cursample = data.endsample;
curtime = toc;
smptime = (cursample - startsample)/data.fsample;
df = smptime - curtime;
if df < 0
plot([idx-1 idx],[olddf df],'r');
else
plot([idx-1 idx],[olddf df],'g');
end
olddf = df;
title(sprintf('packet timing for %g s blocks in %d channels at sample frequency %d; sample time = %g, real time = %g, delay = %g',...
data.blocksize/data.fsample,length(data.label),data.fsample,smptime,curtime,smptime - curtime));
idx = idx + 1;
drawnow;
if idx==cfg.npackets && strcmp(cfg.saveplot,'yes')
saveas(gcf,cfg.saveplot,'jpg');
end
|
github
|
lcnhappe/happe-master
|
ft_realtime_topography.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/example/ft_realtime_topography.m
| 7,588 |
utf_8
|
a80a1641c2aa67f4120d9f7bd114d8c8
|
function ft_realtime_topography(cfg)
% FT_REALTIME_TOPOGRAPHY reads continuous data from a file or from a data stream,
% estimates the power and plots the scalp topography in real time.
%
% Use as
% ft_realtime_topography(cfg)
% with the following configuration options
% cfg.blocksize = number, size of the blocks/chuncks that are processed (default = 1 second)
% cfg.overlap = number, amojunt of overlap between chunks (default = 0 seconds)
% cfg.layout = specification of the layout, see FT_PREPARE_LAYOUT
%
% The source of the data is configured as
% cfg.dataset = string
% or alternatively to obtain more low-level control as
% cfg.datafile = string
% cfg.headerfile = string
% cfg.eventfile = string
% cfg.dataformat = string, default is determined automatic
% cfg.headerformat = string, default is determined automatic
% cfg.eventformat = string, default is determined automatic
%
% To stop this realtime function, you have to press Ctrl-C
%
% Example use
% cfg = [];
% cfg.dataset = 'PW02_ingnie_20061212_01.ds';
% cfg.layout = 'CTF151.lay';
% cfg.channel = 'MEG';
% cfg.blocksize = 0.5;
% cfg.overlap = 0.25;
% cfg.demean = 'yes';
% cfg.bpfilter = [15 25];
% cfg.bpfreq = 'yes';
% ft_realtime_topography(cfg);
% 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$
% set the defaults
if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end % default is detected automatically
if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end % default is detected automatically
if ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end % default is detected automatically
if ~isfield(cfg, 'blocksize'), cfg.blocksize = 1; end % in seconds
if ~isfield(cfg, 'overlap'), cfg.overlap = 0; end % in seconds
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
% translate dataset into datafile+headerfile
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes');
cfg = ft_checkconfig(cfg, 'required', {'datafile' 'headerfile'});
% ensure that the persistent variables related to caching are cleared
clear ft_read_header
% read the header for the first time
hdr = ft_read_header(cfg.headerfile);
fprintf('updating the header information, %d samples available\n', hdr.nSamples*hdr.nTrials);
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chanindx = match_str(hdr.label, cfg.channel);
% prepare the layout, also implements channel selection
lay = ft_prepare_layout(cfg);
% determine the size of blocks to process
blocksize = round(cfg.blocksize*hdr.Fs);
overlap = round(cfg.overlap*hdr.Fs);
% initialize some stuff
cmin = -1;
cmax = 1;
clear recurz
recurz; % initialize the persistent variables
% open a new figure
h = figure;
prevSample = 0;
count = 0;
lay = ft_prepare_layout(cfg);
[laysel, datsel] = match_str(lay.label, hdr.label);
% get the 2D position of the channels
x = lay.pos(laysel,1);
y = lay.pos(laysel,2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is the general BCI loop where realtime incoming data is handled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while true
% determine number of samples available in buffer
hdr = ft_read_header(cfg.headerfile, 'cache', true);
% see whether new samples are available
newsamples = (hdr.nSamples*hdr.nTrials-prevSample);
if newsamples>=(blocksize-overlap)
% determine the samples to process
if strcmp(cfg.bufferdata, 'last')
begsample = hdr.nSamples*hdr.nTrials - blocksize + 1;
endsample = hdr.nSamples*hdr.nTrials;
elseif strcmp(cfg.bufferdata, 'first')
begsample = prevSample + 1;
endsample = prevSample + blocksize ;
else
error('unsupported value for cfg.bufferdata');
end
% this allows overlapping data segments
if overlap && (begsample>overlap)
begsample = begsample - overlap;
endsample = endsample - overlap;
end
% remember up to where the data was read
prevSample = endsample;
count = count + 1;
fprintf('processing segment %d from sample %d to %d\n', count, begsample, endsample);
% read data segment
dat = ft_read_data(cfg.datafile, 'dataformat', cfg.dataformat, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% from here onward it is specific to the power estimation from the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% put the data in a fieldtrip-like raw structure
data = [];
data.trial{1} = dat;
data.time{1} = offset2time(begsample, hdr.Fs, endsample-begsample+1);
data.label = hdr.label(chanindx);
data.hdr = hdr;
data.fsample = hdr.Fs;
% apply preprocessing options
data = ft_preprocessing(cfg, data);
% estimate power
powest = sum(data.trial{1}.^2, 2);
if ~ishandle(h)
% re-initialize some stuff
cmin = -1;
cmax = 1;
% open a new figure
h = figure;
end
% compute z-transformed
powest = recurz(powest);
% plot the topography
ft_plot_topo(x, y, powest(datsel), 'outline', lay.outline, 'mask', lay.mask);
hold on
plot(x, y, 'k.');
hold off
c = caxis;
cmin = min(cmin, c(1));
cmax = max(cmax, c(2));
c = [cmin cmax];
caxis(c);
drawnow
end % if enough new samples
end % while true
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function time = offset2time(offset, fsample, nsamples)
time = (offset + (0:(nsamples-1)))/fsample;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION recursive computation of z-transformed data by means of persistent variables
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function z = recurz(x)
persistent n
persistent s
persistent ss
if nargin==0 || isempty(x)
% re-initialize
n = [];
s = [];
ss = [];
return
end
if isempty(n)
n = 1;
else
n = n + 1;
end
if isempty(s)
s = x;
else
s = s + x;
end
if isempty(ss)
ss = x.^2;
else
ss = ss + x.^2;
end
if n==1
% standard deviation cannot be computed yet
z = zeros(size(x));
elseif all(s(:)==ss(:))
% standard deviation is zero anyway
z = zeros(size(x));
else
% compute standard deviation and z-transform of the input data
sd = sqrt((ss - (s.^2)./n) ./ (n-1));
z = (x-s/n)./ sd;
end
|
github
|
lcnhappe/happe-master
|
ft_realtime_heartbeatdetect.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/example/ft_realtime_heartbeatdetect.m
| 9,725 |
utf_8
|
a64cf7e75558cb8c89ea26c459849f8f
|
function ft_realtime_heartbeatdetect(cfg)
% FT_REALTIME_HEARTBEATDETECT is an example realtime application for online
% detection of heart beats. It should work both for EEG and MEG.
%
% Use as
% ft_realtime_heartbeatdetect(cfg)
% with the following configuration options
% cfg.blocksize = number, size of the blocks/chuncks that are processed (default = 1 second)
% cfg.channel = cell-array, see FT_CHANNELSELECTION (default = 'all')
% cfg.jumptoeof = whether to skip to the end of the stream/file at startup (default = 'yes')
% cfg.bufferdata = whether to start on the 'first or 'last' data that is available (default = 'first')
% cfg.threshold = value, after normalization (default = 3)
%
% The source of the data is configured as
% cfg.dataset = string
% or alternatively to obtain more low-level control as
% cfg.datafile = string
% cfg.headerfile = string
% cfg.eventfile = string
% cfg.dataformat = string, default is determined automatic
% cfg.headerformat = string, default is determined automatic
% cfg.eventformat = string, default is determined automatic
%
% To stop the realtime function, you have to press Ctrl-C
% Copyright (C) 2009-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$
% set the default configuration options
cfg.dataformat = ft_getopt(cfg, 'dataformat'); % default is detected automatically
cfg.headerformat = ft_getopt(cfg, 'headerformat'); % default is detected automatically
cfg.eventformat = ft_getopt(cfg, 'eventformat'); % default is detected automatically
cfg.blocksize = ft_getopt(cfg, 'blocksize', 0.1); % in seconds
cfg.threshold = ft_getopt(cfg, 'threshold', 3); % after normalization
cfg.mindist = ft_getopt(cfg, 'mindist', 0.1); % in seconds
cfg.channel = ft_getopt(cfg, 'channel', 'all');
cfg.jumptoeof = ft_getopt(cfg, 'jumptoeof', 'yes'); % jump to end of file at initialization
cfg.bufferdata = ft_getopt(cfg, 'bufferdata', 'first'); % first or last
cfg.demean = ft_getopt(cfg, 'demean', 'yes'); % baseline correction
cfg.detrend = ft_getopt(cfg, 'detrend', 'no');
cfg.olfilter = ft_getopt(cfg, 'olfilter', 'no'); % continuous online filter
cfg.olfiltord = ft_getopt(cfg, 'olfiltord', 4);
cfg.olfreq = ft_getopt(cfg, 'olfreq', [2 45]);
cfg.dftfilter = ft_getopt(cfg, 'dftfilter', 'yes'); % filter using discrete Fourier transform
cfg.dftfreq = ft_getopt(cfg, 'dftfreq', 50); % line noise frequency
if ~isfield(cfg, 'dataset') && ~isfield(cfg, 'datafile') && ~isfield(cfg, 'headerfile')
cfg.dataset = 'buffer://localhost:1972';
end
% translate dataset into datafile+headerfile
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes');
cfg = ft_checkconfig(cfg, 'required', {'datafile' 'headerfile'});
% ensure that the persistent variables related to caching are cleared
clear ft_read_header
% start by reading the header from the realtime buffer
hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat, 'cache', true, 'retry', true);
% define a subset of channels for reading
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chanindx = match_str(hdr.label, cfg.channel);
nchan = length(chanindx);
if nchan==0
error('no channels were selected');
elseif nchan>1
error('this function expects that you select a single channel');
end
% determine the size of blocks to process
blocksize = round(cfg.blocksize * hdr.Fs);
if strcmp(cfg.jumptoeof, 'yes')
prevSample = hdr.nSamples * hdr.nTrials;
else
prevSample = 0;
end
prevState = [];
count = 0;
tpl = [];
ws_noPeaks = warning('off', 'signal:findpeaks:noPeaks');
ws_PeakHeight = warning('off', 'signal:findpeaks:largeMinPeakHeight');
% start the timer
tic
t0 = toc;
n0 = 0;
t1 = t0;
n1 = n0;
% this will keep the time of each heart beat
heartbeat = [];
% these are for the feedback
close all
h1f = figure;
plot(nan);
h1a = get(h1f, 'children');
h1c = get(h1a, 'children');
set(h1f, 'Position', [010 300 560 420]);
xlabel('time (s)');
ylim([-6 6]);
h2f = figure;
plot(nan, '.');
h2a = get(h2f, 'children');
h2c = get(h2a, 'children');
set(h2f, 'Position', [580 300 560 420]);
title('heartbeat');
xlabel('time (s)');
ylabel('beats per minute');
c = onCleanup(@cleanup_cb);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is the general BCI loop where realtime incoming data is handled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while true
% determine the samples to process
if strcmp(cfg.bufferdata, 'last')
% determine number of samples available in buffer
hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat, 'cache', true);
begsample = hdr.nSamples*hdr.nTrials - blocksize + 1;
endsample = hdr.nSamples*hdr.nTrials;
elseif strcmp(cfg.bufferdata, 'first')
endsample = min(prevSample+blocksize, hdr.nSamples*hdr.nTrials);
begsample = endsample - blocksize + 1;
else
error('unsupported value for cfg.bufferdata');
end
% remember up to where the data was read
prevSample = endsample;
count = count + 1;
% fprintf('processing segment %d from sample %d to %d\n', count, begsample, endsample);
% read data segment from buffer
dat = ft_read_data(cfg.datafile, 'header', hdr, 'dataformat', cfg.dataformat, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false, 'blocking', true);
dat = double(dat);
% fprintf('time between subsequent reads is %f seconds\n', toc-t1);
% keep track of the timing
t1 = toc;
n1 = n1 + size(dat,2);
% fprintf('read %d samples in %f seconds, realtime ratio = %f\n', n1-n0, t1-t0, ((n1-n0)/(t1-t0))/hdr.Fs);
% fprintf('time lag %6.3f seconds\n', (n1-n0)/hdr.Fs - (t1-t0));
% fprintf('estimated sampling rate %.2f Hz\n', (n1-n0)/(t1-t0));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% from here onward it is specific to the display of the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sample = begsample:endsample;
time = sample./hdr.Fs;
% apply some preprocessing options
if strcmp(cfg.demean, 'yes')
dat = ft_preproc_baselinecorrect(dat);
end
if strcmp(cfg.detrend, 'yes')
dat = ft_preproc_detrend(dat);
end
if strcmp(cfg.dftfilter, 'yes')
dat = ft_preproc_dftfilter(dat, hdr.Fs, cfg.dftfreq);
end
if strcmp(cfg.olfilter, 'yes')
if ~exist('FM', 'var')
% initialize online filter
if cfg.olfreq(1)==0
fprintf('using online low-pass filter\n');
[B, A] = butter(cfg.olfiltord, cfg.olfreq(2)/hdr.Fs);
elseif cfg.olfreq(2)>=hdr.Fs/2
fprintf('using online high-pass filter\n');
[B, A] = butter(cfg.olfiltord, cfg.olfreq(1)/hdr.Fs, 'high');
else
fprintf('using online band-pass filter\n');
[B, A] = butter(cfg.olfiltord, cfg.olfreq/hdr.Fs);
end
% use one sample to initialize
FM = ft_preproc_online_filter_init(B, A, dat(:,1));
end
% apply online filter
[FM, dat] = ft_preproc_online_filter_apply(FM, dat);
end
[dat, prevState] = ft_preproc_standardize(dat, [], [], prevState);
if cfg.threshold<0
% detect negative peaks
[peakval, peakind] = findpeaks(-dat, 'minpeakheight', -cfg.threshold);
peakval = -peakval;
else
% detect positive peaks
[peakval, peakind] = findpeaks(dat, 'minpeakheight', cfg.threshold);
end
if numel(peakind)/(blocksize/hdr.Fs)>3
% heartbeat cannot be above 180 bpm
warning('skipping due to noise');
peakval = [];
peakind = [];
end
% FIXME having the heartbeat vector growing is not a very good idea
heartbeat = [heartbeat time(peakind)];
if ishandle(h1f)
set(h1c, 'xdata', time, 'ydata', dat);
set(h1a, 'xlim', time([1 end]));
end
if numel(heartbeat)>5 && ishandle(h2f)
% skip the first heartbeat for the axes
set(h2c, 'xdata', heartbeat(2:end), 'ydata', 60./diff(heartbeat));
set(h2a, 'xlim', heartbeat([2 end]) + [0 1]);
set(h2a, 'ylim', [0 160]);
end
% if numel(heartbeat)>3
% event.type = 'heartrate';
% event.value = heartbeat(end) - heartbeat(end-1);
% event.sample = [];
% event.offset = 0;
% event.duration = 0;
% ft_write_event(cfg.dataset, event);
% end
% force Matlab to redraw the figures
drawnow
end % while true
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that gives a beep as feedback
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function feedback_beep(varargin)
beep = audioplayer(0.05*sin(1000*2*pi*(1:1024)/8192), 8192);
play(beep);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function cleanup_cb(varargin)
delete(timerfindall)
|
github
|
lcnhappe/happe-master
|
ft_realtime_powerestimate.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/example/ft_realtime_powerestimate.m
| 6,443 |
utf_8
|
361c8a8f141a0cc16b24d8c40614a42f
|
function ft_realtime_powerestimate(cfg)
% FT_REALTIME_POWERESTIMATE is an example realtime application for online
% power estimation. It should work both for EEG and MEG.
%
% Use as
% ft_realtime_powerestimate(cfg)
% with the following configuration options
% cfg.channel = cell-array, see FT_CHANNELSELECTION (default = 'all')
% cfg.foilim = [Flow Fhigh] (default = [0 120])
% cfg.blocksize = number, size of the blocks/chuncks that are processed (default = 1 second)
% cfg.bufferdata = whether to start on the 'first or 'last' data that is available (default = 'last')
%
% The source of the data is configured as
% cfg.dataset = string
% or alternatively to obtain more low-level control as
% cfg.datafile = string
% cfg.headerfile = string
% cfg.eventfile = string
% cfg.dataformat = string, default is determined automatic
% cfg.headerformat = string, default is determined automatic
% cfg.eventformat = string, default is determined automatic
%
% To stop the realtime function, you have to press Ctrl-C
% 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$
% set the default configuration options
if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end % default is detected automatically
if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end % default is detected automatically
if ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end % default is detected automatically
if ~isfield(cfg, 'blocksize'), cfg.blocksize = 1; end % in seconds
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'foilim'), cfg.foilim = [0 120]; end
if ~isfield(cfg, 'bufferdata'), cfg.bufferdata = 'last'; end % first or last
% translate dataset into datafile+headerfile
if ~isfield(cfg, 'dataset') && ~isfield(cfg, 'header') && ~isfield(cfg, 'datafile')
cfg.dataset = 'buffer://localhost:1972';
end
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes');
cfg = ft_checkconfig(cfg, 'required', {'datafile' 'headerfile'});
% ensure that the persistent variables related to caching are cleared
clear ft_read_header
% start by reading the header from the realtime buffer
hdr = ft_read_header(cfg.headerfile, 'cache', true, 'retry', true);
% define a subset of channels for reading
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chanindx = match_str(hdr.label, cfg.channel);
nchan = length(chanindx);
if nchan==0
error('no channels were selected');
end
% determine the size of blocks to process
blocksize = round(cfg.blocksize * hdr.Fs);
% this is used for scaling the figure
powmax = 0;
% set up the spectral estimator
specest = spectrum.welch('Hamming', min(hdr.Fs, blocksize));
prevSample = 0;
count = 0;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is the general BCI loop where realtime incoming data is handled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while true
% determine number of samples available in buffer
hdr = ft_read_header(cfg.headerfile, 'cache', true);
% see whether new samples are available
newsamples = (hdr.nSamples*hdr.nTrials-prevSample);
if newsamples>=blocksize
% determine the samples to process
if strcmp(cfg.bufferdata, 'last')
begsample = hdr.nSamples*hdr.nTrials - blocksize + 1;
endsample = hdr.nSamples*hdr.nTrials;
elseif strcmp(cfg.bufferdata, 'first')
begsample = prevSample+1;
endsample = prevSample+blocksize ;
else
error('unsupported value for cfg.bufferdata');
end
% remember up to where the data was read
prevSample = endsample;
count = count + 1;
fprintf('processing segment %d from sample %d to %d\n', count, begsample, endsample);
% read data segment from buffer
dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% from here onward it is specific to the power estimation from the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% put the data in a fieldtrip-like raw structure
data.trial{1} = dat;
data.time{1} = offset2time(begsample, hdr.Fs, endsample-begsample+1);
data.label = hdr.label(chanindx);
data.hdr = hdr;
data.fsample = hdr.Fs;
% apply preprocessing options
data.trial{1} = ft_preproc_baselinecorrect(data.trial{1});
figure(1)
h = get(gca, 'children');
hold on
if ~isempty(h)
% done on every iteration
delete(h);
end
if isempty(h)
% done only once
powmax = 0;
grid on
end
for i=1:nchan
est = psd(specest, data.trial{1}(i,:), 'Fs', data.fsample);
if i==1
pow = est.Data;
else
pow = pow + est.Data;
end
end
pow = pow/nchan;
powmax = max(max(pow), powmax); % this keeps a history
plot(est.Frequencies, pow);
axis([cfg.foilim(1) cfg.foilim(2) 0 powmax]);
str = sprintf('time = %d s\n', round(mean(data.time{1})));
title(str);
xlabel('frequency (Hz)');
ylabel('power');
% force Matlab to update the figure
drawnow
end % if enough new samples
end % while true
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [time] = offset2time(offset, fsample, nsamples)
offset = double(offset);
nsamples = double(nsamples);
time = (offset + (0:(nsamples-1)))/fsample;
|
github
|
lcnhappe/happe-master
|
ft_realtime_average.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/example/ft_realtime_average.m
| 5,663 |
utf_8
|
b0174ada31b4f5780645667fbe5b9251
|
function ft_realtime_average(cfg)
% FT_REALTIME_AVERAGE is an example realtime application for online
% averaging of the data. It should work both for EEG and MEG.
%
% Use as
% ft_realtime_average(cfg)
% with the following configuration options
% cfg.channel = cell-array, see FT_CHANNELSELECTION (default = 'all')
% cfg.trialfun = string with the trial function
%
% The source of the data is configured as
% cfg.dataset = string
% or alternatively to obtain more low-level control as
% cfg.datafile = string
% cfg.headerfile = string
% cfg.eventfile = string
% cfg.dataformat = string, default is determined automatic
% cfg.headerformat = string, default is determined automatic
% cfg.eventformat = string, default is determined automatic
%
% To stop the realtime function, you have to press Ctrl-C
% 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$
% set the default configuration options
if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end % default is detected automatically
if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end % default is detected automatically
if ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end % default is detected automatically
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'bufferdata'), cfg.bufferdata = 'last'; end % first or last
% translate dataset into datafile+headerfile
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes');
cfg = ft_checkconfig(cfg, 'required', {'datafile' 'headerfile'});
% ensure that the persistent variables related to caching are cleared
clear ft_read_header
% start by reading the header from the realtime buffer
hdr = ft_read_header(cfg.headerfile, 'cache', true);
% define a subset of channels for reading
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chanindx = match_str(hdr.label, cfg.channel);
nchan = length(chanindx);
if nchan==0
error('no channels were selected');
end
prevSample = 0;
count = 0;
% initialize the average, it will be filled on the first iteration
avgsum = [];
avgnum = [];
% open a figure in which the average will be plotted
figure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is the general BCI loop where realtime incoming data is handled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while true
% determine latest header and event information
event = ft_read_event(cfg.dataset, 'minsample', prevSample+1); % only consider events that are later than the data processed sofar
hdr = ft_read_header(cfg.dataset, 'cache', true); % the trialfun might want to use this, but it is not required
cfg.event = event; % store it in the configuration, so that it can be passed on to the trialfun
cfg.hdr = hdr; % store it in the configuration, so that it can be passed on to the trialfun
% evaluate the trialfun, note that the trialfun should not re-read the events and header
fprintf('evaluating ''%s'' based on %d events\n', cfg.trialfun, length(event));
trl = feval(cfg.trialfun, cfg);
fprintf('processing %d trials\n', size(trl,1));
for trllop=1:size(trl,1)
begsample = trl(trllop,1);
endsample = trl(trllop,2);
offset = trl(trllop,3);
% remember up to where the data was read
prevSample = endsample;
count = count + 1;
fprintf('processing segment %d from sample %d to %d\n', count, begsample, endsample);
% read data segment from buffer
dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% from here onward it is specific to the processing of the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% apply some preprocessing options
dat = ft_preproc_baselinecorrect(dat);
if isempty(average)
% initialize the accumulating variables on the first call
avgsum = dat;
avgnum = 1;
else
avgsum = avgsum + dat;
avgnum = avgnum + 1;
end
% compute the average
avg = avgsum ./ avgnum;
% create a time-axis and plot the average
time = offset2time(offset, hdr.Fs, endsample-begsample+1);
plot(time, avg);
% force matlab to redraw the figure
drawnow
end % looping over new trials
end % while true
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [time] = offset2time(offset, fsample, nsamples)
offset = double(offset);
nsamples = double(nsamples);
time = (offset + (0:(nsamples-1)))/fsample;
|
github
|
lcnhappe/happe-master
|
ft_realtime_selectiveaverage.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/example/ft_realtime_selectiveaverage.m
| 7,947 |
utf_8
|
2d90d2683d30fc029fd00490a76696c1
|
function ft_realtime_selectiveaverage(cfg)
% FT_REALTIME_SELECTIVEAVERAGE is an example realtime application for online
% averaging of the data. It should work both for EEG and MEG.
%
% Use as
% ft_realtime_selectiveaverage(cfg)
% with the following configuration options
% cfg.channel = cell-array, see FT_CHANNELSELECTION (default = 'all')
% cfg.trialfun = string with the trial function
%
% The source of the data is configured as
% cfg.dataset = string
% or alternatively to obtain more low-level control as
% cfg.datafile = string
% cfg.headerfile = string
% cfg.eventfile = string
% cfg.dataformat = string, default is determined automatic
% cfg.headerformat = string, default is determined automatic
% cfg.eventformat = string, default is determined automatic
%
% To stop the realtime function, you have to press Ctrl-C
% 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$
% set the default configuration options
if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end % default is detected automatically
if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end % default is detected automatically
if ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end % default is detected automatically
if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end
if ~isfield(cfg, 'bufferdata'), cfg.bufferdata = 'last'; end % first or last
if ~isfield(cfg, 'jumptoeof'), cfg.jumptoeof = 'no'; end % jump to end of file at initialization
% translate dataset into datafile+headerfile
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes');
cfg = ft_checkconfig(cfg, 'required', {'datafile' 'headerfile'});
% ensure that the persistent variables related to caching are cleared
clear ft_read_header
% start by reading the header from the realtime buffer
hdr = ft_read_header(cfg.headerfile, 'cache', true);
% define a subset of channels for reading
cfg.channel = ft_channelselection(cfg.channel, hdr.label);
chanindx = match_str(hdr.label, cfg.channel);
nchan = length(chanindx);
if nchan==0
error('no channels were selected');
end
if strcmp(cfg.jumptoeof, 'yes')
prevSample = hdr.nSamples * hdr.nTrials;
else
prevSample = 0;
end
count = 0;
% initialize the timelock cell-array, each cell will hold the average in one condition
timelock = {};
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is the general BCI loop where realtime incoming data is handled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while true
% determine latest header and event information
event = ft_read_event(cfg.dataset, 'minsample', prevSample+1); % only consider events that are later than the data processed sofar
hdr = ft_read_header(cfg.dataset, 'cache', true); % the trialfun might want to use this, but it is not required
cfg.event = event; % store it in the configuration, so that it can be passed on to the trialfun
cfg.hdr = hdr; % store it in the configuration, so that it can be passed on to the trialfun
% evaluate the trialfun, note that the trialfun should not re-read the events and header
fprintf('evaluating ''%s'' based on %d events\n', cfg.trialfun, length(event));
trl = feval(cfg.trialfun, cfg);
% the code below assumes that the 4th column of the trl matrix contains the condition index
% set the default condition to one if no condition index was given
if size(trl,1)>0 && size(trl,2)<4
trl(:,4) = 1;
end
fprintf('processing %d trials\n', size(trl,1));
for trllop=1:size(trl,1)
begsample = trl(trllop,1);
endsample = trl(trllop,2);
offset = trl(trllop,3);
condition = trl(trllop,4);
% remember up to where the data was read
prevSample = endsample;
count = count + 1;
fprintf('processing segment %d from sample %d to %d, condition = %d\n', count, begsample, endsample, condition);
% read data segment from buffer
dat = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% from here onward it is specific to the processing of the data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% put the data in a fieldtrip-like raw structure
data.trial{1} = dat;
data.time{1} = offset2time(offset, hdr.Fs, endsample-begsample+1);
data.label = hdr.label(chanindx);
data.hdr = hdr;
data.fsample = hdr.Fs;
% apply some preprocessing options
data.trial{1} = ft_preproc_baselinecorrect(data.trial{1});
if length(timelock)<condition || isempty(timelock{condition})
% this is the first occurence of this condition, initialize an empty timelock structure
timelock{condition}.label = data.label;
timelock{condition}.time = data.time{1};
timelock{condition}.avg = [];
timelock{condition}.var = [];
timelock{condition}.dimord = 'chan_time';
nchans = size(data.trial{1}, 1);
nsamples = size(data.trial{1}, 2);
% the following elements are for the cumulative computation
timelock{condition}.n = 0; % number of trials
timelock{condition}.s = zeros(nchans, nsamples); % sum
timelock{condition}.ss = zeros(nchans, nsamples); % sum of squares
end
% add the new data to the accumulated data
timelock{condition}.n = timelock{condition}.n + 1;
timelock{condition}.s = timelock{condition}.s + data.trial{1};
timelock{condition}.ss = timelock{condition}.ss + data.trial{1}.^2;
% compute the average and variance on the fly
timelock{condition}.avg = timelock{condition}.s ./ timelock{condition}.n;
timelock{condition}.var = (timelock{condition}.ss - (timelock{condition}.s.^2)./timelock{condition}.n) ./ (timelock{condition}.n-1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% from here onward additional processing of the selective averages could be done
% as an example here the ERP of each condition is plotted in its own figure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% compute the t-score versus zero by dividing the average by the standard error of mean
tscore = timelock{condition}.avg ./ (sqrt(timelock{condition}.var)./(timelock{condition}.n - 1));
figure(condition)
plot(timelock{condition}.time, tscore);
title(sprintf('condition %d, ntrials = %d', condition, timelock{condition}.n));
% force matlab to redraw the figure
drawnow
end % looping over new trials
end % while true
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [time] = offset2time(offset, fsample, nsamples)
offset = double(offset);
nsamples = double(nsamples);
time = (offset + (0:(nsamples-1)))/fsample;
|
github
|
lcnhappe/happe-master
|
encode_nifti1.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/example/private/encode_nifti1.m
| 4,870 |
utf_8
|
9cf92a03587c511a5cec2c8c76a3c2c3
|
function blob = encode_nifti1(H)
%function blob = encode_nifti1(H)
%
% Encodes a NIFTI-1 header (=> raw 348 bytes (uint8)) from a Matlab structure
% that matches the C struct defined in nifti1.h.
%
% WARNING: This function currently ignores endianness !!!
% (C) 2010 S.Klanke
blob = uint8(zeros(1,348));
if ~isstruct(H)
error 'Input must be a structure';
end
% see nift1.h for information on structure
sizeof_hdr = int32(348);
blob(1:4) = typecast(sizeof_hdr, 'uint8');
blob = setString(blob, 5, 14, H, 'data_type');
blob = setString(blob, 15, 32, H, 'db_name');
blob = setInt32( blob, 33, 36, H, 'extents');
blob = setInt16( blob, 37, 38, H, 'session_error');
blob = setInt8( blob, 39, 39, H, 'regular');
blob = setInt8( blob, 40, 40, H, 'dim_info');
dim = int16(H.dim(:)');
ndim = numel(dim);
if ndim<1 || ndim>7
error 'Field "dim" must have 1..7 elements';
end
dim = [int16(ndim) dim];
blob(41:(42+2*ndim)) = typecast(dim,'uint8');
blob = setSingle(blob, 57, 60, H, 'intent_p1');
blob = setSingle(blob, 61, 64, H, 'intent_p2');
blob = setSingle(blob, 65, 68, H, 'intent_p3');
blob = setInt16( blob, 69, 70, H, 'intent_code');
blob = setInt16( blob, 71, 72, H, 'datatype');
blob = setInt16( blob, 73, 74, H, 'bitpix');
blob = setInt16( blob, 75, 76, H, 'slice_start');
blob = setSingle(blob, 77, 80, H, 'qfac');
if isfield(H,'pixdim')
pixdim = single(H.pixdim(:)');
ndim = numel(pixdim);
if ndim<1 || ndim>7
error 'Field "pixdim" must have 1..7 elements';
end
blob(81:(80+4*ndim)) = typecast(pixdim,'uint8');
end
blob = setSingle(blob, 109, 112, H, 'vox_offset');
blob = setSingle(blob, 113, 116, H, 'scl_scope');
blob = setSingle(blob, 117, 120, H, 'scl_inter');
blob = setInt16( blob, 121, 122, H, 'slice_end');
blob = setInt8( blob, 123, 123, H, 'slice_code');
blob = setInt8( blob, 124, 124, H, 'xyzt_units');
blob = setSingle(blob, 125, 128, H, 'cal_max');
blob = setSingle(blob, 129, 132, H, 'cal_min');
blob = setSingle(blob, 133, 136, H, 'slice_duration');
blob = setSingle(blob, 137, 140, H, 'toffset');
blob = setInt32( blob, 141, 144, H, 'glmax');
blob = setInt32( blob, 145, 148, H, 'glmin');
blob = setString(blob, 149, 228, H, 'descrip');
blob = setString(blob, 229, 252, H, 'aux_file');
blob = setInt16( blob, 253, 254, H, 'qform_code');
blob = setInt16( blob, 255, 256, H, 'sform_code');
blob = setSingle(blob, 257, 260, H, 'quatern_b');
blob = setSingle(blob, 261, 264, H, 'quatern_c');
blob = setSingle(blob, 265, 268, H, 'quatern_d');
blob = setSingle(blob, 269, 272, H, 'quatern_x');
blob = setSingle(blob, 273, 276, H, 'quatern_y');
blob = setSingle(blob, 277, 280, H, 'quatern_z');
blob = setSingle(blob, 281, 296, H, 'srow_x');
blob = setSingle(blob, 297, 312, H, 'srow_y');
blob = setSingle(blob, 313, 328, H, 'srow_z');
blob = setString(blob, 329, 344, H, 'intent_name');
if ~isfield(H,'magic')
blob(345:347) = uint8('ni1');
else
blob = setString(blob, 345, 347, H, 'magic');
end
function blob = setString(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = getfield(H, fieldname);
ne = numel(F);
mx = endidx - begidx +1;
if ne > 0
if ~ischar(F) || ne > mx
errmsg = sprintf('Field "data_type" must be a string of maximally %i characters.', mx);
error(errmsg);
end
blob(begidx:(begidx+ne-1)) = uint8(F(:)');
end
% set 32-bit integers (check #elements)
function blob = setInt32(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = int32(getfield(H, fieldname));
ne = numel(F);
sp = (endidx - begidx +1) / 4;
if ne~=sp
errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp);
error(errmsg);
end
blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8');
% set 16-bit integers (check #elements)
function blob = setInt16(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = int16(getfield(H, fieldname));
ne = numel(F);
sp = (endidx - begidx +1) / 2;
if ne~=sp
errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp);
error(errmsg);
end
blob(begidx:(begidx+2*ne-1)) = typecast(F(:)', 'uint8');
% just 8-bit integers (check #elements)
function blob = setInt8(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = int8(getfield(H, fieldname));
ne = numel(F);
sp = (endidx - begidx +1);
if ne~=sp
errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp);
error(errmsg);
end
blob(begidx:(begidx+ne-1)) = typecast(F(:)', 'uint8');
% single precision floats
function blob = setSingle(blob, begidx, endidx, H, fieldname)
if ~isfield(H,fieldname)
return
end
F = single(getfield(H, fieldname));
ne = numel(F);
sp = (endidx - begidx +1) / 4;
if ne~=sp
errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp);
error(errmsg);
end
blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8');
|
github
|
lcnhappe/happe-master
|
ft_realtime_headlocalizer.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/realtime/online_meg/ft_realtime_headlocalizer.m
| 34,879 |
utf_8
|
da6be976bfcbd763152dc11de64b3c1b
|
function ft_realtime_headlocalizer(cfg)
% FT_REALTIME_HEADLOCALIZER is a realtime application for online visualization of the
% head position indicator (HPI) coils in CTF275 and Elekta/Neuromag systems.
%
% Repositioning within a recording session can be achieved by marking the HPI
% coil positions at an arbitrary point, i.e. by clicking the 'Update' button.
% Black unfilled markers should appear which indicate the positions of the coils
% at the moment of buttonpress. Distance to these marked positions then
% become colorcoded, i.e. green, orange, or red.
%
% Repositioning between a recording session, i.e. to a previous recording session,
% can be achieved by specifying a template; e.g. by pointing to another dataset;
% e.g. cfg.template = 'subject01xxx.ds' (CTF only), or by pointing to a textfile
% created during a previous recording; e.g. cfg.template = '29-Apr-2013-xxx.txt'.
% The latter textfile is created automatically with each 'Update' buttonpress.
%
% Use as
% ft_realtime_headlocalizer(cfg)
% with the following configuration options
% cfg.dataset = string, name or location of a dataset/buffer (default = 'buffer://odin:1972')
% cfg.template = string, name of a template dataset for between-session repositioning (default = [])
% cfg.bufferdata = whether to start on the 'first or 'last' data that is available (default = 'last')
% cfg.coilfreq = single number in Hz or list of numbers (Neuromag default = [293, 307, 314, 321, 328])
% cfg.blocksize = number, size of the blocks/chuncks that are processed (default = 1 second)
% cfg.accuracy_green = distance from fiducial coordinate; green when within limits (default = 0.15 cm)
% cfg.accuracy_orange = orange when within limits, red when out (default = 0.3 cm)
%
% This method is described in Stolk A, Todorovic A, Schoffelen JM, Oostenveld R.
% "Online and offline tools for head movement compensation in MEG."
% Neuroimage. 2013 Mar;68:39-48. doi: 10.1016/j.neuroimage.2012.11.047.
% Copyright (C) 2008-2013, Arjen Stolk & 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$
agreement = {
'By using this realtime headlocalizer tool in your research, you agree to citing the publication below.'
''
'Stolk A, Todorovic A, Schoffelen JM, Oostenveld R.'
'"Online and offline tools for head movement compensation in MEG."'
'Neuroimage. 2013 Mar;68:39-48.'
};
if ~strcmp(questdlg(agreement,'User agreement', 'Yes', 'Cancel', 'Cancel'), 'Yes')
return
end
% do the general setup of the function
ft_defaults
% set the defaults
cfg.dataset = ft_getopt(cfg, 'dataset', 'buffer://odin:1972'); % location of the buffer/dataset
cfg.accuracy_green = ft_getopt(cfg, 'accuracy_green', .15); % green when within this distance from reference
cfg.accuracy_orange = ft_getopt(cfg, 'accuracy_orange', .3); % orange when within this distance from reference
cfg.template = ft_getopt(cfg, 'template', []); % template dataset containing the references
cfg.blocksize = ft_getopt(cfg, 'blocksize', 1); % in seconds
cfg.bufferdata = ft_getopt(cfg, 'bufferdata', 'last'); % first (replay) or last (real-time)
cfg.coilfreq = ft_getopt(cfg, 'coilfreq', [293, 307, 314, 321, 328]); % Hz, Neuromag
% ensure pesistent variables are cleared
clear ft_read_header
% start by reading the header from the realtime buffer
cfg = ft_checkconfig(cfg, 'dataset2files', 'yes'); % translate dataset into datafile+headerfile
hdr = ft_read_header(cfg.headerfile, 'cache', true, 'coordsys', 'dewar');
% determine the size of blocks to process
blocksize = round(cfg.blocksize * hdr.Fs);
prevSample = 0;
count = 0;
% determine MEG system type
isneuromag = ft_senstype(hdr.grad, 'neuromag');
isctf = ft_senstype(hdr.grad, 'ctf275');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read template head position, to reposition to, if template file is specified
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isctf
if ~isempty(cfg.template)
[p, f, x]=fileparts(cfg.template);
if strcmp(x, '.ds')
shape = ft_read_headshape(cfg.template, 'coordsys', 'dewar', 'format', 'ctf_ds');
template(1,:) = [shape.fid.pos(1,1), shape.fid.pos(1,2), shape.fid.pos(1,3)]; % chan X pos
template(2,:) = [shape.fid.pos(2,1), shape.fid.pos(2,2), shape.fid.pos(2,3)];
template(3,:) = [shape.fid.pos(3,1), shape.fid.pos(3,2), shape.fid.pos(3,3)];
elseif strcmp(x, '.txt')
template = dlmread(cfg.template);
else
error('incorrect template file specified');
end
else
template = [];
end
% remove CTF REF sensors, for plotting purposes
chansel = match_str(hdr.grad.chantype,'meggrad');
hdr.grad.chanpos = hdr.grad.chanpos(chansel,:);
hdr.grad.chanori = hdr.grad.chanori(chansel,:);
hdr.grad.chantype = hdr.grad.chantype(chansel,:);
hdr.grad.label = hdr.grad.label(chansel,:);
hdr.grad.tra = hdr.grad.tra(chansel,:);
elseif isneuromag
if ~isempty(cfg.template)
template = dlmread(cfg.template);
else
template = [];
end
else
error('the data does not resemble ctf, nor neuromag')
end % if ctf or neuromag
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read digitized head position (for dipole fitting)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isctf
sens = hdr.grad;
% not needed for CTF275 systems
dip = [];
vol = [];
coilsignal = [];
elseif isneuromag
shape = ft_read_headshape(cfg.headerfile, 'coordsys', 'dewar', 'format', 'neuromag_fif','unit','m'); % ensure SI units
for i = 1:min(size(shape.pos,1),length(cfg.coilfreq)) % for as many digitized or specified coils
if ~isempty(strfind(shape.label{i},'hpi'))
dip(i).pos = shape.pos(i,:); % chan X pos, initial guess for each of the dipole/coil positions
dip(i).mom = [0 0 0]';
end
end
if ~exist('dip', 'var')
error('head localization requires digitized positions for Neuromag systems')
end
% prepare the forward model and the sensor array for subsequent fitting
% note that the forward model is a magnetic dipole in an infinite vacuum
%cfg.channel = ft_channelselection('MEG', hdr.label); % because we want to planars as well (previously only magnetometers)
cfg.channel = ft_channelselection('MEGMAG', hdr.label); % old
%cfg.channel = setdiff(ft_channelselection('MEG', hdr.label),ft_channelselection('MEGMAG', hdr.label)); % just trying out (planar mags)
%cfg.channel = ft_channelselection('IAS*',hdr.label); % internal active shielding
[vol, sens] = ft_prepare_vol_sens([], hdr.grad, 'channel', cfg.channel);
sens = ft_datatype_sens(sens, 'version', 'upcoming', 'scaling', 'amplitude/distance', 'distance', 'm'); % ensure SI units
coilsignal = [];
% update distances, given that sensor units are m an not cm
cfg.accuracy_green = cfg.accuracy_green/100;
cfg.accuracy_orange = cfg.accuracy_orange/100;
else
error('the data does not resemble ctf, nor neuromag')
end % if ctf or neuromag
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define a subset of channels for reading
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if isctf
[dum, chanindx] = match_str('headloc', hdr.chantype);
elseif isneuromag
% 102 magnetometers
[dum, chanindx] = match_str('megmag', hdr.chantype);
% all 306
%[dum, chanindx1] = match_str('megmag', hdr.chantype);
%[dum, chanindx2] = match_str('megplanar', hdr.chantype); % because we want to planars as well
%chanindx = sort([chanindx1; chanindx2],1); % because we want to planars as well
% 204 planar gradiometers
%[dum, chanindx] = match_str('megplanar', hdr.chantype);
% 11 IAS
% chanindx = 1:11;
end
if isempty(chanindx)
error('the data does not seem to have head localization channels');
end
% this information is passed between the GUI callback functions
info = [];
info.hdr = hdr;
info.blocksize = blocksize;
info.isctf = isctf;
info.isneuromag = isneuromag;
info.cfg = cfg;
info.template = template;
info.sens = sens;
info.vol = vol;
info.dip = dip;
info.continue = true;
clear hdr blocksize isctf isneuromag cfg template sens vol dip
% initiate main figure
hMainFig = figure;
% attach the info in the figure
guidata(hMainFig, info);
% initiate gui controls
uicontrol_sub(hMainFig);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% this is the general BCI loop where realtime incoming data is handled
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
while ishandle(hMainFig) && info.continue % while the flag is one, the loop continues
% get the potentially updated information from the main window
info = guidata(hMainFig);
% determine number of samples available in buffer
info.hdr = ft_read_header(info.cfg.headerfile, 'cache', true, 'coordsys', 'dewar');
% see whether new samples are available
newsamples = (info.hdr.nSamples*info.hdr.nTrials-prevSample);
if newsamples>=info.blocksize
if strcmp(info.cfg.bufferdata, 'last')
begsample = info.hdr.nSamples*info.hdr.nTrials - info.blocksize + 1;
endsample = info.hdr.nSamples*info.hdr.nTrials;
elseif strcmp(info.cfg.bufferdata, 'first')
begsample = prevSample + 1;
endsample = prevSample + info.blocksize ;
else
error('unsupported value for cfg.bufferdata');
end
% remember up to where the data was read
prevSample = endsample;
count = count + 1;
fprintf('processing segment %d from sample %d to %d\n', count, begsample, endsample);
% read data segment from buffer
dat = ft_read_data(info.cfg.datafile, 'header', info.hdr, 'begsample', begsample, 'endsample', endsample, 'chanindx', chanindx, 'checkboundary', false);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% from here onward it is specific to the head localization
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% put the data in a fieldtrip-like raw structure
data.trial{1} = double(dat);
data.time{1} = offset2time(begsample, info.hdr.Fs, endsample-begsample+1);
data.label = info.hdr.label(chanindx);
data.hdr = info.hdr;
data.fsample = info.hdr.Fs;
if info.isneuromag && size(coilsignal,2)~=info.blocksize
% construct the reference signal for each of the coils
% this needs to be updated if the blocksize changes
ncoil = length(info.cfg.coilfreq);
if ncoil==0
error('no coil frequencies were specified');
else
time = (1:info.blocksize)./info.hdr.Fs;
coilsignal = zeros(ncoil, info.blocksize);
for i=1:ncoil
coilsignal(i,:) = exp(time*info.cfg.coilfreq(i)*1i*2*pi);
coilsignal(i,:) = coilsignal(i,:) / norm(coilsignal(i,:));
end
end
end
% compute the HPI coil positions, this takes some time
[hpi, info.dip] = data2hpi(data, info.dip, info.vol, info.sens, coilsignal, info.isctf, info.isneuromag); % for neuromag datasets this is relatively slow
if ~ishandle(hMainFig)
% the figure has been closed
break
end
% get the potentially updated information from the main window
info = guidata(hMainFig);
% update the info
info.hpi = hpi;
% store the updated gui variables
guidata(hMainFig, info);
% DRAW LEFT PANEL - TOP VIEW
a = subplot(1,2,1);
h = get(a, 'children');
hold on;
if ~isempty(h)
% done on every iteration
delete(h);
end
% draw the color-coded head and distances from the templates
draw_sub(hMainFig);
% show current timesample
title(sprintf('top view, runtime = %d s\n', round(mean(data.time{1}))));
% not needed any more
clear data;
% viewing angle
if info.isctf
view(-45, 90)
elseif info.isneuromag
view(0, 90)
end
% DRAW RIGHT PANEL - FRONT/REAR VIEW
b = subplot(1,2,2);
i = get(b, 'children');
hold on;
if ~isempty(i)
% done on every iteration
delete(i);
end
% draw the color-coded head and distances from the templates
draw_sub(hMainFig);
% viewing angle
if get(info.hViewRadioButton1,'Value') == 1
if info.isctf
view(135, 0)
elseif info.isneuromag
view(180, 0)
end
title(sprintf('anterior view, clock time %s', datestr(now))); % show current data & time
elseif get(info.hViewRadioButton2,'Value') == 1
if info.isctf
view(-45, 0)
elseif info.isneuromag
view(0, 0)
end
title(sprintf('posterior view, clock time %s', datestr(now))); % show current data & time
end
% force Matlab to update the figure
drawnow
end % if enough new samples
end % while true
close(hMainFig); % close the figure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that initiates the figure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function uicontrol_sub(handle, eventdata)
% get the info
info = guidata(handle);
% initiate figure
set(handle, 'KeyPressFcn', {@key_sub});
hUpdateButton = uicontrol(...
'Parent', handle,...
'Style', 'pushbutton',...
'String', 'Update',...
'Units', 'normalized',...
'Position', [.65 .0875 .15 .075],...
'FontSize', 12,...
'Callback', {@update_ButtonDownFcn});
hQuitButton = uicontrol(...
'Parent', handle,...
'Style', 'pushbutton',...
'String', 'Quit',...
'Units', 'normalized',...
'Position', [.8 .0875 .15 .075],...
'FontSize', 12,...
'Callback', {@quit_ButtonDownFcn});
hCoilCheckBox = uicontrol(...
'Parent', handle,...
'Style', 'checkbox',...
'String', 'Coils',...
'Units', 'normalized',...
'Position', [.05 .1 .075 .05],...
'FontSize', 8,...
'BackgroundColor', [.8 .8 .8],...
'Value', 1,...
'Callback', {@coil_CheckBox});
hHeadCheckBox = uicontrol(...
'Parent', handle,...
'Style', 'checkbox',...
'String', 'Head',...
'Units', 'normalized',...
'Position', [.125 .1 .075 .05],...
'FontSize', 8,...
'BackgroundColor', [.8 .8 .8],...
'Value', 1,...
'Callback', {@head_CheckBox});
hSensorCheckBox = uicontrol(...
'Parent', handle,...
'Style', 'checkbox',...
'String', 'Sensors',...
'Units', 'normalized',...
'Position', [.2 .1 .075 .05],...
'FontSize', 8,...
'BackgroundColor', [.8 .8 .8],...
'Value', 0,...
'Callback', {@sensor_CheckBox});
hViewRadioButton1 = uicontrol(...
'Parent', handle,...
'Style', 'radiobutton',...
'String', 'Anterior view',...
'Units', 'normalized',...
'Position', [.275 .1 .1 .05],...
'FontSize', 8,...
'BackgroundColor', [.8 .8 .8],...
'Value', 0,... % by default switched off
'Callback', {@view_RadioButton1});
hViewRadioButton2 = uicontrol(...
'Parent', handle,...
'Style', 'radiobutton',...
'String', 'Posterior view',...
'Units', 'normalized',...
'Position', [.375 .1 .1 .05],...
'FontSize', 8,...
'BackgroundColor', [.8 .8 .8],...
'Value', 1,... % by default switched on
'Callback', {@view_RadioButton2});
hBlocksizeMenu = uicontrol(...
'Parent', handle,...
'Style', 'popupmenu',...
'String', {'.1 second','.2 second','.5 second','1 second','1.5 second','2 seconds','5 seconds','10 seconds','30 seconds'},...
'Units', 'normalized',...
'Position', [.475 .0925 .1 .05],...
'FontSize', 8,...
'BackgroundColor', [.8 .8 .8],...
'Value', 4,... % default
'Callback', {@blocksize_Menu});
info.hQuitButton = hQuitButton;
info.hCoilCheckBox = hCoilCheckBox;
info.hHeadCheckBox = hHeadCheckBox;
info.hSensorCheckBox = hSensorCheckBox;
info.hViewRadioButton1 = hViewRadioButton1;
info.hViewRadioButton2 = hViewRadioButton2;
info.hBlocksizeMenu = hBlocksizeMenu;
% put the info back
guidata(handle, info);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that computes the HPI coil positions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [hpi, dip] = data2hpi(data, dip, vol, sens, coilsignal, isctf, isneuromag)
% The CTF275 system localizes the HPI coil positions online, and writes them
% to the dataset. For the Neuromag systems the signals evoked by the HPI coils
% are superimposed on the other signals. This requires additional online
% dipolefitting of those HPI coils.
if isctf
% assign the channels to the resp. coil coordinates
[dum, x1] = match_str('HLC0011', data.label);
[dum, y1] = match_str('HLC0012', data.label);
[dum, z1] = match_str('HLC0013', data.label);
[dum, x2] = match_str('HLC0021', data.label);
[dum, y2] = match_str('HLC0022', data.label);
[dum, z2] = match_str('HLC0023', data.label);
[dum, x3] = match_str('HLC0031', data.label);
[dum, y3] = match_str('HLC0032', data.label);
[dum, z3] = match_str('HLC0033', data.label);
% convert from meter to cm and assign to the resp. coil
hpi{1} = data.trial{1}([x1 y1 z1],end) * 100;
hpi{2} = data.trial{1}([x2 y2 z2],end) * 100;
hpi{3} = data.trial{1}([x3 y3 z3],end) * 100;
elseif isneuromag
% estimate the complex-valued MEG topography for each coil
% this implements a discrete Fourier transform (DFT)
topo = [];
%[x, ut] = svdfft( data.trial{1} );
%data.trial{1} = x;
topo = ft_preproc_detrend(data.trial{1}) * ctranspose(coilsignal);
% ignore the out-of-phase spectral component in the topography
topo = real(topo); % THIS SEEMS TO BE CRUCIAL
% fit a magnetic dipole to each of the topographies
constr.sequential = true; % for BTI systems this would be 'false' as all coils have the same frequency
constr.rigidbody = true;
% fit the coils together
dipall = [];
ncoil = numel(dip);
for i=1:ncoil
dipall.pos(i,:) = dip(i).pos;
end
dipall = dipole_fit(dipall, sens, vol, topo, 'constr', constr, 'display', 'off');
for i=1:ncoil
sel = (1:3) + 3*(i-1);
dip(i).pos = dipall.pos(i,:);
dip(i).mom = real(dipall.mom(sel,i)); % ignore the complex phase information
hpi{i} = dip(i).pos;
end
else
error('the data does not resemble ctf, nor neuromag')
end % if ctf or neuromag
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION that does the timing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [time] = offset2time(offset, fsample, nsamples)
offset = double(offset);
nsamples = double(nsamples);
time = (offset + (0:(nsamples-1)))/fsample;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which computes the circumcenter(x,y,z) of the 3D triangle (3 coils)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [cc] = circumcenter(hpi)
% use coordinates relative to point `a' of the triangle
xba = hpi{2}(1) - hpi{1}(1);
yba = hpi{2}(2) - hpi{1}(2);
zba = hpi{2}(3) - hpi{1}(3);
xca = hpi{3}(1) - hpi{1}(1);
yca = hpi{3}(2) - hpi{1}(2);
zca = hpi{3}(3) - hpi{1}(3);
% squares of lengths of the edges incident to `a'
balength = xba * xba + yba * yba + zba * zba;
calength = xca * xca + yca * yca + zca * zca;
% cross product of these edges
xcrossbc = yba * zca - yca * zba;
ycrossbc = zba * xca - zca * xba;
zcrossbc = xba * yca - xca * yba;
% calculate the denominator of the formulae
denominator = 0.5 / (xcrossbc * xcrossbc + ycrossbc * ycrossbc + zcrossbc * zcrossbc);
% calculate offset (from `a') of circumcenter
xcirca = ((balength * yca - calength * yba) * zcrossbc - (balength * zca - calength * zba) * ycrossbc) * denominator;
ycirca = ((balength * zca - calength * zba) * xcrossbc - (balength * xca - calength * xba) * zcrossbc) * denominator;
zcirca = ((balength * xca - calength * xba) * ycrossbc - (balength * yca - calength * yba) * xcrossbc) * denominator;
cc(1) = xcirca + hpi{1}(1,end);
cc(2) = ycirca + hpi{1}(2,end);
cc(3) = zcirca + hpi{1}(3,end);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which draws the color-coded head and distances to the template
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function draw_sub(handle)
% get the info
info = guidata(handle);
if get(info.hSensorCheckBox, 'Value') && ~isempty(info.sens)
% plot the sensors
hold on; ft_plot_sens(info.sens, 'style', 'k.');
end
% plot the template fiducial positions
if ~isempty(info.template)
if info.isctf
plot3(info.template(1,1), info.template(1,2), info.template(1,3), 'k^', 'MarkerSize', 27, 'LineWidth', 2); % chan X pos
plot3(info.template(2,1), info.template(2,2), info.template(2,3), 'ko', 'MarkerSize', 27, 'LineWidth', 2);
plot3(info.template(3,1), info.template(3,2), info.template(3,3), 'ko', 'MarkerSize', 27, 'LineWidth', 2);
text(-8,8, info.template(2,3), 'Left', 'FontSize', 15);
text(6,-6, info.template(3,3), 'Right', 'FontSize', 15);
elseif info.isneuromag
for j = 1:size(info.template,1)
plot3(info.template(j,1), info.template(j,2), info.template(j,3), 'ko', 'MarkerSize', 27, 'LineWidth', 2); % chan X pos
end
end
end
% plot the HPI coil positions
for j = 1:numel(info.hpi)
plot3(info.hpi{j}(1), info.hpi{j}(2), info.hpi{j}(3), 'ko', 'LineWidth', 1,'MarkerSize', 5)
end
if get(info.hCoilCheckBox, 'Value')
if info.isctf
% draw nasion position
if ~isempty(info.template)
if abs(info.template(1,1))-info.cfg.accuracy_green < abs(info.hpi{1}(1)) && abs(info.hpi{1}(1)) < abs(info.template(1,1))+info.cfg.accuracy_green ...
&& abs(info.template(1,2))-info.cfg.accuracy_green < abs(info.hpi{1}(2)) && abs(info.hpi{1}(2)) < abs(info.template(1,2))+info.cfg.accuracy_green ...
&& abs(info.template(1,3))-info.cfg.accuracy_green < abs(info.hpi{1}(3)) && abs(info.hpi{1}(3)) < abs(info.template(1,3))+info.cfg.accuracy_green
plot3(info.hpi{1}(1),info.hpi{1}(2),info.hpi{1}(3),'g^', 'MarkerFaceColor',[.5 1 .5],'MarkerSize',25)
head1 = true;
elseif abs(info.template(1,1))-info.cfg.accuracy_orange < abs(info.hpi{1}(1)) && abs(info.hpi{1}(1)) < abs(info.template(1,1))+info.cfg.accuracy_orange ...
&& abs(info.template(1,2))-info.cfg.accuracy_orange < abs(info.hpi{1}(2)) && abs(info.hpi{1}(2)) < abs(info.template(1,2))+info.cfg.accuracy_orange ...
&& abs(info.template(1,3))-info.cfg.accuracy_orange < abs(info.hpi{1}(3)) && abs(info.hpi{1}(3)) < abs(info.template(1,3))+info.cfg.accuracy_orange
plot3(info.hpi{1}(1),info.hpi{1}(2),info.hpi{1}(3),'y^', 'MarkerFaceColor',[1 .5 0],'MarkerEdgeColor',[1 .5 0],'MarkerSize',25)
head1 = false;
else % when not in correct position
plot3(info.hpi{1}(1),info.hpi{1}(2), info.hpi{1}(3),'r^', 'MarkerFaceColor',[1 0 0],'MarkerSize',25)
head1 = false;
end
else
plot3(info.hpi{1}(1),info.hpi{1}(2), info.hpi{1}(3),'r^', 'MarkerFaceColor',[1 0 0],'MarkerSize',25)
head1 = false;
end
% draw left ear position
if ~isempty(info.template)
if abs(info.template(2,1))-info.cfg.accuracy_green < abs(info.hpi{2}(1)) && abs(info.hpi{2}(1)) < abs(info.template(2,1))+info.cfg.accuracy_green ...
&& abs(info.template(2,2))-info.cfg.accuracy_green < abs(info.hpi{2}(2)) && abs(info.hpi{2}(2)) < abs(info.template(2,2))+info.cfg.accuracy_green ...
&& abs(info.template(2,3))-info.cfg.accuracy_green < abs(info.hpi{2}(3)) && abs(info.hpi{2}(3)) < abs(info.template(2,3))+info.cfg.accuracy_green
plot3(info.hpi{2}(1),info.hpi{2}(2),info.hpi{2}(3),'go', 'MarkerFaceColor',[.5 1 .5],'MarkerSize',25)
head2 = true;
elseif abs(info.template(2,1))-info.cfg.accuracy_orange < abs(info.hpi{2}(1)) && abs(info.hpi{2}(1)) < abs(info.template(2,1))+info.cfg.accuracy_orange ...
&& abs(info.template(2,2))-info.cfg.accuracy_orange < abs(info.hpi{2}(2)) && abs(info.hpi{2}(2)) < abs(info.template(2,2))+info.cfg.accuracy_orange ...
&& abs(info.template(2,3))-info.cfg.accuracy_orange < abs(info.hpi{2}(3)) && abs(info.hpi{2}(3)) < abs(info.template(2,3))+info.cfg.accuracy_orange
plot3(info.hpi{2}(1),info.hpi{2}(2),info.hpi{2}(3),'yo', 'MarkerFaceColor',[1 .5 0],'MarkerEdgeColor',[1 .5 0],'MarkerSize',25)
head2 = false;
else % when not in correct position
plot3(info.hpi{2}(1),info.hpi{2}(2), info.hpi{2}(3),'ro', 'MarkerFaceColor',[1 0 0],'MarkerSize',25)
head2 = false;
end
else
plot3(info.hpi{2}(1),info.hpi{2}(2), info.hpi{2}(3),'ro', 'MarkerFaceColor',[1 0 0],'MarkerSize',25)
head2 = false;
end
% draw right ear position
if ~isempty(info.template)
if abs(info.template(3,1))-info.cfg.accuracy_green < abs(info.hpi{3}(1)) && abs(info.hpi{3}(1)) < abs(info.template(3,1))+info.cfg.accuracy_green ...
&& abs(info.template(3,2))-info.cfg.accuracy_green < abs(info.hpi{3}(2)) && abs(info.hpi{3}(2)) < abs(info.template(3,2))+info.cfg.accuracy_green ...
&& abs(info.template(3,3))-info.cfg.accuracy_green < abs(info.hpi{3}(3)) && abs(info.hpi{3}(3)) < abs(info.template(3,3))+info.cfg.accuracy_green
plot3(info.hpi{3}(1),info.hpi{3}(2),info.hpi{3}(3),'go', 'MarkerFaceColor',[.5 1 .5],'MarkerSize',25)
head3 = true;
elseif abs(info.template(3,1))-info.cfg.accuracy_orange < abs(info.hpi{3}(1)) && abs(info.hpi{3}(1)) < abs(info.template(3,1))+info.cfg.accuracy_orange ...
&& abs(info.template(3,2))-info.cfg.accuracy_orange < abs(info.hpi{3}(2)) && abs(info.hpi{3}(2)) < abs(info.template(3,2))+info.cfg.accuracy_orange ...
&& abs(info.template(3,3))-info.cfg.accuracy_orange < abs(info.hpi{3}(3)) && abs(info.hpi{3}(3)) < abs(info.template(3,3))+info.cfg.accuracy_orange
plot3(info.hpi{3}(1),info.hpi{3}(2),info.hpi{3}(3),'yo', 'MarkerFaceColor',[1 .5 0],'MarkerEdgeColor',[1 .5 0],'MarkerSize',25)
head3 = false;
else % when not in correct position
plot3(info.hpi{3}(1),info.hpi{3}(2), info.hpi{3}(3),'ro', 'MarkerFaceColor',[1 0 0],'MarkerSize',25)
head3 = false;
end
else
plot3(info.hpi{3}(1),info.hpi{3}(2), info.hpi{3}(3),'ro', 'MarkerFaceColor',[1 0 0],'MarkerSize',25)
head3 = false;
end
if get(info.hHeadCheckBox, 'Value')
% draw 3d head
cc = circumcenter(info.hpi);
x_radius = sqrt((info.hpi{2}(1) - cc(1))^2 + (info.hpi{2}(2) - cc(2))^2);
y_radius = sqrt((info.hpi{3}(1) - cc(1))^2 + (info.hpi{3}(2) - cc(2))^2);
[xe, ye, ze] = ellipsoid(cc(1),cc(2),cc(3),x_radius,y_radius,11);
hh = surfl(xe, ye, ze);
shading interp
if get(info.hCoilCheckBox, 'Value') % this only works if 'coils' are updated
if head1 == true && head2 == true && head3 == true
colormap cool
else
colormap hot
end
end
alpha(.15)
end
elseif info.isneuromag
% plot fitted positions of each coil
if ~isempty(info.template)
for j = 1:size(info.template,1)
if abs(info.template(j,1))-info.cfg.accuracy_green < abs(info.hpi{j}(1)) && abs(info.hpi{j}(1)) < abs(info.template(j,1))+info.cfg.accuracy_green ...
&& abs(info.template(j,2))-info.cfg.accuracy_green < abs(info.hpi{j}(2)) && abs(info.hpi{j}(2)) < abs(info.template(j,2))+info.cfg.accuracy_green ...
&& abs(info.template(j,3))-info.cfg.accuracy_green < abs(info.hpi{j}(3)) && abs(info.hpi{j}(3)) < abs(info.template(j,3))+info.cfg.accuracy_green
plot3(info.hpi{j}(1),info.hpi{j}(2),info.hpi{j}(3),'go', 'MarkerFaceColor',[.5 1 .5],'MarkerSize',25)
elseif abs(info.template(j,1))-info.cfg.accuracy_orange < abs(info.hpi{j}(1,end)) && abs(info.hpi{j}(1)) < abs(info.template(j,1))+info.cfg.accuracy_orange ...
&& abs(info.template(j,2))-info.cfg.accuracy_orange < abs(info.hpi{j}(2)) && abs(info.hpi{j}(2)) < abs(info.template(j,2))+info.cfg.accuracy_orange ...
&& abs(info.template(j,3))-info.cfg.accuracy_orange < abs(info.hpi{j}(3)) && abs(info.hpi{j}(3)) < abs(info.template(j,3))+info.cfg.accuracy_orange
plot3(info.hpi{j}(1),info.hpi{j}(2),info.hpi{j}(3),'yo', 'MarkerFaceColor',[1 .5 0],'MarkerEdgeColor',[1 .5 0],'MarkerSize',25)
else % when not in correct position
plot3(info.hpi{j}(1,end),info.hpi{j}(2), info.hpi{j}(3),'ro', 'MarkerFaceColor',[1 0 0],'MarkerSize',25);
end
end
else
for j = 1:numel(info.hpi)
plot3(info.hpi{j}(1),info.hpi{j}(2), info.hpi{j}(3),'ro', 'MarkerFaceColor',[1 0 0],'MarkerSize',25);
end
end
end
end
% axis
grid on
xlabel('x (cm)');
ylabel('y (cm)');
zlabel('z (cm)');
set(gca, 'xtick', -10:2:10)
set(gca, 'ytick', -10:2:10)
set(gca, 'ztick', -40:2:-10) % note the different scaling
axis square
% put the info back
guidata(handle, info);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTION which handles hot keys in the current plot
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function key_sub(handle, eventdata)
% get the info
info = guidata(handle);
switch eventdata.Key
case 'u'
% update the template positions
fprintf('updating template coordinates \n')
for j = 1:numel(info.hpi)
info.template(j,:) = info.hpi{j}(:); % chan X pos
end
% write template position to text file for later re-positioning
template_time = [date datestr(now,'-HH-MM-SS')];
fprintf('writing to %s.txt \n', template_time);
dlmwrite([template_time '.txt'], info.template, ' ');
case 'q'
% stop the application
fprintf('stopping the application \n')
info.continue = false;
case 'c'
% display the sensors/dewar
if get(info.hCoilCheckBox,'Value') == 0;
fprintf('displaying coils \n')
set(info.hCoilCheckBox, 'Value', 1); % toggle on
elseif get(info.hCoilCheckBox,'Value') == 1;
set(info.hCoilCheckBox, 'Value', 0); % toggle off
end
case 'h'
% display the sensors/dewar
if get(info.hHeadCheckBox,'Value') == 0;
fprintf('displaying head \n')
set(info.hHeadCheckBox, 'Value', 1); % toggle on
elseif get(info.hHeadCheckBox,'Value') == 1;
set(info.hHeadCheckBox, 'Value', 0); % toggle off
end
case 's'
% display the sensors/dewar
if get(info.hSensorCheckBox,'Value') == 0;
fprintf('displaying sensors/dewar \n')
set(info.hSensorCheckBox, 'Value', 1); % toggle on
elseif get(info.hSensorCheckBox,'Value') == 1;
set(info.hSensorCheckBox, 'Value', 0); % toggle off
end
otherwise
fprintf('no command executed \n')
end
% put the info back
guidata(handle, info);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% SUBFUNCTIONs which handle button presses
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function update_ButtonDownFcn(handle, eventdata)
% get the info
info = guidata(handle);
% update the template positions
fprintf('updating template coordinates \n')
for j = 1:numel(info.hpi)
info.template(j,:) = info.hpi{j}(:); % chan X pos
end
% write template position to text file for later re-positioning
template_time = [date datestr(now,'-HH-MM-SS')];
fprintf('writing to %s.txt \n', template_time);
dlmwrite([template_time '.txt'], info.template, ' ');
% put the info back
guidata(handle, info);
function quit_ButtonDownFcn(handle, eventdata)
% get the info
info = guidata(handle);
% stop the application
fprintf('stopping the application \n')
info.continue = false;
% put the info back
guidata(handle, info);
function coil_CheckBox(hObject, eventdata)
% toggle coils display
function head_CheckBox(hObject, eventdata)
% toggle head display
function sensor_CheckBox(hObject, eventdata)
% toggle sensors display
function view_RadioButton1(handle, eventdata)
% get the info
info = guidata(handle);
% toggle front view - in combination with view_RadioButton2
if get(info.hViewRadioButton1,'Value') == 1;
set(info.hViewRadioButton2, 'Value', 0); % toggle off radiobutton 2
set(info.hViewRadioButton1, 'Value', 1); % toggle on radiobutton 1
elseif get(info.hViewRadioButton1,'Value') == 0;
set(info.hViewRadioButton2, 'Value', 1); % toggle on radiobutton 2
set(info.hViewRadioButton1, 'Value', 0); % toggle off radiobutton 1
end
% put the info back
guidata(handle, info);
function view_RadioButton2(handle, eventdata)
% get the info
info = guidata(handle);
% toggle back view - in combination with view_RadioButton1
if get(info.hViewRadioButton2,'Value') == 1;
set(info.hViewRadioButton1, 'Value', 0); % toggle off radiobutton 1
set(info.hViewRadioButton2, 'Value', 1); % toggle on radiobutton 2
elseif get(info.hViewRadioButton2,'Value') == 0;
set(info.hViewRadioButton1, 'Value', 1); % toggle on radiobutton 1
set(info.hViewRadioButton2, 'Value', 0); % toggle off radiobutton 2
end
% put the info back
guidata(handle, info);
function blocksize_Menu(handle, eventdata)
% get the info
info = guidata(handle);
val = get(info.hBlocksizeMenu, 'Value');
switch val
case 1
info.blocksize = round(0.1 * info.hdr.Fs); % 0.1 s
case 2
info.blocksize = round(0.2 * info.hdr.Fs);
case 3
info.blocksize = round(0.5 * info.hdr.Fs);
case 4
info.blocksize = round(1 * info.hdr.Fs);
case 5
info.blocksize = round(1.5 * info.hdr.Fs);
case 6
info.blocksize = round(2 * info.hdr.Fs);
case 7
info.blocksize = round(5 * info.hdr.Fs);
case 8
info.blocksize = round(10 * info.hdr.Fs);
case 9
info.blocksize = round(30 * info.hdr.Fs);
end
fprintf('changing blocksize to %d samples\n', info.blocksize);
% put the info back
guidata(handle, info);
|
github
|
lcnhappe/happe-master
|
readBESAimage.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/besa/readBESAimage.m
| 8,358 |
utf_8
|
4969e3fff82f74a3094d9595d66499e3
|
function image = readBESAimage(filename)
% readBESAimage reads information from exported BESA images (Beamformer,
% LAURA, sLORETA, swLORETA, LORETA, sSLOFO, User-Defined image, surface
% minimum norm, Probe scan, Sensitivity). The function poutput is a struct
% with fields containing all relevant information from the image file.
%
% Use as
% image = readBESAimage(filename)
% Modified April 26, 2006 Robert Oostenveld
% Modified November 6, 2006 Karsten Hoechstetter
% Modified January 2, 2008 Karsten Hoechstetter
if isempty(findstr(filename,'.'))
filename = [filename,'.dat'];
end
fp = fopen(filename);
ImageVersion = fgetl(fp);
% Check Version Number
version = str2num(ImageVersion(findstr(ImageVersion,':')+1:length(ImageVersion)));
switch version
case 1
image=import_v1(ImageVersion,fp);
case 2
image=import_v2(fp);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Image Version 1.0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function image=import_v1(ImageVersion,fp)
% Check type of Image
if ~isempty(findstr(ImageVersion,'MN'))
image.Imagetype = 'Minimum Norm';
image.Imagemode = 'Time';
else
fgetl(fp);
ImageInfo = fgetl(fp);
if ~isempty(findstr(ImageInfo,'Sens.'))
image.Imagetype = 'Sensitivity';
elseif ~isempty(findstr(ImageInfo,'MSBF'))
image.Imagetype = 'MSBF';
image.Imagemode = 'Time-Frequency';
elseif ~isempty(findstr(ImageInfo,'MSPS'))
image.Imagetype = 'MSPS';
if ~isempty(findstr(ImageInfo,'Image (TF)'))
image.Imagemode = 'Time-Frequency';
else
image.Imagemode = 'Time';
end
end
if strcmp(ImageInfo(end-3:end),'[dB]')
image.Units = 'dB';
else
image.Units = '%';
end
end
% Extract additional information (time and frequency, source, MN Info)
if strcmp(image.Imagemode,'Time-Frequency')
TimeSeparator = findstr(ImageInfo,' : ');
Blanks = findstr(ImageInfo,' ');
[x,Index] = min(abs(Blanks-TimeSeparator));
TimeIndex=Blanks(Index-1);
image.Time = sscanf(ImageInfo(TimeIndex:end),'%s',4);
image.Frequency = sscanf(ImageInfo(findstr(ImageInfo,'ms')+3:end),'%s',2);
elseif strcmp(image.Imagetype,'Sensitivity')
image.Source = ImageInfo(findstr(ImageInfo,' - ')+3:end);
elseif strcmp(image.Imagetype,'Minimum Norm')
fgetl(fp);
h = fgetl(fp); image.DataFile = h(21:end);
h = fgetl(fp); image.Condition = h(21:end);
h = fgetl(fp);
if(~isempty(h))
image.DataType = h(21:end);
h = fgetl(fp); image.Method = h(21:end);
fgetl(fp); % Empty line
end
if(strcmp(image.Method,'Surface Minimum Norm'))
h = fgetl(fp); image.DepthWeighting = h(21:end);
h = fgetl(fp); image.SpTmpWeighting = h(21:end);
h = fgetl(fp); image.SpTmpWeightingType = h(21:end);
h = fgetl(fp); image.Dimension = str2num(h(21:end));
h = fgetl(fp); image.NoiseEstimation = h(21:end);
h = fgetl(fp); image.NoiseWeighting = h(21:end);
h = fgetl(fp); image.NoiseScaleFactor = str2num(h(21:end));
h = fgetl(fp); image.SelMeanNoise = h(21:end);
elseif(strcmp(image.Method,'Cortical LORETA'))
h = fgetl(fp); image.DepthWeighting = h(25:end);
h = fgetl(fp); image.RegularizationType = h(25:end);
h = fgetl(fp); image.RegularizationValue = h(25:end);
h = fgetl(fp); image.LaplacianType = h(25:end);
end
fgetl(fp);
h = fgetl(fp); image.Locations = str2num(h(21:end));
h = fgetl(fp); image.TimeSamples = str2num(h(21:end));
fgetl(fp); fgetl(fp); fgetl(fp);
end
% Get Coordinates and Data
if ~isempty(strmatch(image.Imagetype,strvcat('MSPS','MSBF','Sensitivity')))
% Get Coordinates
fgetl(fp); fgetl(fp);
h = fgetl(fp);
hx = sscanf(h,'X: %f %f %d');
xmin = hx(1); xmax = hx(2); xnum = hx(3);
h = fgetl(fp);
hy = sscanf(h,'Y: %f %f %d');
ymin = hy(1); ymax = hy(2); ynum = hy(3);
h = fgetl(fp);
hz = sscanf(h,'Z: %f %f %d');
zmin = hz(1); zmax = hz(2); znum = hz(3);
fgetl(fp);
image.Coordinates=struct('X',{[xmin:floor((xmax-xmin)/(xnum-1)*10000)/10000:xmax]},...
'Y',{[ymin:floor((ymax-ymin)/(ynum-1)*10000)/10000:ymax]},...
'Z',{[zmin:floor((zmax-zmin)/(znum-1)*10000)/10000:zmax]});
% Get Data
image.Data = zeros(xnum,ynum,znum);
for z=1:znum
fgetl(fp);
a=fscanf(fp,'%f',[xnum,ynum]);
for x=1:xnum
for y=1:ynum
image.Data(x,y,z)=a(x,y);
end
end
fgetl(fp);fgetl(fp);
end
% Minimum Norm Image
elseif ~isempty(strmatch(image.Imagetype,('Minimum Norm')))
fscanf(fp,'Latency (milliseconds):');
image.Latency = fscanf(fp,'%f',[1,image.TimeSamples]);
image.Coordinates = zeros(image.Locations,3);
image.Data = zeros(image.Locations,image.TimeSamples);
for i=1:image.Locations
h=fscanf(fp,'%f',[1,3]);
image.Coordinates(i,:) = h;
image.Data(i,:)=fscanf(fp,'%f',[1,image.TimeSamples]);
end
end
fclose(fp);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Image Version 2.0
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function image=import_v2(fp)
fgetl(fp);
c=fgetl(fp); image.DataFile = c(21:end);
c=fgetl(fp); image.Condition = c(21:end);
c=fgetl(fp);
if strfind(c,'Method')
image.Imagetype = c(21:end);
image.Imagemode = 'Time';
c=fgetl(fp); image.Regularization = c(21:end);
c=fgetl(fp);
t=findstr(c,' ms');
if t
image.Latency = c(1:t-1);
else t=0;
end
image.Units = strtrim(c(t+3:end));
elseif ~isempty(findstr(c,'MSBF'))
image.Imagetype = 'MSBF';
image.Imagemode = 'Time-Frequency';
if strcmp(c(end-3:end),'[dB]')
image.Units = 'dB';
else
image.Units = '%';
end
elseif ~isempty(findstr(c,'MSPS'))
image.Imagetype = 'MSPS';
if ~isempty(findstr(c,'Image (TF)'))
image.Imagemode = 'Time-Frequency';
else
image.Imagemode = 'Time';
image.Latency = c(1:findstr(c,' ms')-1);
end
if strcmp(c(end-3:end),'[dB]')
image.Units = 'dB';
else
image.Units = '%';
end
elseif ~isempty(findstr(c,'Sens'))
image.Imagemode = 'Sensitivity';
image.Units = '%';
image.Source = sscanf(c,'Src. %i');
end
fgetl(fp);fgetl(fp);
c=fgetl(fp); X=sscanf(c,'X: %f %f %f');
c=fgetl(fp); Y=sscanf(c,'Y: %f %f %f');
c=fgetl(fp); Z=sscanf(c,'Z: %f %f %f');
image.Coordinates=struct('X',{[X(1):floor((X(2)-X(1))/(X(3)-1)*10000)/10000:X(2)]},...
'Y',{[Y(1):floor((Y(2)-Y(1))/(Y(3)-1)*10000)/10000:Y(2)]},...
'Z',{[Z(1):floor((Z(2)-Z(1))/(Z(3)-1)*10000)/10000:Z(2)]});
fgetl(fp);
c=fgetl(fp);
if strfind(c,'Voxel locations')
image.Coordinates.X = zeros(1,X(3)*Y(3)*Z(3));
image.Coordinates.Y = zeros(1,X(3)*Y(3)*Z(3));
image.Coordinates.Z = zeros(1,X(3)*Y(3)*Z(3));
for i=1:X(3)*Y(3)*Z(3)
try
c=fgetl(fp); C = sscanf(c,'%f %f %f %f %f %f');
image.Coordinates.X(i)=C(4);
image.Coordinates.Y(i)=C(5);
image.Coordinates.Z(i)=C(6);
catch
image.Coordinates.X=image.Coordinates.X(1:i-1);
image.Coordinates.Y=image.Coordinates.Y(1:i-1);
image.Coordinates.Z=image.Coordinates.Z(1:i-1);
break
end
end
for t=1:1000000
try
temp=fscanf(fp,'%f',[3,length(image.Coordinates.X)]);
image.Data(:,:,t)=temp';
fgetl(fp); fgetl(fp);
catch
break
end
end
elseif strfind(c,'Sample') % Time Series
for zindex=1:Z(3)
% Fehlt noch: Latenz mit auslesen
for t=1:100000
try
for zindex=1:Z(3)
fgetl(fp);
image.Data(:,:,zindex,t)=fscanf(fp,'%f',[X(3),Y(3)]);
fgetl(fp); fgetl(fp);
end
fgetl(fp);
catch
break
end
end
end
else % Single Image
image.Data=zeros(X(3),Y(3),Z(3));
image.Data(:,:,1)=fscanf(fp,'%f',[X(3),Y(3)]);
for zindex=2:Z(3)
fgetl(fp); fgetl(fp); fgetl(fp);
image.Data(:,:,zindex)=fscanf(fp,'%f',[X(3),Y(3)]);
end
end
fclose(fp);
function matrix=getblock(fp,no_rows,no_columns)
matrix = zeros(no_rows,no_columns);
for row=1:no_rows
fgetl(fp)
matrix(row,:)=str2double(fgetl(fp));
end
|
github
|
lcnhappe/happe-master
|
load_audio0123.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/videomeg/load_audio0123.m
| 3,277 |
utf_8
|
010d2cece743343ca3b509e44403cb33
|
function [ts, ids, offset, data, srate, site_id, is_sender] = load_audio0123(filename)
% Read an audio file from the disk.
%--------------------------------------------------------------------------
% Copyright (C) 2015 BioMag Laboratory, Helsinki University Central Hospital
%
% 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, version 3.
%
% 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/>.
%--------------------------------------------------------------------------
MAGIC_STR = 'ELEKTA_AUDIO_FILE';
h = fopen(filename, 'rb');
header_str = fread(h, length(MAGIC_STR), 'uchar');
% make sure the file is a valid audio file
assert(strcmp(char(header_str'), MAGIC_STR));
ver = fread(h, 1, 'uint32');
assert(ver==0 || ver==1 || ver==2 || ver==3);
if ver==3
site_id = fread(h, 1, 'uint8');
sender_flag = fread(h, 1, 'uint8');
is_sender = (sender_flag==1);
else
site_id = -1;
is_sender = false;
end
srate = fread(h, 1, 'uint32');
nchans = fread(h, 1, 'uint32');
% get the size of the data part of the file in bytes
dt_start = ftell(h);
fseek(h, 0 ,'eof');
dt_end = ftell(h);
fseek(h, dt_start, 'bof');
% read the buffer size from the first data chunk
[t, id, buflen] = read_attrib(h, ver);
frames_per_buf = buflen/(2*nchans);
if(ver==0 || ver==1)
attrib_sz = 8 + 4;
end
if(ver==2 || ver==3)
attrib_sz = 8 + 8 + 4;
end
assert(mod((dt_end - dt_start), (attrib_sz + buflen)) == 0)
numof_chunks = (dt_end - dt_start) / (attrib_sz + buflen);
% allocate the memory
ts = zeros(numof_chunks, 1, 'uint64');
ids = zeros(numof_chunks, 1, 'uint64');
data = zeros(frames_per_buf*nchans, numof_chunks);
% compute offset
offset = [1 : frames_per_buf : frames_per_buf*numof_chunks]';
% read the data
fprintf('load_audio_0123: reading audio data from %s...\n',filename);
fseek(h, dt_start, 'bof');
for i = 1 : numof_chunks
PRINT_INTERVAL=1e6; % print status messages at this interval
[ts(i), ids(i), blen] = read_attrib(h, ver);
assert(blen == buflen);
data(:,i) = fread(h, buflen/2, 'int16');
if mod(i, PRINT_INTERVAL) == 0
fprintf('load_audio_0123: loaded %g buffers of %i bytes\n', i, buflen);
end
end
fclose(h);
data = reshape(data, nchans, frames_per_buf*numof_chunks)';
end
function [t, id, blen] = read_attrib(h, ver)
assert(ver==0 || ver==1 || ver==2 || ver==3);
t = fread(h, 1, 'uint64=>uint64');
if(ver==2 || ver==3)
id = fread(h, 1, 'uint64=>uint64');
else
id = -1;
end
blen = fread(h, 1, 'uint32');
end
|
github
|
lcnhappe/happe-master
|
comp_tstamps.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/videomeg/comp_tstamps.m
| 3,190 |
utf_8
|
f9969e0dd7f6d27c544b26a34bf20649
|
function data_tstamps = comp_tstamps(inp, sfreq)
% COMP_TSTAMPS - extract timestamps from a trigger channel
% INP - vector of samples for the trigger channel
% SFREQ - sampling frequency
% Return the vector of the same length as INP, containing timestamps for
% each entry of INP. For detecting timestamps use parameters defined
% below (should match the parameters used for generating the timing
% sequence).
%
% TODO: this function does not handle the boundary case for the first train
% of pulses correctly. This is because there is no trigger before the train
% and there will be no dtrigs value before the first trigger of the train.
% Thus the first pulse train will always be ignored. It would be neat to fix
% this.
%--------------------------------------------------------------------------
% Copyright (C) 2015 BioMag Laboratory, Helsinki University Central Hospital
%
% 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, version 3.
%
% 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/>.
%--------------------------------------------------------------------------
THRESH = 3;
BASELINE = 5; % seconds
TRAIN_STEP = 0.015; % seconds
NBITS = 43; % including the parity bit
% find the upgoing flank of all triggers (threshold crossings)
trigs = find([0 diff(inp>THRESH)>0]);
% determine the duration of each trigger
d = trigs(2:end) - trigs(1:end-1);
samps = [];
tss = [];
% iterate over all timestamp candidates
for i = find(d > BASELINE * sfreq)
ts = read_timestamp(d, i, TRAIN_STEP*sfreq, NBITS);
if ts ~= -1
samps(end+1) = trigs(i+1);
tss(end+1) = ts;
end
end
% fit timestamps to samples with linear regression
p = polyfit(samps, tss, 1);
data_tstamps = [1:length(inp)] * p(1) + p(2);
% DEBUG
%figure;
%title('Fit accuracy');
%plot(samps/sfreq, p(1)*samps+p(2) - tss);
%xlabel('time, seconds');
%ylabel('linear fit error, msec');
% ~DEBUG
function ts = read_timestamp(dtrigs, cur, step, nbits)
% READ_TIMESTAMP - read and decode one timestamp
ts = 0;
parity = false;
for i = 1 : nbits
% end of input reached before NBITS bits read
if cur+i > length(dtrigs)
warning('end of input reached before NBITS bits read');
ts = -1;
return;
end
% invalid interval between two triggers
if (dtrigs(cur+i) < step*1.5) | (dtrigs(cur+i) > step*4.5)
warning('invalid interval between two triggers');
ts = -1;
return;
end
if dtrigs(cur+i) > step*3
parity = ~parity;
if i < nbits % don't read the parity bit into the timestamp
ts = ts + 2^(i-1);
end
end
end
if parity
warning('parity check failed');
ts = -1;
end
|
github
|
lcnhappe/happe-master
|
mff_micros2Sample.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/egi_mff/mff_micros2Sample.m
| 527 |
utf_8
|
97dfab73c9d72c1615c28404bc7ca63a
|
%% mff_micros2Sample.m
% Matlab File
% author Colin Davey
% date 3/2/2012
% Copyright 2012, 2013 EGI. All rights reserved.
% Support routine for MFF Matlab code. Not intended to be called directly.
%
% Converts from microseconds to samples, given the sampling rate.
%%
function [sampleNum, remainder] = mff_micros2Sample(microsecs, sampRate)
microsecs = double(microsecs);
sampDuration = 1000000/sampRate;
sampleNum = microsecs/sampDuration;
remainder = uint64(rem(microsecs, sampDuration));
sampleNum = fix(sampleNum);
|
github
|
lcnhappe/happe-master
|
mff_valid.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/egi_mff/mff_valid.m
| 2,663 |
utf_8
|
04a88daab90374c3cfc10d82a25c9c9e
|
%% mff_valid.m
% Matlab File
% author Colin Davey
% date 12/3/2013
% Copyright 2013 EGI. All rights reserved.
% Support routine for MFF Matlab code. Not intended to be called directly.
%
% Tests whether a file is valid, and throws an exception if not. Gives an
% informational warning if filename doesn't end in '.mff'.
%%
function mff_valid(filePath)
valid = false;
filePathExist = exist(filePath);
% Check that filePath exists.
if filePathExist == 0
theException = MException('EGI_MFF:MFF_NO_EXIST', 'MFF does not exist.');
% Check that filePath isn't a regular file.
elseif filePathExist == 2
theException = MException('EGI_MFF:MFF_NOT_DIR', 'MFF is not a folder or package.');
% Check that filePath is a directory.
elseif filePathExist ~= 7
theException = MException('EGI_MFF:MFF_NOT_DIR_OR_FILE', 'MFF is not a folder, package or file.');
else
% Check that filePath/info.xml exists and is a file.
if exist([filePath filesep 'info.xml']) ~= 2
theException = MException('EGI_MFF:INVALID_NO_INFO', 'MFF is not valid. There is no info.xml file.');
% Check that filePath/info1.xml exists and is a file.
elseif exist([filePath filesep 'info1.xml']) ~= 2
theException = MException('EGI_MFF:INVALID_NO_INFO1', 'MFF is not valid. There is no info1.xml file.');
% Check that filePath/signal1.bin exists and is a file.
elseif exist([filePath filesep 'signal1.bin']) ~= 2
theException = MException('EGI_MFF:INVALID_NO_SIGNAL1', 'MFF is not valid. There is no signal1.bin file.');
% Check the version.
else
infoObj = mff_getObject(com.egi.services.mff.api.MFFResourceType.kMFF_RT_Info, 'info.xml', filePath);
ver = infoObj.getMFFVersion;
if ver ~= 3;
theException = MException('EGI_MFF:WRONG_VER', 'MFF is not version 3. Please convert using EGI''s MFF File Converter. Contact [email protected] form more information.');
else
valid = true;
end
end
end
if ~valid
throw(theException);
end
% Delete DS_Store file that gets generated when moving to a PC.
fullDS_StorePath = [filePath filesep '._.DSStore'];
if exist(fullDS_StorePath, 'file') == 2
delete(fullDS_StorePath);
end
% Give a warning if name doesn't end in '.mff'.
mff_warning = '*** Filename does not end in ''.mff''. This can cause a problem for some versions of NetStation. ***';
if size(filePath,2) < size('.mff',2) + 1
% warning('EGI_MFF:EXT_WARNING', mff_warning);
fprintf('%s\n', mff_warning);
elseif ~(strcmp(lower(filePath(end-3:end)), '.mff'))
% warning('EGI_MFF:EXT_WARNING', mff_warning);
fprintf('%s\n', mff_warning);
end
|
github
|
lcnhappe/happe-master
|
read_mff_header.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/egi_mff/read_mff_header.m
| 2,673 |
utf_8
|
3709cd08e3c235fbeeed3cc7e8419f1e
|
%% read_mff_header.m
% Matlab File
% author Colin Davey
% date 3/2/2012, 4/15/2014
% Copyright 2012, 2014 EGI. All rights reserved.
%
% Takes the path to the data and returns the header in the structure
% described at http://www.fieldtriptoolbox.org/reference/ft_read_header.
%
% filePath ? The path to the .mff file.
%
% Return a Field Trip header. Pulls most of the information from the
% summary info returned by mff_getSummaryInfo. Stores the summary info in
% the .orig field. Gets the sensor label info from the sensor layout
% object. Gets the pib channel info from the pns set object.
%%
function header = read_mff_header(filePath)
summaryInfo = mff_getSummaryInfo(filePath);
% Pull header info from the summary info.
header.Fs = summaryInfo.sampRate;
header.nChans = summaryInfo.nChans;
header.nSamplesPre = 0;
if strcmp(summaryInfo.epochType, 'seg')
header.nSamples = summaryInfo.epochNumSamps(1);
header.nTrials = size(summaryInfo.epochBeginSamps,2);
% if Time0 is the same for all segments...
if size(unique(summaryInfo.epochTime0),2) == 1
header.nSamplesPre = summaryInfo.epochTime0(1);
end
else
header.nSamples = sum(summaryInfo.epochNumSamps);
header.nTrials = 1;
end
% Add the sensor info.
sensorLayoutObj = mff_getObject(com.egi.services.mff.api.MFFResourceType.kMFF_RT_SensorLayout, 'sensorLayout.xml', filePath);
sensors = sensorLayoutObj.getSensors();
nChans = 0;
for p = 1:sensors.size
sensorObj = sensors.get(p-1); % sensors 0 based
sensorType = sensorObj.getType;
if sensorType == 0 || sensorType == 1
tmpLabel = sensorObj.getName;
if strcmp(tmpLabel,'')
tmpLabel = sprintf('E%d', sensorObj.getNumber);
else
tmpLabel = char(tmpLabel);
end
header.label{p} = tmpLabel;
header.chantype{p} = 'eeg'; % hard-coded for now.
header.chanunit{p} = 'uV'; % hard-coded for now.
nChans = nChans + 1;
end
end
if nChans ~= header.nChans
%Error. Should never occur. todo?: error handling
end
% Add the pib channel info.
if summaryInfo.pibNChans > 0
pnsSetObj = mff_getObject(com.egi.services.mff.api.MFFResourceType.kMFF_RT_PNSSet, 'pnsSet.xml', filePath);
pnsSensors = pnsSetObj.getPNSSensors;
for p = 1:summaryInfo.pibNChans
tmpLabel = sprintf('pib%d', p);
header.label{nChans + p} = tmpLabel;
pnsSensorObj = pnsSensors.get(p-1);
header.chantype{nChans + p} = char(pnsSensorObj.getName);
header.chanunit{nChans + p} = char(pnsSensorObj.getUnit);
end
end
header.nChans = header.nChans + summaryInfo.pibNChans;
header.orig = summaryInfo;
|
github
|
lcnhappe/happe-master
|
write_mff_data.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/egi_mff/write_mff_data.m
| 4,329 |
utf_8
|
6446ec1b98cec6e10279f1c1891567ed
|
%% write_mff_data.m
% Matlab File
% author Colin Davey
% date 3/2/2012, 4/15/2014
% Copyright 2012, 2014 EGI. All rights reserved.
%
% Writes channel data (newData) in newData to an MFF file. NewData is a 2-D
% matrix of size Nchans*Nsamples as described at
% http://www.fieldtriptoolbox.org/reference/ft_read_data.
%
% If dstMFFPath is empty, or the same as srcMFFPath, then the data gets
% overwritten, otherwise, the srcMFFPath is copied to dstMFFPath, and the
% data is written to dstMFFPath. In the later case, hdr is ignored.
%
% hdr ? FieldTrip header. You have the option of passing in the header, or
% []. If you pass in the header, it pulls data out of it, rather than
% recomputing them.
%
% This function has the following limitations: It requires a source data
% file (srcMFFPath), in other words, it doesn?t allow you to create
% synthetic data and create a new MFF file. Also, it assumes that the data
% is in the same structure as the srcFile in terms of number of channels,
% number of samples, number of epochs and sizes of epochs. So, it doesn?t
% support processes that change any of those items, for example, channel
% downsampling, or segmentation.
%
% This function doesn't modify the MFF file's history data. To do that,
% call mff_write_history.
%%
function write_mff_data(srcMFFPath, dstMFFPath, newData, hdr)
if isempty(dstMFFPath)
dstMFFPath = srcMFFPath;
end
if strcmp(dstMFFPath, srcMFFPath)
if isempty(hdr)
srcSummaryInfo = mff_getSummaryInfo(dstMFFPath);
else
srcSummaryInfo = hdr.orig;
end
else
if exist(dstMFFPath, 'dir') == 7
fullDS_StorePath = [dstMFFPath filesep '._.DS_Store'];
if exist(fullDS_StorePath, 'file') == 2
delete(fullDS_StorePath);
end
rmdir(dstMFFPath, 's');
end
copyfile(srcMFFPath, dstMFFPath);
srcSummaryInfo = mff_getSummaryInfo(dstMFFPath);
end
if ~strcmp(class(newData), 'single')
newData = single(newData);
end
write_mff_signal(srcSummaryInfo.eegFilename, srcSummaryInfo.javaObjs.blocks, dstMFFPath, newData(1:srcSummaryInfo.nChans,:));
if srcSummaryInfo.pibNChans ~= 0
pibData = newData(srcSummaryInfo.nChans+1:srcSummaryInfo.nChans+srcSummaryInfo.pibNChans,:);
if srcSummaryInfo.pibHasRef
numSamples = size(newData, 2);
pibData = [pibData ; zeros(1, numSamples)];
end
write_mff_signal(srcSummaryInfo.pibFilename, srcSummaryInfo.javaObjs.pibBlocks, dstMFFPath, pibData);
end
function write_mff_signal(signalFilename, blocks, dstMFFPath, newData)
dstSignalFile = [signalFilename 'Tmp'];
dstURI = [dstMFFPath filesep dstSignalFile];
delegate = javaObject('com.egi.services.mff.api.LocalMFFFactoryDelegate');
factory = javaObject('com.egi.services.mff.api.MFFFactory', delegate);
resourceType = javaObject('com.egi.services.mff.api.MFFResourceType', com.egi.services.mff.api.MFFResourceType.kMFF_RT_Signal);
factory.createResourceAtURI(dstURI, resourceType);
dstBinObj = mff_getObject(com.egi.services.mff.api.MFFResourceType.kMFF_RT_Signal, dstSignalFile, dstMFFPath);
for p=0:blocks.size - 1
aBlock = blocks.get(p);
numChannels = aBlock.numberOfSignals;
% number of 4 byte floats is 1/4 the data block size
% That is divided by channel count to get data for each channel:
samplesTimesChannels = aBlock.dataBlockSize/4;
numSamples = samplesTimesChannels / numChannels;
if p == 0
beginSamp = 1;
else
beginSamp = endSamp + 1;
end
endSamp = (beginSamp + numSamples)-1;
% if p > 0
% beginSamp = sum(srcSummaryInfo.epochNumSamps(1:p)) + 1;
% end
% % beginSamp = srcSummaryInfo.epochBeginSamps(p+1)+1;
% endSamp = (beginSamp + srcSummaryInfo.epochNumSamps(p+1))-1;
% fprintf('%d: %d %d %d\n', p, beginSamp, endSamp, size(newData,2));
newDataEpoch = newData(:,beginSamp:endSamp);
newDataEpoch = reshape(newDataEpoch', size(newDataEpoch,1) * size(newDataEpoch,2), 1);
newDataEpoch = typecast(newDataEpoch, 'int8');
aBlock.data = newDataEpoch;
dstBinObj.writeSignalBlock(aBlock);
aBlock.data = [];
java.lang.Runtime.getRuntime.freeMemory;
end
factory.closeResource(dstBinObj);
% delete the EEG file
% rename the written file to the EEG filename
movefile(dstURI, [dstMFFPath filesep signalFilename]);
|
github
|
lcnhappe/happe-master
|
read_mff_data.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/egi_mff/read_mff_data.m
| 8,057 |
utf_8
|
dec75b9fc9150ef62661f59c76e781b1
|
%% read_mff_data.m
% Matlab File
% author Colin Davey
% date 3/2/2012, 4/15/2014
% Copyright 2012, 2014 EGI. All rights reserved.
%
% Takes the path to the data and returns the 2-D matrix of size
% Nchans*Nsamples as described at
% http://www.fieldtriptoolbox.org/reference/ft_read_data.
%
% filePath ? The path to the .mff file.
%
% indType ? Indicates how to interpret the next two parameters. There are
% two possible values:
%
% -- 'epoch', which interprets the following two parameters as epoch
% numbers.
% -- 'sample', which interprets the following two parameters as
% sample numbers.
%
% chanInds ? Indicates which channels to include. If you pass in []
% (MATLAB?s equivalent of NULL), you get all the channels. You can pass in
% lists of channels in MATLAB format, such as [1 2 3] or [1:3], and so on.
%
% hdr ? FieldTrip header. You have the option of passing in the header, or
% []. If you pass in the header, it pulls data out of it, rather than
% recomputing them.
%%
function data = read_mff_data(filePath, indType, beginInd, endInd, chanInds, hdr)
if isempty(hdr)
% try
summaryInfo = mff_getSummaryInfo(filePath);
% catch theException
% throw(theException)
% end
else
summaryInfo = hdr.orig;
end
% If the begin and end are specified in epochs, then need the begin and end
% blocks corresponding to the epochs. Otherwise, it's specified in samples,
% in which case, we also need the begin and end samples.
if strcmp(indType, 'sample')
[beginBlock beginSample] = blockSample2BlockAndSample(beginInd, summaryInfo.blockNumSamps);
[endBlock endSample] = blockSample2BlockAndSample(endInd, summaryInfo.blockNumSamps);
else
beginBlock = summaryInfo.epochFirstBlocks(beginInd);
endBlock = summaryInfo.epochLastBlocks(endInd);
end
dataNumSamples = (summaryInfo.blockBeginSamps(endBlock) - summaryInfo.blockBeginSamps(beginBlock)) + summaryInfo.blockNumSamps(endBlock);
pibNChans = 0;
if ~isempty(summaryInfo.javaObjs.pibBinObj)
pibNChans = summaryInfo.pibNChans;
if summaryInfo.pibHasRef
pibNChans = pibNChans + 1;
end
end
eegNChans = summaryInfo.nChans;
data = zeros(eegNChans + pibNChans, dataNumSamples);
% Get the data from the blocks.
% EEG data...
% Call to function replaced by inline code for speed purposes.
% data(1:eegNChans,:) = read_mff_data_blocks(summaryInfo.binObj, summaryInfo.blocks, beginBlock, endBlock, eegNChans, dataNumSamples, summaryInfo.blockNumSamps);
%%
binObj = summaryInfo.javaObjs.binObj;
blocks = summaryInfo.javaObjs.blocks;
startChan = 1;
endChan = eegNChans;
sampleInd = 1;
for blockInd = beginBlock-1:endBlock-1
% fprintf('blockInd %d\n', blockInd); %!!!
lastSampleInd = sampleInd + summaryInfo.blockNumSamps(blockInd+1) - 1;
data(startChan:endChan,sampleInd:lastSampleInd) = read_mff_data_block(binObj, blocks, blockInd);
sampleInd = lastSampleInd + 1;
end
% PIB data if any...
if ~isempty(summaryInfo.javaObjs.pibBinObj)
% Call to function replaced by inline code for speed purposes.
% data(eegNChans+1:end,:) = read_mff_data_blocks(summaryInfo.pibBinObj, summaryInfo.pibBlocks, beginBlock, endBlock, pibNChans, dataNumSamples, summaryInfo.blockNumSamps);
binObj = summaryInfo.javaObjs.pibBinObj;
blocks = summaryInfo.javaObjs.pibBlocks;
startChan = eegNChans + 1;
endChan = eegNChans + pibNChans;
sampleInd = 1;
for blockInd = beginBlock-1:endBlock-1
% fprintf('blockInd %d\n', blockInd); %!!!
lastSampleInd = sampleInd + summaryInfo.blockNumSamps(blockInd+1) - 1;
data(startChan:endChan,sampleInd:lastSampleInd) = read_mff_data_block(binObj, blocks, blockInd);
sampleInd = lastSampleInd + 1;
end
end
% if channel indeces were provided, downsample to the requested channels
if size(chanInds,1) ~= 0
data = data(chanInds,:);
end
% If begin and end are specified in samples, trim the data down to the
% specified samples.
if strcmp(indType, 'sample')
if (beginSample ~= 1) || (beginSample + (endInd-beginInd) ~= size(data,2))
data = data(:,beginSample:beginSample + (endInd-beginInd));
end
% Otherwise, if the data are segmented, reshape into trials.
elseif strcmp(summaryInfo.epochType, 'seg')
nChans = size(data, 1);
nSamples = summaryInfo.epochNumSamps(1);
nTrials = (endInd - beginInd) + 1;
data = reshape(data,nChans, nSamples, nTrials);
end
%% Gets the data from the blocks.
% Three versions of this routine, from fastest to slowest (newest to
% oldest), preserved for informational purposes. Ultimately not used
% because it's much faster to insert these lines inline in the caller.
% function data = read_mff_data_blocks(binObj, blocks, beginBlock, endBlock, numChans, numSamples, blockNumSamps)
% data = zeros(numChans, numSamples);
% sampleInd = 1;
% for blockInd = beginBlock-1:endBlock-1
% % fprintf('blockInd %d\n', blockInd); %!!!
% lastSampleInd = sampleInd + blockNumSamps(blockInd+1) - 1;
% data(:,sampleInd:lastSampleInd) = read_mff_data_block(binObj, blocks, blockInd);
% sampleInd = lastSampleInd + 1;
% end
% function data = read_mff_data_blocks(binObj, blocks, beginBlock, endBlock, numChans, numSamples, blockNumSamps)
% for blockInd = beginBlock-1:endBlock-1
% % fprintf('blockInd %d\n', blockInd); %!!!
% tmpdata = read_mff_data_block(binObj, blocks, blockInd);
% lastSampleInd = sampleInd + size(tmpdata,2) - 1;
% data(:,sampleInd:lastSampleInd) = tmpdata;
% sampleInd = lastSampleInd + 1;
% end
% function data = read_mff_data_blocks(binObj, blocks, beginBlock, endBlock, numChans, numSamples, blockNumSamps)
% for blockInd = beginBlock-1:endBlock-1
% % fprintf('blockInd %d\n', blockInd);
% tmpdata = read_mff_data_block(binObj, blocks, blockInd);
% if blockInd == beginBlock-1
% data = tmpdata;
% else
% if size(data,1) == size(tmpdata,1)
% data = [data tmpdata];
% else
% % Error: blocks disagree on number of channels. Should never
% % occur, especially given the checking performed by this point.
% % todo?: Add error handling?
% end
% end
% end
%% Gets one block of data.
function data = read_mff_data_block(binObj, blocks, blockInd)
% Load a block
blockObj = blocks.get(blockInd);
blockObj = binObj.loadSignalBlockData(blockObj);
% The data is stored as bytes. Need numbers for reshaping.
numChannels = blockObj.numberOfSignals;
% number of 4 byte floats is 1/4 the data block size
% That is divided by channel count to get data for each channel:
samplesTimesChannels = blockObj.dataBlockSize/4;
numSamples = samplesTimesChannels / numChannels;
% get block, returned as bytes.
data = blockObj.data;
% free up memory in java space.
blockObj.data = [];
java.lang.Runtime.getRuntime.freeMemory;
% convert bytes to equivalent floating point values
data = typecast(data,'single');
% reshape as an epoch.
data = reshape(data, numSamples, numChannels)';
%% Given a sample number within the complete data, return an epoch number,
% and a sample number within that epoch.
% epochNumSamps contains an element for each epoch - the number of samples
% in that epoch.
function [epochNum sample] = epochSample2EpochAndSample(sampleNum, epochNumSamps)
epochNum = 1;
numSamps = epochNumSamps(epochNum);
while sampleNum > numSamps
epochNum = epochNum + 1;
numSamps = numSamps + epochNumSamps(epochNum);
end
numSamps = numSamps - epochNumSamps(epochNum);
sample = sampleNum - numSamps;
%% Given a sample number within the complete data, return a block number,
% and a sample number within that block.
% blockNumSamps contains an element for each block - the number of samples
% in that block.
function [blockNum sample] = blockSample2BlockAndSample(sampleNum, blockNumSamps)
blockNum = 1;
numSamps = blockNumSamps(blockNum);
while sampleNum > numSamps
blockNum = blockNum + 1;
numSamps = numSamps + blockNumSamps(blockNum);
end
numSamps = numSamps - blockNumSamps(blockNum);
sample = sampleNum - numSamps;
|
github
|
lcnhappe/happe-master
|
write_mff_event.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/egi_mff/write_mff_event.m
| 6,173 |
utf_8
|
a2125898d8e7a7d9b5d0b39224e9575b
|
%% write_mff_event.m
% Matlab File
% author Colin Davey
% date 3/2/2012, 4/15/2014
% Copyright 2012, 2014 EGI. All rights reserved.
%
% Writes an events structure (as described at
% http://www.fieldtriptoolbox.org/reference/ft_read_event) to an event-track
% file in an existing MFF file (filePath).
%
% filePath ? The path to the .mff file.
%
% trackName ? the name of the track as it will appear in Net Station.
%
% replace ? a boolean that indicates what the code should do if the track
% already exists. If set to ?true?, the existing track will get
% overwritten. If set to ?false?, the code will end with an error message.
%
% hdr ? FieldTrip header. You have the option of passing in the header, or
% []. If you pass in the header, it pulls data out of it, rather than
% recomputing them.
%
% This function doesn't modify the MFF file's history data. To do that,
% call mff_write_history, described below.
%%
function write_mff_event(filePath, trackName, events, replace, hdr)
if isempty(hdr)
summaryInfo = mff_getSummaryInfo(filePath);
else
summaryInfo = hdr.orig;
end
infoObj = mff_getObject(com.egi.services.mff.api.MFFResourceType.kMFF_RT_Info, 'info.xml', filePath);
beginTimeStr = infoObj.getRecordTime();
MFFUtil = javaObject('com.egi.services.mff.utility.MFFUtil');
dstURI = [filePath filesep 'Events_' pathSafe(trackName) '.xml'];
if ~replace
if exist(dstURI, 'file') == 2
theException = MException('EGI_MFF:EVENTTRACK_EXISTS', 'Specified event track exists. If you want to overwrite, set 4th parameter to true.');
throw(theException);
end
end
hasDurationRemainders = false;
hasSampleRemainders = false;
fields = fieldnames(events(1));
if ~isempty(find(strcmp(fields, 'orig'), 1));
if ~isempty(find(strcmp(fields, 'durationRemainder'), 1));
hasDurationRemainders = true;
end
if ~isempty(find(strcmp(fields, 'sampleRemainder'), 1));
hasSampleRemainders = true;
end
else
end
%%
newEventList = javaObject('java.util.ArrayList');
numEvents = size(events,2);
for p = 1:numEvents
if isempty(events(p).value)
event = javaObject('com.egi.services.mff.api.Event');
type = events(p).type;
typeLen = size(type, 2);
if typeLen > 4
typeOrig = type;
type = type(1:4);
fprintf('*** Event type field ''%s'' is over 4 characters. Truncating to ''%s''. ***\n', typeOrig, type);
elseif typeLen < 4
typeOrig = type;
for q = typeLen+1:4
type = [type '_'];
end
fprintf('*** Event type field ''%s'' is under 4 characters. Padding to ''%s''. ***\n', typeOrig, type);
end
event.setCode(type);
doDurationRemainder = false;
if hasDurationRemainders
if events(p).orig.durationRemainder ~= 0
doDurationRemainder = true;
end
end
duration = events(p).duration;
if doDurationRemainder
duration = samples2Micros(duration - 1, summaryInfo.sampRate) + events(p).orig.durationRemainder;
else
duration = samples2Micros(events(p).duration, summaryInfo.sampRate);
end
event.setDuration(duration);
% get begin time in microsecs
% convert from epoch sample (as if no time went by during breaks)
% to sample of continuous.
epochSample = events(p).sample;
sample = epochSample2Sample(epochSample, summaryInfo.epochBeginSamps, summaryInfo.epochNumSamps);
% Convert from samples to microsecs
microsecs = samples2Micros(sample, summaryInfo.sampRate);
if hasSampleRemainders
microsecs = microsecs + events(p).orig.sampleRemainder;
end
% String timeInStringForm;
% long timeMicrosecondForm;
% long newTime = timeMicrosecondForm + MFFUtil.getTimeInMicroseconds(timeInStringForm);
beginTimeMicrosecs = uint64(MFFUtil.getTimeInMicroseconds(beginTimeStr));
microsecsDate = uint64(microsecs + beginTimeMicrosecs);
% String newTimeInStringForm = MFFUtil.getDateTime(newTime, null);
% Note that the null argument will give you the default time zone. If you want a timezone from the source, then do:
% String newTimeInStringForm = MFFUtil.getDateTime(newTime, MFFUtil.getTimeZone(timeInStringForm));
dateTimeStr = MFFUtil.getDateTime(microsecsDate, MFFUtil.getTimeZone(beginTimeStr));
event.setBeginTime(dateTimeStr);
newEventList.add(event);
end
end
% add events to event object
delegate = javaObject('com.egi.services.mff.api.LocalMFFFactoryDelegate');
factory = javaObject('com.egi.services.mff.api.MFFFactory', delegate);
resourceVal = com.egi.services.mff.api.MFFResourceType.kMFF_RT_EventTrack;
resourceType = javaObject('com.egi.services.mff.api.MFFResourceType', resourceVal);
% fprintf('%s %s\n', char(URI), char(resourceType));
factory.createResourceAtURI(dstURI, resourceType);
newEventTrackObj = factory.openResourceAtURI(dstURI, resourceType);
if ~isempty(newEventTrackObj)
newEventTrackObj.setEvents(newEventList);
newEventTrackObj.setTrackType('EVNT');
newEventTrackObj.setName(trackName);
newEventTrackObj.saveResource();
else
fprintf('Could not create event track.\n');
end
function micros = samples2Micros(samples, sampRate)
sampDuration = 1000000/sampRate;
micros = uint64(samples*sampDuration);
function sampleNum = epochSample2Sample(epochSampleNum, epochBeginSamps, epochNumSamps)
epoch = 1;
while (epochSampleNum > sum(epochNumSamps(1:epoch)))
epoch = epoch + 1;
end
sampleNum = ((epochSampleNum - sum(epochNumSamps(1:epoch-1))) + epochBeginSamps(epoch)) - 1;
% Unsafe Chars: <space>:/\?%*|\"<>
function pathSafeFile = pathSafe(inFile)
unsafeInds = find(...
inFile == ' ' |...
inFile == ':' |...
inFile == '/' |...
inFile == '\' |...
inFile == '?' |...
inFile == '%' |...
inFile == '*' |...
inFile == '|' |...
inFile == '\' |...
inFile == '"' |...
inFile == '<' |...
inFile == '>'...
);
pathSafeFile = inFile;
pathSafeFile(unsafeInds) = '_';
|
github
|
lcnhappe/happe-master
|
write_mff_history.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/egi_mff/write_mff_history.m
| 4,440 |
utf_8
|
c40dcab28c29f1f1502200d38126b463
|
%% write_mff_history.m
% Matlab File
% author Colin Davey
% date 4/15/2014
% Copyright 2014 EGI. All rights reserved.
%
% This function adds an item to the list of history items. It is intended
% to be run after running code that either a) creates a new mff file based
% on an existing one, or b) modifies an existing one. The history item can
% be seen in Net Station through the File Info->History feature.
%
% filePath ? The path to the .mff file.
%
% entryStruct has the following elements:
%
% name - string that corresponds to the name of the tool specification in
% NetStation. For example, if you create a segmentation specification for
% a VTD experiment, and call it "VTD Seg", then the string "VTD Seg" would
% go here.
%
% method - The name of the tool (not the tool specification.) In the above
% example, the string "Segmentation" would go here.
%
% version - The version of the tool, eg "1.0".
%
% beginTime - The time the tool started running. The following matlab
% command creates a time in the proper format:
% sprintf('%d-%02d-%02dT%02d:%02d:%02.5f',clock);
%
% endTime - The time the tool finished running. See beginTime, above, for
% the matlab command that creates a time in the proper format.
%
% sourceFileList - The list of files that were processed by the tool to
% generate the resulting file. For example, a tool that filters a single
% file to create a filtered version of the data would have just one item in
% this list. A tool that creates a grand average by averaging multiple
% single-subject files would have multiple items in this list.
%
% settingList - A cell array of zero or more strings that express the
% settings/parameters for the tool. These are optional, and are intended to
% be read by humans, not machines.
%
% resultList - A cell array of zero or more strings that express the
% results of the tool. These are optional, and are intended to be read by
% humans, not machines.
%%
function write_mff_history(filePath, entryStruct)
try
mff_valid(filePath);
catch theException
throw(theException);
end
%% 1) Read in history resource.
histObj = mff_getObject(com.egi.services.mff.api.MFFResourceType.kMFF_RT_History, 'history.xml', filePath);
%% 2) Get the list of current entires (it might be null, in which case
% create a new one and set it).
if isempty(histObj)
delegate = javaObject('com.egi.services.mff.api.LocalMFFFactoryDelegate');
factory = javaObject('com.egi.services.mff.api.MFFFactory', delegate);
resourceVal = com.egi.services.mff.api.MFFResourceType.kMFF_RT_History;
resourceType = javaObject('com.egi.services.mff.api.MFFResourceType', resourceVal);
factory.createResourceAtURI([filePath filesep 'history.xml'], resourceType);
histObj = factory.openResourceAtURI([filePath filesep 'history.xml'], resourceType);
entryList = javaObject('java.util.ArrayList');
histObj.setEntries(entryList);
else
entryList = histObj.getEntries;
if isempty(entryList) % Is this feasible? ie history exists, but entryList is empty?
entryList = javaObject('java.util.ArrayList');
histObj.setEntries(entryList);
end
end
%% 3) Add an Entry object to the list.
entry = javaObject('com.egi.services.mff.api.Entry');
tool = javaObject('com.egi.services.mff.api.Tool');
tool.setName(entryStruct.name);
tool.setKind('Transformation');
tool.setMethod(entryStruct.method);
tool.setVersion(entryStruct.version);
tool.setBeginTime(entryStruct.beginTime);
tool.setEndTime(entryStruct.endTime);
sourceFileList = javaObject('java.util.ArrayList');
for p=1:size(entryStruct.sourceFileList,2)
filePathObj = javaObject('com.egi.services.mff.api.FilePath');
filePathObj.setFilePath(entryStruct.sourceFileList{p});
sourceFileList.add(filePathObj);
filePathObj = [];
end
java.lang.Runtime.getRuntime.freeMemory;
tool.setSourceFiles(sourceFileList);
settingList = javaObject('java.util.ArrayList');
for p=1:size(entryStruct.settingList,2)
settingList.add(entryStruct.settingList{p});
end
tool.setSettings(settingList);
resultList = javaObject('java.util.ArrayList');
for p=1:size(entryStruct.resultList,2)
resultList.add(entryStruct.resultList{p});
end
tool.setResults(resultList);
entry.setEntry(tool);
entry.setType('tool');
entryList.add(entry);
%% 4) Save the history resource in the standard way all resources are saved.
histObj.setEntries(entryList);
histObj.saveResource;
|
github
|
lcnhappe/happe-master
|
read_mff_event.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/egi_mff/read_mff_event.m
| 8,001 |
utf_8
|
8f54b92417702a6bde1b09e9ea67c6a0
|
%% read_mff_event.m
% Matlab File
% author Colin Davey
% date 3/2/2012, 4/15/2014
% Copyright 2012, 2014 EGI. All rights reserved.
%
% Takes the path to the data and returns the events in the structure
% described at http://www.fieldtriptoolbox.org/reference/ft_read_event.
%
% filePath ? The path to the .mff file.
%
% hdr ? FieldTrip header. You have the option of passing in the header, or
% []. If you pass in the header, it pulls data out of it, rather than
% recomputing them.
%%
function events = read_mff_event(filePath, hdr)
if isempty(hdr)
summaryInfo = mff_getSummaryInfo(filePath);
else
summaryInfo = hdr.orig;
end
% Pull the information about the epochs out of the summary info
epochBeginSamps = summaryInfo.epochBeginSamps;
epochNumSamps = summaryInfo.epochNumSamps;
epochFirstBlocks = summaryInfo.epochFirstBlocks;
epochLastBlocks = summaryInfo.epochLastBlocks;
% Get the start time of the recording
infoObj = mff_getObject(com.egi.services.mff.api.MFFResourceType.kMFF_RT_Info, 'info.xml', filePath);
beginTime = infoObj.getRecordTime();
events = [];
eventInd = 0;
% Create the meta data events, ie epoch breaks and time 0 events.
for p = 1:size(summaryInfo.epochBeginSamps,2)
eventInd = eventInd + 1;
events(eventInd).type = ['break ' summaryInfo.epochType];
events(eventInd).sample = samples2EpochSample(summaryInfo.epochBeginSamps(p), epochBeginSamps, epochNumSamps);
events(eventInd).value = summaryInfo.epochLabels{p};
events(eventInd).offset = [];
events(eventInd).duration = summaryInfo.epochNumSamps(p);
events(eventInd).timestamp = [];
events(eventInd).orig.sampleRemainder = 0;
events(eventInd).orig.durationRemainder = 0;
events(eventInd).orig.trackname = 'metadata';
events(eventInd).orig.keys = {};
eventInds(eventInd,1) = events(eventInd).sample;
eventInds(eventInd,2) = eventInd;
if strcmp(summaryInfo.epochType, 'var')
eventInd = eventInd + 1;
events(eventInd).type = 't0';
events(eventInd).sample = samples2EpochSample((summaryInfo.epochTime0(p) + summaryInfo.epochBeginSamps(p)) - 1, epochBeginSamps, epochNumSamps);
events(eventInd).value = 't0';
events(eventInd).offset = [];
events(eventInd).duration = 1;
events(eventInd).timestamp = []; % or calculate string
events(eventInd).orig.sampleRemainder = 0;
events(eventInd).orig.durationRemainder = 0;
events(eventInd).orig.trackname = 'metadata';
events(eventInd).orig.keys = {};
eventInds(eventInd,1) = events(eventInd).sample;
eventInds(eventInd,2) = eventInd;
end
end
% Go through all the event tracks, if any...
eventtracknamelist = summaryInfo.javaObjs.mfffileObj.getEventTrackList(false);
eventtrackcount = eventtracknamelist.size();
if eventtrackcount > 0
% MFFUtil is used to for operations on string-based timestamp
MFFUtil = javaObject('com.egi.services.mff.utility.MFFUtil');
for tracknum = 0:eventtrackcount-1
trackname = eventtracknamelist.get(tracknum);
tracknameL = lower(trackname);
if strcmp(tracknameL(end-3:end), '.xml')
trackname = trackname(1:end-4);
eventTrackObj = mff_getObject(com.egi.services.mff.api.MFFResourceType.kMFF_RT_EventTrack, tracknameL, filePath);
eventList = eventTrackObj.getEvents;
numEvents = eventList.size;
for p = 0:numEvents-1
% Java arrays are 0 based
theEvent = eventList.get(p);
eventTime = theEvent.getBeginTime;
%Need to convert to samples (get sampling rate up above)
eventTimeInMicros = uint64(MFFUtil.getTimeDifferenceInMicroseconds(eventTime , beginTime));
[eventTimeInSamples, sampleRemainder] = mff_micros2Sample(eventTimeInMicros, summaryInfo.sampRate);
eventTimeInEpochSamples = samples2EpochSample(eventTimeInSamples, epochBeginSamps, epochNumSamps);
if eventTimeInEpochSamples < 1
% Error: invalid sample number
else
eventInd = eventInd + 1;
% fprintf('%d %d %d\n', eventTimeInSamples, eventTimeInEpochSamples, eventTimeInSamples-eventTimeInEpochSamples);
% Matlab arrays are 1 based
events(eventInd).type = char(theEvent.getCode);
events(eventInd).sample = eventTimeInEpochSamples;
events(eventInd).orig.sampleRemainder = sampleRemainder;
events(eventInd).value = [];
events(eventInd).offset = [];
[events(eventInd).duration, events(eventInd).orig.durationRemainder] = mff_micros2Sample(theEvent.getDuration, summaryInfo.sampRate);
if events(eventInd).orig.durationRemainder > 0
events(eventInd).duration = events(eventInd).duration + 1;
end
events(eventInd).timestamp = []; %eventTime;
events(eventInd).orig.trackname = trackname;
% New code for keys. Java arrays are 0 based.
keylist = theEvent.getKeys;
eventkeycount = keylist.size;
% events(eventInd).keys = cell(eventkeycount, 4);
% Create an empty keylist in case there are no keys,
% e.g. DINs.
events(eventInd).orig.keys = {};
for q = 0:eventkeycount-1
theKey = keylist.get(q);
theKeyCode = char(theKey.getCode);
theKeyData = char(theKey.getData);
theKeyDataType = char(theKey.getDataType);
theKeyDescription = char(theKey.getDescription);
events(eventInd).orig.keys{q+1}.code = theKeyCode;
events(eventInd).orig.keys{q+1}.data = theKeyData;
events(eventInd).orig.keys{q+1}.datatype = theKeyDataType;
events(eventInd).orig.keys{q+1}.description = theKeyDescription;
% events(eventInd).keys(q+1).code = theKeyCode;
% events(eventInd).keys(q+1).data = theKeyData;
% events(eventInd).keys(q+1).datatype = theKeyDataType;
% events(eventInd).keys(q+1).description = theKeyDescription;
% events(eventInd).keys{q+1, 1} = theKeyCode;
% events(eventInd).keys{q+1, 2} = theKeyData;
% events(eventInd).keys{q+1, 3} = theKeyDataType;
% events(eventInd).keys{q+1, 4} = theKeyDescription;
end
eventInds(eventInd,1) = events(eventInd).sample;
eventInds(eventInd,2) = eventInd;
end
end
end
end
% Sort events, which includes metadata events and events that have come
% from different tracks, by time.
eventInds = sortrows(eventInds);
for p = 1:eventInd
nextEventInd = eventInds(p,2);
sortedEvents(p) = events(nextEventInd);
end
events = sortedEvents;
end
% Converts from samples since start of recording (as if there were no
% breaks) to samples in file.
function epochSampleNum = samples2EpochSample(sampleNum, epochBeginSamps, epochNumSamps)
numEpochs = size(epochBeginSamps,2);
p = 1;
epochSampleNum = 0;
while (sampleNum > (epochBeginSamps(p) + epochNumSamps(p) - 1)) && (p < numEpochs)
epochSampleNum = epochSampleNum + epochNumSamps(p);
p = p+1;
end
if p <= numEpochs
if sampleNum >= epochBeginSamps(p)
epochSampleNum = epochSampleNum + ((sampleNum - epochBeginSamps(p))+1);
else
epochSampleNum = -1;
% Error: sample falls between epochs
end
else
epochSampleNum = -2;
% Error: sample is after last epoch
end
|
github
|
lcnhappe/happe-master
|
efficiency_bin.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/bct/efficiency_bin.m
| 2,700 |
utf_8
|
276bfa775a0cb36ac38e13fcb06ff32a
|
function E=efficiency_bin(A,local)
%EFFICIENCY_BIN Global efficiency, local efficiency.
%
% Eglob = efficiency_bin(A);
% Eloc = efficiency_bin(A,1);
%
% The global efficiency is the average of inverse shortest path length,
% and is inversely related to the characteristic path length.
%
% The local efficiency is the global efficiency computed on the
% neighborhood of the node, and is related to the clustering coefficient.
%
% Inputs: A, binary undirected or directed connection matrix
% local, optional argument
% local=0 computes global efficiency (default)
% local=1 computes local efficiency
%
% Output: Eglob, global efficiency (scalar)
% Eloc, local efficiency (vector)
%
%
% Algorithm: algebraic path count
%
% Reference: Latora and Marchiori (2001) Phys Rev Lett 87:198701.
% Fagiolo (2007) Phys Rev E 76:026107.
% Rubinov M, Sporns O (2010) NeuroImage 52:1059-69
%
%
% Mika Rubinov, U Cambridge
% Jonathan Clayden, UCL
% 2008-2013
% Modification history:
% 2008: Original (MR)
% 2013: Bug fix, enforce zero distance for self-connections (JC)
% 2013: Local efficiency generalized to directed networks
n=length(A); %number of nodes
A(1:n+1:end)=0; %clear diagonal
A=double(A~=0); %enforce double precision
if exist('local','var') && local %local efficiency
E=zeros(n,1);
for u=1:n
V=find(A(u,:)|A(:,u).'); %neighbors
sa=A(u,V)+A(V,u).'; %symmetrized adjacency vector
e=distance_inv(A(V,V)); %inverse distance matrix
se=e+e.'; %symmetrized inverse distance matrix
numer=sum(sum((sa.'*sa).*se))/2; %numerator
if numer~=0
denom=sum(sa).^2 - sum(sa.^2); %denominator
E(u)=numer/denom; %local efficiency
end
end
else %global efficiency
e=distance_inv(A);
E=sum(e(:))./(n^2-n);
end
function D=distance_inv(A_)
l=1; %path length
Lpath=A_; %matrix of paths l
D=A_; %distance matrix
n_=length(A_);
Idx=true;
while any(Idx(:))
l=l+1;
Lpath=Lpath*A_;
Idx=(Lpath~=0)&(D==0);
D(Idx)=l;
end
D(~D | eye(n_))=inf; %assign inf to disconnected nodes and to diagonal
D=1./D; %invert distance
|
github
|
lcnhappe/happe-master
|
reachdist.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/bct/reachdist.m
| 1,995 |
utf_8
|
fe609993c33b1602c328e2a662f2f8a5
|
function [R,D] = reachdist(CIJ)
%REACHDIST Reachability and distance matrices
%
% [R,D] = reachdist(CIJ);
%
% The binary reachability matrix describes reachability between all pairs
% of nodes. An entry (u,v)=1 means that there exists a path from node u
% to node v; alternatively (u,v)=0.
%
% The distance matrix contains lengths of shortest paths between all
% pairs of nodes. An entry (u,v) represents the length of shortest path
% from node u to node v. The average shortest path length is the
% characteristic path length of the network.
%
% Input: CIJ, binary (directed/undirected) connection matrix
%
% Outputs: R, reachability matrix
% D, distance matrix
%
% Note: faster but more memory intensive than "breadthdist.m".
%
% Algorithm: algebraic path count.
%
%
% Olaf Sporns, Indiana University, 2002/2007/2008
% initialize
R = CIJ;
D = CIJ;
powr = 2;
N = size(CIJ,1);
CIJpwr = CIJ;
% Check for vertices that have no incoming or outgoing connections.
% These are "ignored" by 'reachdist'.
id = sum(CIJ,1); % indegree = column sum of CIJ
od = sum(CIJ,2)'; % outdegree = row sum of CIJ
id_0 = find(id==0); % nothing goes in, so column(R) will be 0
od_0 = find(od==0); % nothing comes out, so row(R) will be 0
% Use these columns and rows to check for reachability:
col = setxor(1:N,id_0);
row = setxor(1:N,od_0);
[R,D,powr] = reachdist2(CIJ,CIJpwr,R,D,N,powr,col,row);
% "invert" CIJdist to get distances
D = powr - D+1;
% Put 'Inf' if no path found
D(D==(N+2)) = Inf;
D(:,id_0) = Inf;
D(od_0,:) = Inf;
%----------------------------------------------------------------------------
function [R,D,powr] = reachdist2(CIJ,CIJpwr,R,D,N,powr,col,row)
% Olaf Sporns, Indiana University, 2002/2008
CIJpwr = CIJpwr*CIJ;
R = double(R | ((CIJpwr)~=0));
D = D+R;
if ((powr<=N)&&(~isempty(nonzeros(R(row,col)==0))))
powr = powr+1;
[R,D,powr] = reachdist2(CIJ,CIJpwr,R,D,N,powr,col,row);
end;
|
github
|
lcnhappe/happe-master
|
consensus_und.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/bct/consensus_und.m
| 3,133 |
utf_8
|
2399e05c584d7327bb19ba25e2c89812
|
function ciu = consensus_und(d,tau,reps)
%CONSENSUS consensus clustering
%
% CIU = CONSENSUS(D,TAU,REPS) seeks a consensus partition of the
% agreement matrix D. The algorithm used here is almost identical to the
% one introduced in Lancichinetti & Fortunato (2012): The agreement
% matrix D is thresholded at a level TAU to remove an weak elements. The
% resulting matrix is then partitions REPS number of times using the
% Louvain algorithm (in principle, any clustering algorithm that can
% handle weighted matrixes is a suitable alternative to the Louvain
% algorithm and can be substituted in its place). This clustering
% produces a set of partitions from which a new agreement is built. If
% the partitions have not converged to a single representative partition,
% the above process repeats itself, starting with the newly built
% agreement matrix.
%
% NOTE: In this implementation, the elements of the agreement matrix must
% be converted into probabilities.
%
% NOTE: This implementation is slightly different from the original
% algorithm proposed by Lanchichinetti & Fortunato. In its original
% version, if the thresholding produces singleton communities, those
% nodes are reconnected to the network. Here, we leave any singleton
% communities disconnected.
%
% Inputs: D, agreement matrix with entries between 0 and 1
% denoting the probability of finding node i in the
% same cluster as node j
% TAU, threshold which controls the resolution of the
% reclustering
% REPS, number of times that the clustering algorithm is
% reapplied
%
% Outputs: CIU, consensus partition
%
% References: Lancichinetti & Fortunato (2012). Consensus clustering in
% complex networks. Scientific Reports 2, Article number: 336.
%
% Richard Betzel, Indiana University, 2012
%
% modified on 3/2014 to include "unique_partitions"
n = length(d); flg = 1;
while flg == 1
flg = 0;
dt = d.*(d >= tau).*~eye(n);
if nnz(dt) == 0
ciu = (1:n)';
else
ci = zeros(n,reps);
for iter = 1:reps
ci(:,iter) = community_louvain(dt);
end
ci = relabel_partitions(ci);
ciu = unique_partitions(ci);
nu = size(ciu,2);
if nu > 1
flg = 1;
d = agreement(ci)./reps;
end
end
end
function cinew = relabel_partitions(ci)
[n,m] = size(ci);
cinew = zeros(n,m);
for i = 1:m
c = ci(:,i);
d = zeros(size(c));
count = 0;
while sum(d ~= 0) < n
count = count + 1;
ind = find(c,1,'first');
tgt = c(ind);
rep = c == tgt;
d(rep) = count;
c(rep) = 0;
end
cinew(:,i) = d;
end
function ciu = unique_partitions(ci)
ci = relabel_partitions(ci);
ciu = [];
count = 0;
c = 1:size(ci,2);
while ~isempty(ci)
count = count + 1;
tgt = ci(:,1);
ciu = [ciu,tgt]; %#ok<AGROW>
dff = sum(abs(bsxfun(@minus,ci,tgt))) == 0;
ci(:,dff) = [];
c(dff) = [];
end
|
github
|
lcnhappe/happe-master
|
efficiency_wei.m
|
.m
|
happe-master/Packages/eeglab14_0_0b/plugins/fieldtrip-20160917/external/bct/efficiency_wei.m
| 4,166 |
utf_8
|
d7b86059eb2ec0a923ab289c876fd9b0
|
function E=efficiency_wei(W,local)
%EFFICIENCY_WEI Global efficiency, local efficiency.
%
% Eglob = efficiency_wei(W);
% Eloc = efficiency_wei(W,1);
%
% The global efficiency is the average of inverse shortest path length,
% and is inversely related to the characteristic path length.
%
% The local efficiency is the global efficiency computed on the
% neighborhood of the node, and is related to the clustering coefficient.
%
% Inputs: W, weighted undirected or directed connection matrix
% (all weights in W must be between 0 and 1)
% local, optional argument
% local=0 computes global efficiency (default)
% local=1 computes local efficiency
%
% Output: Eglob, global efficiency (scalar)
% Eloc, local efficiency (vector)
%
% Notes:
% The efficiency is computed using an auxiliary connection-length
% matrix L, defined as L_ij = 1/W_ij for all nonzero L_ij; This has an
% intuitive interpretation, as higher connection weights intuitively
% correspond to shorter lengths.
% The weighted local efficiency broadly parallels the weighted
% clustering coefficient of Onnela et al. (2005) and distinguishes the
% influence of different paths based on connection weights of the
% corresponding neighbors to the node in question. In other words, a path
% between two neighbors with strong connections to the node in question
% contributes more to the local efficiency than a path between two weakly
% connected neighbors. Note that this weighted variant of the local
% efficiency is hence not a strict generalization of the binary variant.
%
% Algorithm: Dijkstra's algorithm
%
% References: Latora and Marchiori (2001) Phys Rev Lett 87:198701.
% Onnela et al. (2005) Phys Rev E 71:065103
% Fagiolo (2007) Phys Rev E 76:026107.
% Rubinov M, Sporns O (2010) NeuroImage 52:1059-69
%
%
% Mika Rubinov, U Cambridge, 2011-2012
%Modification history
% 2011: Original (based on efficiency.m and distance_wei.m)
% 2013: Local efficiency generalized to directed networks
n=length(W); %number of nodes
L = W;
A = W~=0;
ind = L~=0;
L(ind) = 1./L(ind); %connection-length matrix
if exist('local','var') && local %local efficiency
E=zeros(n,1);
for u=1:n
V=find(A(u,:)|A(:,u).'); %neighbors
sw=W(u,V).^(1/3)+W(V,u).^(1/3).'; %symmetrized weights vector
e=distance_inv_wei(L(V,V)); %inverse distance matrix
se=e.^(1/3)+e.'.^(1/3); %symmetrized inverse distance matrix
numer=(sum(sum((sw.'*sw).*se)))/2; %numerator
if numer~=0
sa=A(u,V)+A(V,u).'; %symmetrized adjacency vector
denom=sum(sa).^2 - sum(sa.^2); %denominator
E(u)=numer/denom; %local efficiency
end
end
else
e=distance_inv_wei(L);
E=sum(e(:))./(n^2-n); %global efficiency
end
function D=distance_inv_wei(W_)
n_=length(W_);
D=inf(n_); %distance matrix
D(1:n_+1:end)=0;
for u=1:n_
S=true(1,n_); %distance permanence (true is temporary)
W1_=W_;
V=u;
while 1
S(V)=0; %distance u->V is now permanent
W1_(:,V)=0; %no in-edges as already shortest
for v=V
T=find(W1_(v,:)); %neighbours of shortest nodes
D(u,T)=min([D(u,T);D(u,v)+W1_(v,T)]);%smallest of old/new path lengths
end
minD=min(D(u,S));
if isempty(minD)||isinf(minD), %isempty: all nodes reached;
break, %isinf: some nodes cannot be reached
end;
V=find(D(u,:)==minD);
end
end
D=1./D; %invert distance
D(1:n_+1:end)=0;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.