plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
philippboehmsturm/antx-master
ft_datatype_raw.m
.m
antx-master/xspm8/external/fieldtrip/utilities/ft_datatype_raw.m
10,365
utf_8
4db6184c0320dfb990e48ca6db1e95a2
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 % % 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.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_datatype_raw.m 7216 2012-12-17 19:45:33Z roboos $ % 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 if isequal(hassampleinfo, 'ifmakessense') hassampleinfo = 'yes'; 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') 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'; break; end end end if strcmp(hassampleinfo, 'no') % the actual removal will be done further down warning('removing inconsistent sampleinfo'); end end if isequal(hastrialinfo, 'ifmakessense') hastrialinfo = 'yes'; if isfield(data, 'trialinfo') && size(data.trialinfo,1)~=numel(data.trial) % it does not make sense, so don't keep it hastrialinfo = 'no'; end if strcmp(hastrialinfo, 'no') % the actual removal will be done further down warning('removing inconsistent sampleinfo'); 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 balancing is specified if ~isfield(data.grad, 'balance') || ~isfield(data.grad.balance, 'current') data.grad.balance.current = 'none'; end % ensure the new style sensor description data.grad = ft_datatype_sens(data.grad); end if isfield(data, 'elec') data.elec = ft_datatype_sens(data.elec); end 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 '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 warning_once('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
philippboehmsturm/antx-master
ft_version.m
.m
antx-master/xspm8/external/fieldtrip/utilities/ft_version.m
20,525
utf_8
9447155468f1f54b38bd39fd011d3d94
function [v,ftpath] = ft_version(cmd) % FT_VERSION provides functionality for displaying version information on % the current version of FieldTrip being used, as well us for updating the % FieldTrip installation. % % To understand the different options this function provides, a little bit % of background knowledge is needed about how FieldTrip deals with % versions. FieldTrip does not use a fixed release system, but instead % the 'release' version available from the FTP server is updated daily, % through an automatic script. This release version is based on the % development version used internally by the developers, which is updated % more frequently. Development updates are tracked using Subversion (SVN), % a system that assigns a revision number to each change to the code. The % release version of FieldTrip contains a signature file (signature.md5), % that contains, for each file in the release, the latest revision number % for that file, along with an MD5 hash of the file's contents. A similar % signature file is located on the FieldTrip webserver, which is updated % whenever a developer makes a change to the codebase. % % This function uses both the local signature file (dating from whenever % you downloaded FieldTrip) and the remote signature file (reflecting the % latest version available--this updates more frequently than the daily FTP % release) to determine (1) the version of FieldTrip you are using, (2) % whether you have made local changes to your FieldTrip installation (by % comparing the actual MD5 hashes of files to the ones stored in your local % signature file), (3) whether there are new updates available (by % comparing the local and remote signature files). % % Usage: % ft_version info - display the latest revision number % present in your installation % ft_version full - display full revision information about % your installation; this includes checking % for local and/or remote changes % ft_version update - also displays full revision information; % additionally provides the option of % downloading new or updated files from the % code repository % [v,ftpath] = ft_version - also get information about the root of % your FieldTrip installation % 'Hidden' options: % ft_version signature - generate a new signature file, without % revision information about the files % ft_version fullsignature - generate a new signature file, including % revision information; this can only be % used when you are using an SVN % installation of FieldTrip % Copyright (C) 2012, Eelke Spaak % % This file is part of FieldTrip, see http://www.ru.nl/donders/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_version.m 7383 2013-01-23 13:19:28Z eelspa $ if nargin<1 cmd = 'info'; end [ftpath, ~] = fileparts(mfilename('fullpath')); ftpath = ftpath(1:end-10); % strip away '/utilities' signaturefile = fullfile(ftpath, 'signature.md5'); remotesignature = 'http://fieldtrip.fcdonders.nl/signature.md5'; repository = 'http://fieldtrip.googlecode.com/svn/trunk/'; % are we dealing with an SVN working copy of fieldtrip? issvn = isdir(fullfile(ftpath, '.svn')); switch cmd %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'info' % show the latest revision present in this copy of fieldtrip if issvn % use svn system call to determine latest revision olddir = pwd(); cd(ftpath); [status,output] = system('svn info'); cd(olddir); if status > 0 error('you seem to have an SVN working copy of FieldTrip, yet ''svn info'' does not work as expected'); end rev = regexp(output, 'Revision: (.*)', 'tokens', 'dotexceptnewline'); rev = rev{1}{1}; else % determine latest revision from the signature file fp = fopen(signaturefile, 'r'); line = fgetl(fp); % just get first line, file should be ordered newest-first fclose(fp); rev = regexp(line, '[^\t]*\t([^\t])*\t.*', 'tokens'); rev = rev{1}{1}; end if nargout > 0 v = rev; elseif issvn fprintf('\nThis is FieldTrip, version r%s (svn).\n\n', rev); else fprintf('\nThis is FieldTrip, version r%s.\n\n', rev); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'full' % show the latest revision present in this version of FieldTrip % and also check for possible remote and local changes if issvn % use svn status olddir = pwd(); cd(ftpath); [status,output] = system('svn status'); cd(olddir); if status > 0 error('you seem to have an SVN working copy of FieldTrip, yet ''svn status'' does not work as expected'); end if numel(output) > 1 modFlag = 'M'; else modFlag = 'U'; end fprintf('\nThis is FieldTrip, version r%s%s (svn).\n\n', ft_version(), modFlag); % simply print the output of the svn status command if numel(output) > 1 fprintf('This is the SVN status of your working copy:\n'); fprintf(output); fprintf('\n'); end else % fetch remote hash table str = urlread(remotesignature); [remHashes, remFiles, remRevs] = parseHashTable(str); % fetch local hash table str = fileread(signaturefile); [locHashes, locFiles, locRevs] = parseHashTable(str); % determine changes [remoteDeleted, remoteNew, remoteChanges,... localDeleted, localChanges] = findChanges(locHashes, locFiles,... remHashes, remFiles, ftpath); % print detailed version information if any(localChanges) modFlag = 'M'; % M for modified else modFlag = 'U'; % U for unmodified end fprintf('This is FieldTrip, version r%s%s.\n', ft_version(), modFlag); if any(localChanges) fprintf('\nthe following files have been locally modified:\n'); inds = find(localChanges); for k = 1:numel(inds) fprintf(' r%sm %s\n', locRevs{inds(k)}, locFiles{inds(k)}); end end if any(localDeleted) fprintf('\nthe following files have been locally deleted:\n'); inds = find(localDeleted); for k = 1:numel(inds) fprintf(' r%sd %s\n', locRevs{inds(k)}, locFiles{inds(k)}); end end if any(remoteChanges) fprintf('\na new version is available for the following files:\n'); inds = find(remoteChanges); for k = 1:numel(inds) locInd = strcmp(locFiles, remFiles{inds(k)}); fprintf(' r%s-->r%s %s\n',... locRevs{locInd}, remRevs{inds(k)}, remFiles{inds(k)}); end end if any(remoteDeleted) fprintf('\nthe following files are no longer part of FieldTrip:\n'); files = locFiles(remoteDeleted); for k = 1:numel(files) fprintf(' %s\n', files{k}); end end if any(remoteNew) fprintf('\nthe following new files are available:\n'); files = remFiles(remoteNew); revs = remRevs(remoteNew); for k = 1:numel(files) fprintf(' r%sa %s\n', revs{k}, files{k}); end end fprintf('\n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'update' % get the remote changes, check that there are no conflicting local % changes and update the files if issvn fprintf('\nThis is an SVN working copy of FieldTrip, invoking ''svn update''...\n'); olddir = pwd(); cd(ftpath); system('svn update'); cd(olddir); fprintf('\n'); else % fetch remote hash table str = urlread(remotesignature); [remHashes, remFiles, remRevs] = parseHashTable(str); % fetch local hash table str = fileread(signaturefile); [locHashes, locFiles, locRevs] = parseHashTable(str); % determine changes [remoteDeleted, remoteNew, remoteChanges,... localDeleted, localChanges] = findChanges(locHashes, locFiles,... remHashes, remFiles, ftpath); % index all possible deletions and additions locFilesDelete = []; remFilesDownload = []; olddir = pwd(); cd(ftpath); % keep track of whether local additions will possibly be overwritten overwriteFlag = 0; % first display information on what would be changed if any(remoteNew) fprintf('\nthe following new files will be added:\n'); inds = find(remoteNew); for k = 1:numel(inds) if exist(remFiles{inds(k)}, 'file') msg = '!'; overwriteFlag = 1; else msg = ' '; end % give this change a number and remember it remFilesDownload(end+1) = inds(k); locFilesDelete(end+1) = nan; fprintf('%s %3d. r%s %s\n', msg, numel(locFilesDelete), remRevs{inds(k)}, remFiles{inds(k)}); end end if any(remoteDeleted) fprintf('\nthe following files will be deleted:\n'); inds = find(remoteDeleted); for k = 1:numel(inds) if localChanges(inds(k)) msg = '!'; overwriteFlag = 1; else msg = ' '; end % give this change a number and remember it remFilesDownload(end+1) = nan; locFilesDelete(end+1) = inds(k); fprintf('%s %3d. %s\n', msg, numel(locFilesDelete), locFiles{inds(k)}); end end if any(remoteChanges) fprintf('\nthe following files will be updated:\n'); inds = find(remoteChanges); for k = 1:numel(inds) locInd = strcmp(locFiles, remFiles{inds(k)}); if localChanges(locInd) msg = '!'; overwriteFlag = 1; else msg = ' '; end % give this change a number and remember it remFilesDownload(end+1) = inds(k); locFilesDelete(end+1) = nan; fprintf('%s %3d. r%s-->r%s %s\n',... msg, numel(locFilesDelete), locRevs{locInd},... remRevs{inds(k)}, remFiles{inds(k)}); end end assert(numel(remFilesDownload) == numel(locFilesDelete)); if overwriteFlag fprintf(['\n!!NOTE: if you choose to include changes marked with a leading !,\n'... ' they will overwrite local changes or additions!\n']); end % prompt the user which changes should be incorporated while (true) % use while (true) as poor man's do{}while() changesToInclude = input(['\nwhich changes do you want to include?\n'... '([vector] for specific changes, ''all'', or [] for none)\n? '],'s'); % check integrity of entered data if strcmp(changesToInclude, 'all') changesToInclude = 1:numel(remFilesDownload); else [changesToInclude,status] = str2num(changesToInclude); end if status && isnumeric(changesToInclude) && all(changesToInclude > 0)... && (all(changesToInclude <= numel(remFilesDownload)) || ... changesToInclude == Inf) changesToInclude = unique(changesToInclude); break; end end % include only those changes requested in the actual update locFilesDelete = locFilesDelete(changesToInclude); locFilesDelete(isnan(locFilesDelete)) = []; remFilesDownload = remFilesDownload(changesToInclude); remFilesDownload(isnan(remFilesDownload)) = []; % delete all local files that should be deleted for k = 1:numel(locFilesDelete) ind = locFilesDelete(k); fprintf('deleting file %s...\n', locFiles{ind}); delete(locFiles{ind}); % also remove entry from the hash table cell arrays locFiles(ind) = []; locHashes(ind) = []; locRevs(ind) = []; end % add new files and/or update changed files for k = 1:numel(remFilesDownload) ind = remFilesDownload(k); fprintf('downloading file %s...\n', remFiles{ind}); newFile = urlread([repository remFiles{ind}]); fp = fopen(remFiles{ind}, 'w'); fwrite(fp, newFile); fclose(fp); % update local hash table locInd = strcmp(locFiles, remFiles{ind}); if any(locInd) % file was already present, update hash locHashes{locInd} = remHashes{ind}; locRevs{locInd} = remRevs{ind}; else % new file, add hash locFiles{end} = remFiles{ind}; locHashes{end} = remHashes{ind}; locRevs{end} = remRevs{ind}; end end cd(olddir); if ~isempty(changesToInclude) % output new hash table fp = fopen(signaturefile,'w'); outputHashTable(fp, locHashes, locFiles, locRevs); fclose(fp); fprintf('update finished.\n'); else fprintf('nothing updated.\n'); end ft_version(); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'signature' if exist(signaturefile, 'file') error(sprintf([signaturefile ' already exists.\nIf you are sure you want to re-create '... 'the signature file, you will have to manually delete it.\nNote that this means '... 'that local edits cannot be tracked anymore, and might be overwritten without notice!'])); end fprintf('\nwriting signature file to signature-local.md5 (this might take a few minutes)...'); hashFile = fopen(signaturefile, 'w'); hashAll(hashFile, ftpath, ftpath); fclose(hashFile); fprintf('done.\n\n'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'fullsignature' if exist(signaturefile, 'file') error(sprintf([signaturefile ' already exists.\nIf you are sure you want to re-create '... 'the signature file, you will have to manually delete it.\nNote that this means '... 'that local edits cannot be tracked anymore, and might be overwritten without notice!'])); end if ~issvn error('you can only generate a full signature with revision info if you are using an SVN working copy of FieldTrip'); end fprintf('\nwriting signature file to signature-local.md5 (this might take a few minutes)...'); hashFile = fopen(fullfile(ftpath, 'signature-local.md5'), 'w'); hashAll(hashFile, ftpath, ftpath, 1); fclose(hashFile); fprintf('done.\n\n'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % locHashes and locFiles represent the hashes and filenames of entries in % the local hash table, respectively. remHashes and remFiles represent the % hashes and filenames of entries in the remote hash table, respectively. % ftpath is the FT root path. Returned are logical index vectors into the % remFiles cell array (for remoteChanges and remoteNew) or into the % locFiles cell array (rest). function [remoteDeleted, remoteNew, remoteChanges,... localDeleted, localChanges] = findChanges(locHashes, locFiles,... remHashes, remFiles, ftpath) fprintf('\ncomparing local and remote (latest) hashes, this might take a minute...\n'); remoteDeleted = false(size(locFiles)); localChanges = false(size(locFiles)); remoteChanges = false(size(remFiles)); localDeleted = false(size(locFiles)); % note: no keeping track of local additions (not desirable probably) % compare them by looping over all files in local table for k = 1:numel(locFiles) ind = strcmp(remFiles, locFiles{k}); if sum(ind) > 1 % this should never happen; means remote table is corrupt warning('more than one entry found in remote hash table for file %s', locFiles{k}); end if ~any(ind) % file not found in remote table, should be deleted locally remoteDeleted(k) = 1; continue; end if ~strcmp(remHashes{ind}, locHashes{k}) % hash remote different from hash in local table remoteChanges(ind) = 1; end if ~exist(fullfile(ftpath, locFiles{k}), 'file') localDeleted(k) = 1; continue; end if (nargout > 4) % only check for local changes if requested, slow step if ~strcmp(CalcMD5(fullfile(ftpath, locFiles{k}), 'File'), locHashes{k}) % hash of actual file different from hash in local table localChanges(k) = 1; end end end % only remote additions have not yet been determined, do so now remoteNew = false(size(remFiles)); [dummy,inds] = setdiff(remFiles, locFiles); remoteNew(inds) = 1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % If str is a tab-separated string, with records separated by newlines, % parseHashTable(str) will return the three columns in the file: the first % column will be returned as hashes; the second as revs, the third as % files. function [hashes,files,revs] = parseHashTable(str) lines = regexp(str, '\n', 'split'); if isempty(lines{end}) lines = lines(1:end-1); end hashes = cell(1, numel(lines)); files = cell(1, numel(lines)); revs = cell(1, numel(lines)); for k = 1:numel(lines) tmp = regexp(lines{k}, '\t', 'split'); hashes{k} = tmp{1}; revs{k} = tmp{2}; files{k} = tmp{3}; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hashAll(filePointer, path, basepath, withRev) if nargin < 4 withRev = 0; end % these files are always excluded from the update and hashing routines file_excludes = {'.', '..', '.svn', 'test', 'signature.md5', 'signature-local.md5'}; list = dir(path); for k = 1:numel(list) if ~any(strcmp(list(k).name, file_excludes)) filename = [path '/' list(k).name]; if (list(k).isdir) hashAll(filePointer, filename, basepath, withRev); else md5 = CalcMD5(filename,'File'); if withRev [status, output] = system(['svn info ' filename]); rev = regexp(output, 'Last Changed Rev: (.*)', 'tokens', 'dotexceptnewline'); if ~isempty(rev) && ~isempty(rev{1}) rev = rev{1}{1}; else rev = 'UNKNOWN'; end else rev = 'UNKNOWN'; end filename = filename((numel(basepath)+2):end); % strip off the base path fprintf(filePointer, '%s\t%s\t%s\n',md5,rev,filename); end end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function outputHashTable(filePointer, hashes, files, revs) % sort the entries (highest revs should always be at the top) numRevs = cellfun(@str2double, revs); [sortedRevs,inds] = sort(numRevs, 'descend'); lastnan = find(isnan(sortedRevs), 1, 'last'); % put nans (=UNKNOWN) at the end inds = [inds(lastnan+1:end) inds(1:lastnan)]; hashes = hashes(inds); files = files(inds); revs = revs(inds); for k = 1:numel(hashes) fprintf(filePointer, '%s\t%s\t%s\n', hashes{k}, revs{k}, files{k}); end end
github
philippboehmsturm/antx-master
ft_transform_geometry.m
.m
antx-master/xspm8/external/fieldtrip/utilities/ft_transform_geometry.m
3,961
utf_8
2753b4ed40defdf48f32d8603dccba02
function [output] = ft_transform_geometry(transform, input) % FT_TRANSFORM_GEOMETRY applies a homogeneous coordinate transformation to % a structure with geometric information. These objects include: % - volume conductor geometry, consisting of a mesh, a set of meshes, a % single sphere, or multiple spheres. % - gradiometer of electrode structure containing sensor positions and % coil orientations (for MEG). % - headshape description containing positions in 3D space. % - sourcemodel description containing positions and optional orientations % in 3D space. % % The units in which the transformation matrix is expressed are assumed to % be the same units as the units in which the geometric object is % expressed. Depending on the input object, the homogeneous transformation % matrix should be limited to a rigid-body translation plus rotation % (MEG-gradiometer array), or to a rigid-body translation plus rotation % plus a global rescaling (volume conductor geometry). % % Use as % output = ft_transform_geometry(transform, input) % Copyright (C) 2011, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_transform_geometry.m$ checkrotation = (ft_datatype(input, 'volume') && ~strcmp(ft_voltype(input), 'unknown')) || ft_senstype(input, 'meg'); checkscaling = ~strcmp(ft_voltype(input), 'unknown'); % determine the rotation matrix rotation = eye(4); rotation(1:3,1:3) = transform(1:3,1:3); if any(abs(transform(4,:)-[0 0 0 1])>100*eps) error('invalid transformation matrix'); end if checkrotation % allow for some numerical imprecision if abs(det(rotation)-1)>100*eps error('only a rigid body transformation without rescaling is allowed'); end end if checkscaling % FIXME build in a check for uniform rescaling probably do svd or so % FIXME insert check for nonuniform scaling, should give an error end tfields = {'pos' 'pnt' 'o' 'chanpos' 'coilpos' 'elecpos', 'nas', 'lpa', 'rpa', 'zpoint'}; % apply rotation plus translation rfields = {'ori' 'nrm' 'coilori'}; % only apply rotation mfields = {'transform'}; % plain matrix multiplication recfields = {'fid' 'bnd'}; % recurse into these fields % the field 'r' is not included here, because it applies to a volume % conductor model, and scaling is not allowed, so r will not change. fnames = fieldnames(input); for k = 1:numel(fnames) if any(strcmp(fnames{k}, tfields)) input.(fnames{k}) = apply(transform, input.(fnames{k})); elseif any(strcmp(fnames{k}, rfields)) input.(fnames{k}) = apply(rotation, input.(fnames{k})); elseif any(strcmp(fnames{k}, mfields)) input.(fnames{k}) = transform*input.(fnames{k}); elseif any(strcmp(fnames{k}, recfields)) for j = 1:numel(input.(fnames{k})) input.(fnames{k})(j) = ft_transform_geometry(transform, input.(fnames{k})(j)); end else % do nothing end end output = input; return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that applies the homogeneous transformation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [new] = apply(transform, old) old(:,4) = 1; new = old * transform'; new = new(:,1:3);
github
philippboehmsturm/antx-master
nansum.m
.m
antx-master/xspm8/external/fieldtrip/utilities/private/nansum.m
185
utf_8
4859ec062780c478011dd7a8d94684a0
% NANSUM provides a replacement for MATLAB's nanmean. % % For usage see SUM. function y = nansum(x, dim) if nargin == 1 dim = 1; end idx = isnan(x); x(idx) = 0; y = sum(x, dim); end
github
philippboehmsturm/antx-master
nanstd.m
.m
antx-master/xspm8/external/fieldtrip/utilities/private/nanstd.m
231
utf_8
0ff62b1c345b5ad76a9af59cf07c2983
% NANSTD provides a replacement for MATLAB's nanstd that is almost % compatible. % % For usage see STD. Note that the three-argument call with FLAG is not % supported. function Y = nanstd(varargin) Y = sqrt(nanvar(varargin{:}));
github
philippboehmsturm/antx-master
warning_once.m
.m
antx-master/xspm8/external/fieldtrip/utilities/private/warning_once.m
3,832
utf_8
07dc728273934663973f4c716e7a3a1c
function [ws warned] = warning_once(varargin) % % Use as one of the following % warning_once(string) % warning_once(string, timeout) % warning_once(id, string) % warning_once(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. The default timeout value is 60 seconds. % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = warning_once(...) % or as % warning_once(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, warning_once accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = warning_once(...) % 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 % warning_once('the value is %d', 10) % instead you should do % warning_once(sprintf('the value is %d', 10)) % Copyright (C) 2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: warning_once.m 7123 2012-12-06 21:21:38Z roboos $ persistent stopwatch previous if nargin < 1 error('You need to specify at least a warning message'); end warned = false; if isstruct(varargin{1}) warning(varargin{1}); return; end % 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); timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); timeout = 60; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); timeout = 60; % default timeout in seconds fname = [warningArgs{1}]; end if isempty(timeout) error('Timeout ill-specified'); end if isempty(stopwatch) stopwatch = tic; end if isempty(previous) previous = struct; end now = toc(stopwatch); % measure time since first function call fname = decomma(fixname(fname)); % make a nice string that is allowed as structure fieldname if length(fname) > 63 % MATLAB max name fname = fname(1:63); end if ~isfield(previous, fname) || ... (isfield(previous, fname) && now>previous.(fname).timeout) % warning never given before or timed out ws = warning(warningArgs{:}); previous.(fname).timeout = now+timeout; previous.(fname).ws = ws; warned = true; else % the warning has been issued before, but has not timed out yet ws = previous.(fname).ws; end end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function name = decomma(name) name(name==',')=[]; end % function
github
philippboehmsturm/antx-master
nanmean.m
.m
antx-master/xspm8/external/fieldtrip/utilities/private/nanmean.m
165
utf_8
e6c473a49d8be6e12960af55ced45e54
% NANMEAN provides a replacement for MATLAB's nanmean. % % For usage see MEAN. function y = nanmean(x, dim) N = sum(~isnan(x), dim); y = nansum(x, dim) ./ N; end
github
philippboehmsturm/antx-master
nanvar.m
.m
antx-master/xspm8/external/fieldtrip/utilities/private/nanvar.m
1,093
utf_8
d9641af3bba1e2c6e3512199221e686c
% NANVAR provides a replacement for MATLAB's nanvar that is almost % compatible. % % For usage see VAR. Note that the weight-vector is not supported. If you % need it, please file a ticket at our bugtracker. function Y = nanvar(X, w, dim) switch nargin case 1 % VAR(x) % Normalize by n-1 when no dim is given. Y = nanvar_base(X); n = nannumel(X); w = 0; case 2 % VAR(x, 1) % VAR(x, w) % In this case, the default of normalizing by n is expected. Y = nanvar_base(X); n = nannumel(X); case 3 % VAR(x, w, dim) % if w=0 normalize by n-1, if w=1 normalize by n. Y = nanvar_base(X, dim); n = nannumel(X, dim); otherwise error ('Too many input arguments!') end % Handle different forms of normalization: if numel(w) == 0 % empty weights vector defaults to 0 w = 0; end if numel(w) ~= 1 error('Weighting vector w is not implemented! Please file a bug.'); end if ~isreal(X) Y = real(Y) + imag(Y); n = real(n); end if w == 1 Y = Y ./ n; end if w == 0 Y = Y ./ max(1, (n - 1)); % don't divide by zero! end
github
philippboehmsturm/antx-master
ft_plot_montage.m
.m
antx-master/xspm8/external/fieldtrip/plotting/ft_plot_montage.m
6,823
utf_8
5669e1d67db8e541768e7c780f85ff2e
function ft_plot_montage(dat, varargin) % FT_PLOT_MONTAGE makes a montage of a 3-D array by selecting slices at % regular distances and combining them in one large 2-D image. % % Use as % ft_plot_montage(dat, ...) % where dat is a 3-D array. % % Additional options should be specified in key-value pairs and can be % 'transform' = 4x4 homogeneous transformation matrix specifying the mapping from % voxel space to the coordinate system in which the data are plotted. % 'location' = 1x3 vector specifying a point on the plane which will be plotted % the coordinates are expressed in the coordinate system in which the % data will be plotted. location defines the origin of the plane % 'orientation' = 1x3 vector specifying the direction orthogonal through the plane % which will be plotted (default = [0 0 1]) % 'srange' = % 'slicesize' = % 'nslice' = % % See also FT_PLOT_ORTHO, FT_PLOT_SLICE, FT_SOURCEPLOT % undocumented, these are passed on to FT_PLOT_SLICE % 'intersectmesh' = triangulated mesh through which the intersection of the plane will be plotted (e.g. cortical sheet) % 'intersectcolor' = color for the intersection % Copyrights (C) 2012, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_plot_montage.m 7139 2012-12-11 12:25:35Z jansch $ transform = ft_getopt(varargin, 'transform', eye(4)); loc = ft_getopt(varargin, 'location'); ori = ft_getopt(varargin, 'orientation'); srange = ft_getopt(varargin, 'slicerange'); slicesize = ft_getopt(varargin, 'slicesize'); nslice = ft_getopt(varargin, 'nslice'); % the intersectmesh and intersectcolor options are passed on to FT_PLOT_SLICE dointersect = ~isempty(ft_getopt(varargin, 'intersectmesh')); % set the location if empty if isempty(loc) && (isempty(transform) || all(all(transform-eye(4)==0)==1)) % go to the middle of the volume if the data seem to be in voxel coordinates loc = size(dat)./2; elseif isempty(loc) % otherwise take the origin of the coordinate system loc = [0 0 0]; end % check compatibility of inputs if size(loc, 1) == 1 && isempty(nslice) nslice = 20; elseif size(loc, 1) == 1 && ~isempty(nslice) % this is not a problem, slice spacing will be determined elseif size(loc, 1) > 1 && isempty(nslice) % this is not a problem, number of slices is determined by loc nslice = size(loc, 1); elseif size(loc, 1) > 1 && ~isempty(nslice) if size(loc, 1) ~= nslice error('you should either specify a set of locations or a single location with a number of slices'); end end % set the orientation if empty if isempty(ori), ori = [0 0 1]; end % ensure the ori to have unit norm for k = 1:size(ori,1) ori(k,:) = ori(k,:)./norm(ori(k,:)); end % determine the slice range if size(loc, 1) == 1 && nslice > 1, if isempty(srange) || (ischar(srange) && strcmp(srange, 'auto')) srange = [-50 70]; else end loc = repmat(loc, [nslice 1]) + linspace(srange(1),srange(2),nslice)'*ori; end % ensure that the ori has the same size as the loc if size(ori,1)==1 && size(loc,1)>1, ori = repmat(ori, size(loc,1), 1); end div = [ceil(sqrt(nslice)) ceil(sqrt(nslice))]; optarg = varargin; corners = [inf -inf inf -inf inf -inf]; % get the corners for the axis specification for k = 1:nslice % define 'x' and 'y' axis in projection plane, the definition of x and y is more or less arbitrary [x, y] = projplane(ori(k,:)); % z = ori % get the transformation matrix to project onto the xy-plane T = [x(:) y(:) ori(k,:)' loc(k,:)'; 0 0 0 1]; optarg = ft_setopt(optarg, 'location', loc(k,:)); optarg = ft_setopt(optarg, 'orientation', ori(k,:)); ix = mod(k-1, div(1)); iy = floor((k-1)/div(1)); h(k) = ft_plot_slice(dat, optarg{:}); % FIXME is it safe to pass all optinoal inputs? xtmp = get(h(k), 'xdata'); ytmp = get(h(k), 'ydata'); ztmp = get(h(k), 'zdata'); siz = size(xtmp); if k==1 && isempty(slicesize) slicesize = siz; end % project the positions onto the xy-plane pos = [xtmp(:) ytmp(:) ztmp(:)]; pos = warp_apply(inv(T), pos); xtmp = reshape(pos(:,1), siz); ytmp = reshape(pos(:,2), siz); ztmp = reshape(pos(:,3), siz); % add some offset in the x and y directions to create the montage offset(1) = iy*(slicesize(1)-1); offset(2) = ix*(slicesize(2)-1); % update the specification of the corners of the montage plot if ~isempty(xtmp) c1 = offset(1) + min(xtmp(:)); c2 = offset(1) + max(xtmp(:)); c3 = offset(2) + min(ytmp(:)); c4 = offset(2) + max(ytmp(:)); c5 = min(ztmp(:)); c6 = max(ztmp(:)); end corners = [min(corners(1),c1) max(corners(2),c2) min(corners(3),c3) max(corners(4),c4) min(corners(5),c5) max(corners(6),c6)]; % update the positions set(h(k), 'ydata', offset(1) + xtmp); set(h(k), 'xdata', offset(2) + ytmp); set(h(k), 'zdata', 0 * ztmp); if dointersect, if ~exist('pprevious', 'var'), pprevious = []; end p = setdiff(findobj(gcf, 'type', 'patch'), pprevious); for kk = 1:numel(p) xtmp = get(p(kk), 'xdata'); ytmp = get(p(kk), 'ydata'); ztmp = get(p(kk), 'zdata'); siz2 = size(xtmp); pos = [xtmp(:) ytmp(:) ztmp(:)]; pos = warp_apply(inv(T), pos); xtmp = reshape(pos(:,1), siz2); ytmp = reshape(pos(:,2), siz2); ztmp = reshape(pos(:,3), siz2); % update the positions set(p(kk), 'ydata', offset(1) + xtmp); set(p(kk), 'xdata', offset(2) + ytmp); set(p(kk), 'zdata', 0 * ztmp); end pprevious = [pprevious(:);p(:)]; end drawnow; end set(gcf, 'color', [0 0 0]); set(gca, 'zlim', [0 1]); %axis equal; axis off; view([0 90]); axis(corners([3 4 1 2])); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [x, y] = projplane(z) [u, s, v] = svd([eye(3) z(:)]); x = u(:, 2)'; y = u(:, 3)';
github
philippboehmsturm/antx-master
ft_plot_slice.m
.m
antx-master/xspm8/external/fieldtrip/plotting/ft_plot_slice.m
13,140
utf_8
48a01c38f54d164d078bb54e122bd0e0
function [h, T2] = ft_plot_slice(dat, varargin) % FT_PLOT_SLICE cuts a 2-D slice from a 3-D volume and interpolates if needed % % Use as % ft_plot_slice(dat, ...) % ft_plot_ortho(dat, mask, ...) % where dat and mask are equal-sized 3-D arrays. % % Additional options should be specified in key-value pairs and can be % 'transform' = 4x4 homogeneous transformation matrix specifying the mapping from % voxel space to the coordinate system in which the data are plotted. % 'location' = 1x3 vector specifying a point on the plane which will be plotted % the coordinates are expressed in the coordinate system in which the % data will be plotted. location defines the origin of the plane % 'orientation' = 1x3 vector specifying the direction orthogonal through the plane % which will be plotted (default = [0 0 1]) % 'resolution' = number (default = 1) % 'datmask' = 3D-matrix with the same size as the data matrix, serving as opacitymap % If the second input argument to the function contains a matrix, this % will be used as the mask % 'opacitylim' = 1x2 vector specifying the limits for opacity masking % 'interpmethod' = string specifying the method for the interpolation, see INTERPN (default = 'nearest') % 'style' = string, 'flat' or '3D' % 'colormap' = string, see COLORMAP % 'colorlim' = 1x2 vector specifying the min and max for the colorscale % % See also FT_PLOT_ORTHO, FT_PLOT_MONTAGE, FT_SOURCEPLOT % undocumented % 'intersectmesh' = triangulated mesh through which the intersection of the plane will be plotted (e.g. cortical sheet) % 'intersectcolor' = color for the intersection % Copyrights (C) 2010, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_plot_slice.m 7308 2013-01-14 14:53:49Z jansch $ persistent previous_dim X Y Z % parse first input argument(s). it is either % (dat, varargin) % (dat, msk, varargin) % (dat, [], varargin) if numel(varargin)>0 && (isempty(varargin{1}) || isnumeric(varargin{1})) M = varargin{1}; varargin = varargin(2:end); end % get the optional input arguments transform = ft_getopt(varargin, 'transform'); loc = ft_getopt(varargin, 'location'); ori = ft_getopt(varargin, 'orientation', [0 0 1]); resolution = ft_getopt(varargin, 'resolution', 1); mask = ft_getopt(varargin, 'datmask'); opacitylim = ft_getopt(varargin, 'opacitylim'); interpmethod = ft_getopt(varargin, 'interpmethod', 'nearest'); cmap = ft_getopt(varargin, 'colormap'); clim = ft_getopt(varargin, 'colorlim'); doscale = ft_getopt(varargin, 'doscale', true); % only scale when necessary (time consuming), i.e. when plotting as grayscale image & when the values are not between 0 and 1 h = ft_getopt(varargin, 'surfhandle', []); mesh = ft_getopt(varargin, 'intersectmesh'); intersectcolor = ft_getopt(varargin, 'intersectcolor', 'yrgbmyrgbm'); intersectlinewidth = ft_getopt(varargin, 'intersectlinewidth', 2); intersectlinestyle = ft_getopt(varargin, 'intersectlinestyle'); % convert from yes/no/true/false/0/1 into a proper boolean doscale = istrue(doscale); if ~isa(dat, 'double') dat = cast(dat, 'double'); end if exist('M', 'var') && isempty(mask) warning_once('using the mask from the input and not from the varargin list'); mask = M; clear M; end % norm normalise the ori vector ori = ori./sqrt(sum(ori.^2)); % dimensionality of the input data dim = size(dat); if isempty(previous_dim), previous_dim = [0 0 0]; end % set the location if empty if isempty(loc) && (isempty(transform) || all(all(transform-eye(4)==0)==1)) loc = dim./2; elseif isempty(loc) loc = [0 0 0]; end % set the transformation matrix if empty if isempty(transform) transform = eye(4); end % check whether the mesh is ok dointersect = ~isempty(mesh); if ~iscell(mesh) mesh = {mesh}; end if dointersect for k = 1:numel(mesh) if isfield(mesh{k}, 'pos') % use pos instead of pnt mesh{k}.pnt = mesh{k}.pos; mesh{k} = rmfield(mesh{k}, 'pos'); end if ~isfield(mesh{k}, 'pnt') || ~isfield(mesh{k}, 'tri') error('the triangulated mesh should be a structure with pnt and tri'); end end end % check whether the mask is ok domask = ~isempty(mask); if domask if ~isequal(size(dat), size(mask)) error('the mask data should have the same dimensions as the functional data'); end end % determine whether interpolation is needed dointerp = false; dointerp = dointerp || sum(sum(transform-eye(4)))~=0; dointerp = dointerp || ~all(round(loc)==loc); dointerp = dointerp || sum(ori)~=1; dointerp = dointerp || ~(resolution==round(resolution)); % determine the caller function and toggle dointerp to true, if % ft_plot_slice has been called from ft_plot_montage % this is necessary for the correct allocation of the persistent variables st = dbstack; if ~dointerp && numel(st)>1 && strcmp(st(2).name, 'ft_plot_montage'), dointerp = true; end % determine the corner points of the volume in voxel and in plotting space [corner_vox, corner_head] = cornerpoints(dim+1, transform); if dointerp %--------cut a slice using interpn % get voxel indices if all(dim==previous_dim) % for speeding up the plotting on subsequent calls % use persistent variables X Y Z else [X, Y, Z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3)); end % define 'x' and 'y' axis in projection plane, the definition of x and y is more or less arbitrary [x, y] = projplane(ori); % z = ori % project the corner points onto the projection plane corner_proj = nan(size(corner_head)); for i=1:8 corner = corner_head(i, :); corner = corner - loc(:)'; corner_x = dot(corner, x); corner_y = dot(corner, y); corner_z = 0; corner_proj(i, :) = [corner_x corner_y corner_z]; end % determine a tight grid of points in the projection plane xplane = floor(min(corner_proj(:, 1))):resolution:ceil(max(corner_proj(:, 1))); yplane = floor(min(corner_proj(:, 2))):resolution:ceil(max(corner_proj(:, 2))); zplane = 0; [X2, Y2, Z2] = ndgrid(xplane, yplane, zplane); %2D cartesian grid of projection plane in plane voxels siz = size(squeeze(X2)); pos = [X2(:) Y2(:) Z2(:)]; clear X2 Y2 Z2; if false % this is for debugging ft_plot_mesh(warp_apply(T2, pos)) ft_plot_mesh(corner_head) axis on grid on xlabel('x') ylabel('y') zlabel('z') end % get the transformation matrix from plotting space to voxel space % T1 = inv(transform); % get the transformation matrix to get the projection plane at the right location and orientation into plotting space T2 = [x(:) y(:) ori(:) loc(:); 0 0 0 1]; % get the transformation matrix from projection plane to voxel space % M = T1*T2; M = transform\T2; % get the positions of the pixels of the desires plane in voxel space pos = warp_apply(M, pos); Xi = reshape(pos(:, 1), siz); Yi = reshape(pos(:, 2), siz); Zi = reshape(pos(:, 3), siz); V = interpn(X, Y, Z, dat, Xi, Yi, Zi, interpmethod); [V, Xi, Yi, Zi] = tight(V, Xi, Yi, Zi); siz = size(Xi); if domask, Vmask = tight(interpn(X, Y, Z, mask, Xi, Yi, Zi, interpmethod)); end if ~isempty(Xi) % now adjust the Xi, Yi and Zi, to allow for the surface object % convention, where the data point value is defined in the center of each % square, i.e. the number of elements in each of the dimensions of Xi, Yi % Zi should be 1 more than the functional data, and they should be displaced % by half a voxel distance dx2 = mean(diff(Xi,[],2),2); dx1 = mean(diff(Xi,[],1),1); dy2 = mean(diff(Yi,[],2),2); dy1 = mean(diff(Yi,[],1),1); dz2 = mean(diff(Zi,[],2),2); dz1 = mean(diff(Zi,[],1),1); Xi = [Xi-0.5*dx2*ones(1,siz(2)) Xi(:,end)+0.5*dx2; Xi(end,:)+0.5*dx1 Xi(end,end)+0.5*(dx1(end)+dx2(end))]; Yi = [Yi-0.5*dy2*ones(1,siz(2)) Yi(:,end)+0.5*dy2; Yi(end,:)+0.5*dy1 Yi(end,end)+0.5*(dy1(end)+dy2(end))]; Zi = [Zi-0.5*dz2*ones(1,siz(2)) Zi(:,end)+0.5*dz2; Zi(end,:)+0.5*dz1 Zi(end,end)+0.5*(dz1(end)+dz2(end))]; end else %-------cut a slice without interpolation [x, y] = projplane(ori); T2 = [x(:) y(:) ori(:) loc(:); 0 0 0 1]; % the '+1' and '-0.5' are needed due to the difference between handling % of image and surf. Surf color data is defined in the center of each % square, hence needs axes and coordinate adjustment if all(ori==[1 0 0]), xplane = loc(1); yplane = 1:(dim(2)+1); zplane = 1:(dim(3)+1); end if all(ori==[0 1 0]), xplane = 1:(dim(1)+1); yplane = loc(2); zplane = 1:(dim(3)+1); end if all(ori==[0 0 1]), xplane = 1:(dim(1)+1); yplane = 1:(dim(2)+1); zplane = loc(3); end [Xi, Yi, Zi] = ndgrid(xplane-0.5, yplane-0.5, zplane-0.5); % coordinate is centre of the voxel, 1-based siz = size(squeeze(Xi))-1; Xi = reshape(Xi, siz+1); if numel(xplane)==1, xplane = xplane([1 1]); end; Yi = reshape(Yi, siz+1); if numel(yplane)==1, yplane = yplane([1 1]); end; Zi = reshape(Zi, siz+1); if numel(zplane)==1, zplane = zplane([1 1]); end; V = reshape(dat(xplane(1:end-1), yplane(1:end-1), zplane(1:end-1)), siz); if domask, Vmask = reshape(mask(xplane(1:end-1), yplane(1:end-1), zplane(1:end-1)), siz); end end if isempty(cmap), % treat as gray value: scale and convert to rgb if doscale dmin = min(dat(:)); dmax = max(dat(:)); V = (V-dmin)./(dmax-dmin); clear dmin dmax end V(isnan(V)) = 0; % convert anatomy into RGB values V = cat(3, V, V, V); end if isempty(h), % get positions of the plane in plotting space posh = warp_apply(transform, [Xi(:) Yi(:) Zi(:)], 'homogeneous', 1e-8); if ~isempty(posh) Xh = reshape(posh(:, 1), siz+1); Yh = reshape(posh(:, 2), siz+1); Zh = reshape(posh(:, 3), siz+1); else % emulate old behavior, that allowed empty data to be plotted Xh = []; Yh = []; Zh = []; end % create surface object h = surface(Xh, Yh, Zh, V); else % update the colordata in the surface object set(h, 'Cdata', V); end set(h, 'linestyle', 'none'); if domask, set(h, 'FaceAlpha', 'flat'); set(h, 'AlphaDataMapping', 'scaled'); set(h, 'AlphaData', Vmask); if ~isempty(opacitylim) alim(opacitylim) end end if dointersect % determine three points on the plane inplane = eye(3) - (eye(3) * ori') * ori; v1 = loc + inplane(1,:); v2 = loc + inplane(2,:); v3 = loc + inplane(3,:); for k = 1:numel(mesh) [xmesh, ymesh, zmesh] = intersect_plane(mesh{k}.pnt, mesh{k}.tri, v1, v2, v3); % draw each individual line segment of the intersection if ~isempty(xmesh), p(k) = patch(xmesh', ymesh', zmesh', nan(1, size(xmesh,1))); if ~isempty(intersectcolor), set(p(k), 'EdgeColor', intersectcolor(k)); end if ~isempty(intersectlinewidth), set(p(k), 'LineWidth', intersectlinewidth); end if ~isempty(intersectlinestyle), set(p(k), 'LineStyle', intersectlinestyle); end end end end if ~isempty(cmap) colormap(cmap); end if ~isempty(clim) caxis(clim); end % update the axes to ensure that the whole volume fits ax = [min(corner_head) max(corner_head)]; axis(ax([1 4 2 5 3 6])-0.5); % reorder into [xmin xmax ymin ymaz zmin zmax] st = dbstack; if numel(st)>1, % ft_plot_slice has been called from another function % assume the axis settings to be handled there else axis equal axis vis3d end % store for future reference previous_dim = dim; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [x, y] = projplane(z) [u, s, v] = svd([eye(3) z(:)]); x = u(:, 2)'; y = u(:, 3)'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [V, Xi, Yi, Zi] = tight(V, Xi, Yi, Zi) % cut off the nans at the edges x = sum(~isfinite(V), 1)<size(V, 1); y = sum(~isfinite(V), 2)<size(V, 2); V = V(y, x); if nargin>1, Xi = Xi(y, x); end if nargin>2, Yi = Yi(y, x); end if nargin>3, Zi = Zi(y, x); end
github
philippboehmsturm/antx-master
ft_select_range.m
.m
antx-master/xspm8/external/fieldtrip/plotting/ft_select_range.m
14,023
utf_8
b3a594296f089050fedf2d5771d5715b
function ft_select_range(handle, eventdata, varargin) % FT_SELECT_RANGE is a helper function that can be used as callback function % in a figure. It allows the user to select a horizontal or a vertical % range, or one or multiple boxes. % % The callback function (and it's arguments) specified in callback is called % on a left-click inside a selection, or using the right-click context-menu. % The callback function will have as its first-to-last input argument the range of % all selections. The last input argument is either empty, or, when using the context % menu, a label of the item clicked. % Context menus are shown as the labels presented in the input. When activated, % the callback function is called, with the last input argument being the label of % the selection option. % % Input arguments: % event = string, event used as hook. % callback = function handle or cell-array containing function handle and additional input arguments % contextmenu = cell-array containing labels shown in right-click menu % multiple = boolean, allowing multiple selection boxes or not % xrange = boolean, xrange variable or not % yrange = boolean, yrange variable or not % clear = boolean % % % Example use: % x = randn(10,1); % y = randn(10,1); % figure; plot(x, y, '.'); % % The following example allows multiple horizontal and vertical selections to be made % set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'event', 'WindowButtonDownFcn', 'multiple', true, 'callback', @disp}); % set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'event', 'WindowButtonMotionFcn', 'multiple', true, 'callback', @disp}); % set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'event', 'WindowButtonUpFcn', 'multiple', true, 'callback', @disp}); % % The following example allows a single horizontal selection to be made % set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'event', 'WindowButtonDownFcn', 'multiple', false, 'xrange', true, 'yrange', false, 'callback', @disp}); % set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'event', 'WindowButtonMotionFcn', 'multiple', false, 'xrange', true, 'yrange', false, 'callback', @disp}); % set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'event', 'WindowButtonUpFcn', 'multiple', false, 'xrange', true, 'yrange', false, 'callback', @disp}); % % The following example allows a single point to be selected % set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'event', 'WindowButtonDownFcn', 'multiple', false, 'xrange', false, 'yrange', false, 'callback', @disp}); % set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'event', 'WindowButtonMotionFcn', 'multiple', false, 'xrange', false, 'yrange', false, 'callback', @disp}); % set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'event', 'WindowButtonUpFcn', 'multiple', false, 'xrange', false, 'yrange', false, 'callback', @disp}); % Copyright (C) 2009-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_select_range.m 7366 2013-01-21 13:22:17Z roboos $ % get the optional arguments event = ft_getopt(varargin, 'event'); callback = ft_getopt(varargin, 'callback'); multiple = ft_getopt(varargin, 'multiple', false); xrange = ft_getopt(varargin, 'xrange', true); yrange = ft_getopt(varargin, 'yrange', true); clear = ft_getopt(varargin, 'clear', false); contextmenu = ft_getopt(varargin, 'contextmenu'); % this will be displayed following a right mouse click % convert 'yes/no' string to boolean value multiple = istrue(multiple); xrange = istrue(xrange); yrange = istrue(yrange); clear = istrue(clear); p = handle; while ~isequal(p, 0) handle = p; p = get(handle, 'parent'); end if ishandle(handle) userData = getappdata(handle, 'select_range_m'); else userData = []; end if isempty(userData) userData.range = []; % this is a Nx4 matrix with the selection range userData.box = []; % this is a Nx1 vector with the line handle end p = get(gca, 'CurrentPoint'); p = p(1,1:2); abc = axis; xLim = abc(1:2); yLim = abc(3:4); % limit cursor coordinates if p(1)<xLim(1), p(1)=xLim(1); end; if p(1)>xLim(2), p(1)=xLim(2); end; if p(2)<yLim(1), p(2)=yLim(1); end; if p(2)>yLim(2), p(2)=yLim(2); end; % determine whether the user is currently making a selection selecting = numel(userData.range)>0 && any(isnan(userData.range(end,:))); pointonly = ~xrange && ~yrange; if pointonly && multiple warning('multiple selections are not possible for a point'); multiple = false; end % setup contextmenu if ~isempty(contextmenu) if isempty(get(handle,'uicontextmenu')) hcmenu = uicontextmenu; hcmenuopt = nan(1,numel(contextmenu)); for icmenu = 1:numel(contextmenu) hcmenuopt(icmenu) = uimenu(hcmenu, 'label', contextmenu{icmenu}, 'callback', {@evalcontextcallback, callback{:}, []}); % empty matrix is placeholder, will be updated to userdata.range end end if ~exist('hcmenuopt','var') hcmenuopt = get(get(handle,'uicontextmenu'),'children'); % uimenu handles, used for switchen on/off and updating end % setting associations for all clickable objects % this out to be pretty fast, if this is still to slow in some cases, the code below has to be reused if ~exist('hcmenu','var') hcmenu = get(handle,'uicontextmenu'); end set(findobj(handle,'hittest','on'), 'uicontextmenu',hcmenu); % to be used if above is too slow % associations only done once. this might be an issue in some cases, cause when a redraw is performed in the original figure (e.g. databrowser), a specific assocations are lost (lines/patches/text) % set(get(handle,'children'),'uicontextmenu',hcmenu); % set(findobj(handle,'type','text'), 'uicontextmenu',hcmenu); % set(findobj(handle,'type','patch'),'uicontextmenu',hcmenu); % set(findobj(handle,'type','line'), 'uicontextmenu',hcmenu); % fixme: add other often used object types that ft_select_range is called upon end % get last-used-mouse-button lastmousebttn = get(gcf,'selectiontype'); switch lower(event) case lower('WindowButtonDownFcn') switch lastmousebttn case 'normal' % left click if inSelection(p, userData.range) % the user has clicked in one of the existing selections evalCallback(callback, userData.range); if clear delete(userData.box(ishandle(userData.box))); userData.range = []; userData.box = []; set(handle, 'Pointer', 'crosshair'); if ~isempty(contextmenu) && ~pointonly set(hcmenuopt,'enable','off') end end else if ~multiple % start with a new selection delete(userData.box(ishandle(userData.box))); userData.range = []; userData.box = []; end % add a new selection range userData.range(end+1,1:4) = nan; userData.range(end,1) = p(1); userData.range(end,3) = p(2); % add a new selection box xData = [nan nan nan nan nan]; yData = [nan nan nan nan nan]; userData.box(end+1) = line(xData, yData); end end case lower('WindowButtonUpFcn') switch lastmousebttn case 'normal' % left click if selecting % select the other corner of the box userData.range(end,2) = p(1); userData.range(end,4) = p(2); end if multiple && ~isempty(userData.range) && ~diff(userData.range(end,1:2)) && ~diff(userData.range(end,3:4)) % start with a new selection delete(userData.box(ishandle(userData.box))); userData.range = []; userData.box = []; end if ~isempty(userData.range) % ensure that the selection is sane if diff(userData.range(end,1:2))<0 userData.range(end,1:2) = userData.range(end,[2 1]); end if diff(userData.range(end,3:4))<0 userData.range(end,3:4) = userData.range(end,[4 3]); end if pointonly % only select a single point userData.range(end,2) = userData.range(end,1); userData.range(end,4) = userData.range(end,3); elseif ~xrange % only select along the y-axis userData.range(end,1:2) = [-inf inf]; elseif ~yrange % only select along the x-axis userData.range(end,3:4) = [-inf inf]; end % update contextmenu callbacks if ~isempty(contextmenu) updateContextCallback(hcmenuopt, callback, userData.range) end end if pointonly && ~multiple evalCallback(callback, userData.range); if clear delete(userData.box(ishandle(userData.box))); userData.range = []; userData.box = []; set(handle, 'Pointer', 'crosshair'); end end end case lower('WindowButtonMotionFcn') if selecting && ~pointonly % update the selection box if xrange x1 = userData.range(end,1); x2 = p(1); else x1 = xLim(1); x2 = xLim(2); end if yrange y1 = userData.range(end,3); y2 = p(2); else y1 = yLim(1); y2 = yLim(2); end xData = [x1 x2 x2 x1 x1]; yData = [y1 y1 y2 y2 y1]; set(userData.box(end), 'xData', xData); set(userData.box(end), 'yData', yData); set(userData.box(end), 'Color', [0 0 0]); set(userData.box(end), 'EraseMode', 'xor'); set(userData.box(end), 'LineStyle', '--'); set(userData.box(end), 'LineWidth', 1.5); set(userData.box(end), 'Visible', 'on'); else % update the cursor if inSelection(p, userData.range) set(handle, 'Pointer', 'hand'); if ~isempty(contextmenu) set(hcmenuopt,'enable','on') end else set(handle, 'Pointer', 'crosshair'); if ~isempty(contextmenu) set(hcmenuopt,'enable','off') end end end otherwise error('unexpected event "%s"', event); end % switch event % put the modified selections back into the figure if ishandle(handle) setappdata(handle, 'select_range_m', userData); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function retval = inSelection(p, range) if isempty(range) retval = false; else retval = (p(1)>=range(:,1) & p(1)<=range(:,2) & p(2)>=range(:,3) & p(2)<=range(:,4)); retval = any(retval); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function evalCallback(callback, val) % no context menu item was clicked, set to empty cmenulab = []; if ~isempty(callback) if isa(callback, 'cell') % the callback specifies a function and additional arguments funhandle = callback{1}; funargs = callback(2:end); feval(funhandle, funargs{:}, val, cmenulab); else % the callback only specifies a function funhandle = callback; feval(funhandle, val); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function updateContextCallback(hcmenuopt, callback, val) if ~isempty(callback) if isa(callback, 'cell') % the callback specifies a function and additional arguments funhandle = callback{1}; funargs = callback(2:end); callback = {funhandle, funargs{:}, val}; else % the callback only specifies a function funhandle = callback; callback = {funhandle, val}; end for icmenu = 1:numel(hcmenuopt) set(hcmenuopt(icmenu),'callback',{@evalContextCallback, callback{:}}) end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function evalContextCallback(hcmenuopt, eventdata, varargin) % delete selection box if present % get parent (uimenu -> uicontextmenu -> parent) parent = get(get(hcmenuopt,'parent'),'parent'); % fixme: isn't the parent handle always input provided in the callback? userData = getappdata(parent, 'select_range_m'); if ishandle(userData.box) if any(~isnan([get(userData.box,'ydata') get(userData.box,'xdata')])) delete(userData.box(ishandle(userData.box))); userData.range = []; userData.box = []; set(parent, 'Pointer', 'crosshair'); setappdata(parent, 'select_range_m', userData); end end % get contextmenu name cmenulab = get(hcmenuopt,'label'); if numel(varargin)>1 % the callback specifies a function and additional arguments funhandle = varargin{1}; funargs = varargin(2:end); feval(funhandle, funargs{:}, cmenulab); else % the callback only specifies a function funhandle = varargin{1}; feval(funhandle, val, cmenulab); end
github
philippboehmsturm/antx-master
ft_select_channel.m
.m
antx-master/xspm8/external/fieldtrip/plotting/ft_select_channel.m
5,763
utf_8
65f75d2a28a115832e61158855e728ff
function ft_select_channel(handle, eventdata, varargin) % FT_SELECT_CHANNEL is a helper function that can be used as callback function % in a figure. It allows the user to select a channel. The channel labels % are returned. % % Use as % label = ft_select_channel(h, eventdata, ...) % The first two arguments are automatically passed by Matlab to any % callback function. % % Additional options should be specified in key-value pairs and can be % 'callback' = function handle to be executed after channels have been selected % % You can pass additional arguments to the callback function in a cell-array % like {@function_handle,arg1,arg2} % % Example % % create a figure % lay = ft_prepare_layout([]) % ft_plot_lay(lay) % % % add the required guidata % info = guidata(gcf) % info.x = lay.pos(:,1); % info.y = lay.pos(:,2); % info.label = lay.label % guidata(gcf, info) % % % add this function as the callback to make a single selection % set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'callback', @disp}) % % % or to make multiple selections % set(gcf, 'WindowButtonDownFcn', {@ft_select_channel, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}) % set(gcf, 'WindowButtonUpFcn', {@ft_select_channel, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}) % set(gcf, 'WindowButtonMotionFcn', {@ft_select_channel, 'multiple', true, 'callback', @disp, 'event', 'WindowButtonDownFcn'}) % % Subsequently you can click in the figure and you'll see that the disp % function is executed as callback and that it displays the selected % channels. % Copyright (C) 2009, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_select_channel.m 7123 2012-12-06 21:21:38Z roboos $ % get optional input arguments multiple = ft_getopt(varargin, 'multiple', false); callback = ft_getopt(varargin, 'callback'); if istrue(multiple) % the selection is done using select_range, which will subsequently call select_channel_multiple set(gcf, 'WindowButtonDownFcn', {@ft_select_range, 'multiple', true, 'callback', {@select_channel_multiple, callback}, 'event', 'WindowButtonDownFcn'}); set(gcf, 'WindowButtonUpFcn', {@ft_select_range, 'multiple', true, 'callback', {@select_channel_multiple, callback}, 'event', 'WindowButtonUpFcn'}); set(gcf, 'WindowButtonMotionFcn', {@ft_select_range, 'multiple', true, 'callback', {@select_channel_multiple, callback}, 'event', 'WindowButtonMotionFcn'}); else % the selection is done using select_channel_single pos = get(gca, 'CurrentPoint'); pos = pos(1,1:2); select_channel_single(pos, callback) end % if multiple %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to assist in the selection of a single channel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_channel_single(pos, callback) info = guidata(gcf); x = info.x; y = info.y; label = info.label; % compute a tolerance measure distance = sqrt(abs(sum([x y]'.*[x y]',1))); distance = triu(distance, 1); distance = distance(:); distance = distance(distance>0); distance = median(distance); tolerance = 0.3*distance; % compute the distance between the clicked point and all channels dx = x - pos(1); dy = y - pos(2); dd = sqrt(dx.^2 + dy.^2); [d, i] = min(dd); if d<tolerance label = label{i}; fprintf('channel "%s" selected\n', label); else label = {}; fprintf('no channel selected\n'); end % execute the original callback with the selected channel as input argument if ~isempty(callback) if isa(callback, 'cell') % the callback specifies a function and additional arguments funhandle = callback{1}; funargs = callback(2:end); feval(funhandle, label, funargs{:}); else % the callback only specifies a function funhandle = callback; feval(funhandle, label); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to assist in the selection of multiple channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function select_channel_multiple(callback,range,cmenulab) % last input is context menu label, see ft_select_range info = guidata(gcf); x = info.x(:); y = info.y(:); label = info.label(:); % determine which channels ly in the selected range select = false(size(label)); for i=1:size(range,1) select = select | (x>=range(i, 1) & x<=range(i, 2) & y>=range(i, 3) & y<=range(i, 4)); end label = label(select); % execute the original callback with the selected channels as input argument if any(select) if ~isempty(callback) if isa(callback, 'cell') % the callback specifies a function and additional arguments funhandle = callback{1}; funargs = callback(2:end); feval(funhandle, label, funargs{:}); else % the callback only specifies a function funhandle = callback; feval(funhandle, label); end end end
github
philippboehmsturm/antx-master
ft_datatype_sens.m
.m
antx-master/xspm8/external/fieldtrip/plotting/private/ft_datatype_sens.m
8,876
utf_8
9cca02c1384fde3f0c40f1a5a3a0253a
function [sens] = ft_datatype_sens(sens, varargin) % FT_DATATYPE_SENS describes the FieldTrip structure that represents % an EEG, ECoG, or MEG sensor array. This structure is commonly called % "elec" for EEG and "grad" for MEG, or more general "sens" for either % one. % % The structure for MEG gradiometers and/or magnetometers contains % sens.label = Mx1 cell-array with channel labels % sens.chanpos = Mx3 matrix with channel positions % sens.chanori = Mx3 matrix with channel orientations, used for synthetic planar gradient computation % sens.tra = MxN matrix to combine coils into channels % sens.coilpos = Nx3 matrix with coil positions % sens.coilori = Nx3 matrix with coil orientations % sens.balance = structure containing info about the balancing, See FT_APPLY_MONTAGE % % The structure for EEG or ECoG channels contains % sens.label = Mx1 cell-array with channel labels % sens.chanpos = Mx3 matrix with channel positions % sens.tra = MxN matrix to combine electrodes into channels % sens.elecpos = Nx3 matrix with electrode positions % In case sens.tra is not present in the EEG sensor array, the channels % are assumed to be average referenced. % % The following fields are optional % sens.type = string with the MEG or EEG acquisition system, see FT_SENSTYPE % 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. 'T', 'fT' or 'fT/cm' % sens.fid = structure with fiducial information % % Revision history: % % (2011v2/latest) The chantype and chanunit have been added for MEG. % % (2011v1) To facilitate determining the position of channels (e.g. for plotting) % in case of balanced MEG or bipolar EEG, an explicit distinction has been made % between chanpos+chanori and coilpos+coilori (for MEG) and chanpos and elecpos % (for EEG). The pnt and ori fields are removed % % (2010) Added support for bipolar or otherwise more complex linear combinations % of EEG electrodes using sens.tra, similar to MEG. % % (2009) Noice reduction has been added for MEG systems in the balance field. % % (2006) The optional fields sens.type and sens.unit were added. % % (2003) The initial version was defined, which looked like this for EEG % sens.pnt = Mx3 matrix with electrode positions % sens.label = Mx1 cell-array with channel labels % and like this for MEG % sens.pnt = Nx3 matrix with coil positions % sens.ori = Nx3 matrix with coil orientations % sens.tra = MxN matrix to combine coils into channels % sens.label = Mx1 cell-array with channel labels % % See also FT_READ_SENS, FT_SENSTYPE, FT_CHANTYPE, FT_APPLY_MONTAGE, CTF2GRAD, FIF2GRAD, % BTI2GRAD, YOKOGAWA2GRAD, ITAB2GRAD % Copyright (C) 2011, Robert Oostenveld & Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_datatype_sens.m 7248 2012-12-21 11:37:13Z roboos $ % 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}; end % get the optional input arguments, which should be specified as key-value pairs version = ft_getopt(varargin, 'version', 'latest'); if strcmp(version, 'latest') version = '2011v2'; end if isempty(sens) return; end switch version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case '2011v2' % 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 % there are many cases which deal with either eeg or meg ismeg = ft_senstype(sens, 'meg'); 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, 'channel', 'all'); % 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, 'channel', 'all'); % 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 % FIXME for EEG we have not yet figured out how to deal with this end end if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown')) if ismeg sens.chanunit = ft_chanunit(sens); else % FIXME for EEG we have not yet figured out how to deal with this end end if ~isfield(sens, 'unit') sens = ft_convert_units(sens); 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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 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
philippboehmsturm/antx-master
ptriside.m
.m
antx-master/xspm8/external/fieldtrip/plotting/private/ptriside.m
1,257
utf_8
f52f0beb3731b653116c217b37b673d2
function [side] = ptriside(v1, v2, v3, r, tolerance) % PTRISIDE determines the side of a plane on which a set of points lie. it % returns 0 for the points that lie on the plane % % [side] = ptriside(v1, v2, v3, r) % % the side of points r is determined relative to the plane spanned by % vertices v1, v2 and v3. v1,v2 and v3 should be 1x3 vectors. r should be a % Nx3 matrix % Copyright (C) 2002, Robert Oostenveld % % $Log: ptriside.m,v $ % Revision 1.3 2003/03/11 15:35:20 roberto % converted all files from DOS to UNIX % % Revision 1.2 2003/03/04 21:46:19 roberto % added CVS log entry and synchronized all copyright labels % if nargin<5 tolerance = 100*eps; end n = size(r,1); a = r - ones(n,1)*v1; b = v2 - v1; c = v3 - v1; d = crossproduct(b, c); val = dotproduct(a, d); side = zeros(n, 1); side(val > tolerance) = 1; side(val < -tolerance) = -1; %if val>tolerance % side=1; %elseif val<-tolerance % side=-1; %else % side=0; %end % subfunction without overhead to speed up function c = crossproduct(a, b) c(1) = a(2)*b(3)-a(3)*b(2); c(2) = a(3)*b(1)-a(1)*b(3); c(3) = a(1)*b(2)-a(2)*b(1); % subfunction without overhead to speed up, input a can be a matrix function d = dotproduct(a, b) d = a(:,1)*b(1)+a(:,2)*b(2)+a(:,3)*b(3);
github
philippboehmsturm/antx-master
ft_convert_units.m
.m
antx-master/xspm8/external/fieldtrip/plotting/private/ft_convert_units.m
7,014
utf_8
b6713ad4580d1dac67d2d43489f0dc55
function [obj] = ft_convert_units(obj, target) % FT_CONVERT_UNITS changes the geometrical dimension to the specified SI unit. % The units of the input object is determined from the structure field % object.unit, or is estimated based on the spatial extend of the structure, % e.g. a volume conduction model of the head should be approximately 20 cm large. % % Use as % [object] = ft_convert_units(object, target) % % The following input objects are supported % simple dipole position % electrode definition % gradiometer array definition % volume conductor definition % dipole grid definition % anatomical mri % segmented mri % % 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 FT_ESTIMATE_UNITS, FT_READ_VOL, FT_READ_SENS % Copyright (C) 2005-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_convert_units.m 7337 2013-01-16 15:52:00Z johzum $ % 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 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); else tmp(i) = ft_convert_units(obj(i)); end end obj = tmp; 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; 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, '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 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, '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 % compue the scaling factor from the input units to the desired ones scale = scalingfactor(unit, target); % give some information about the conversion fprintf('converting units from ''%s'' to ''%s''\n', unit, target) % volume conductor model if isfield(obj, 'r'), obj.r = scale * obj.r; end if isfield(obj, 'o'), obj.o = scale * obj.o; end if isfield(obj, 'bnd'), for i=1:length(obj.bnd), obj.bnd(i).pnt = scale * obj.bnd(i).pnt; end, end % gradiometer array if isfield(obj, 'pnt1'), obj.pnt1 = scale * obj.pnt1; end if isfield(obj, 'pnt2'), obj.pnt2 = scale * obj.pnt2; end if isfield(obj, 'prj'), obj.prj = scale * obj.prj; end % gradiometer array, electrode array, head shape or dipole grid if isfield(obj, 'pnt'), obj.pnt = scale * obj.pnt; end if isfield(obj, 'chanpos'), obj.chanpos = scale * obj.chanpos; end 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 length(tok)==1 % assume that it is T or so elseif length(tok)==2 % assume that it is T/cm or so obj.tra(i,:) = obj.tra(i,:) / scale; obj.chanunit{i} = [tok{1} '/' target]; 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 % dipole grid if isfield(obj, 'pos'), obj.pos = scale * obj.pos; end % anatomical MRI or functional volume if isfield(obj, 'transform'), H = diag([scale scale scale 1]); obj.transform = H * obj.transform; end if isfield(obj, 'transformorig'), H = diag([scale scale scale 1]); obj.transformorig = H * obj.transformorig; end % remember the unit obj.unit = target; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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
philippboehmsturm/antx-master
ft_apply_montage.m
.m
antx-master/xspm8/external/fieldtrip/plotting/private/ft_apply_montage.m
13,440
utf_8
4d1063ba5c92c5b8e6c094a1e2b611dd
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 inputor array. The inputor array can subsequently be used for % forward computation and source reconstruction of the data. % % Use as % [sens] = ft_apply_montage(sens, montage, ...) % [data] = ft_apply_montage(data, montage, ...) % [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.labelnew = Mx1 cell-array % montage.labelorg = Nx1 cell-array % % As an example, a bipolar montage could look like this % bipolar.labelorg = {'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 % ]; % % Additional options should be specified in key-value pairs and can be % 'keepunused' string, 'yes' or 'no' (default = 'no') % 'inverse' string, 'yes' or 'no' (default = 'no') % % If the first input is a montage, then the second input montage will be % applied to the first. In effect, the output montage will first do % montage1, then montage2. % % See also FT_READ_SENS, FT_TRANSFORM_SENS % Copyright (C) 2008-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_apply_montage.m 7393 2013-01-23 14:33:27Z jorhor $ % get optional input arguments keepunused = ft_getopt(varargin, 'keepunused', 'no'); inverse = ft_getopt(varargin, 'inverse', 'no'); feedback = ft_getopt(varargin, 'feedback', 'text'); bname = ft_getopt(varargin, 'balancename', ''); if ~isfield(input, 'label') && isfield(input, 'labelnew') % the input data structure is also a montage inputlabel = input.labelnew; else % the input should describe the channel labels inputlabel = input.label; end % check the consistency of the input inputor array or data if ~all(isfield(montage, {'tra', 'labelorg', '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.labelorg) error('the number of channels in the montage is inconsistent'); end if strcmp(inverse, 'yes') % apply the inverse montage, i.e. undo a previously applied montage tmp.labelnew = montage.labelorg; % swap around tmp.labelorg = montage.labelnew; % swap around tmp.tra = full(montage.tra); if rank(tmp.tra) < length(tmp.tra) warning('the linear projection for the montage is not full-rank, the resulting data will have reduced dimensionality'); tmp.tra = pinv(tmp.tra); else tmp.tra = inv(tmp.tra); end montage = tmp; end % use default transfer from sensors to channels if not specified if isfield(input, 'pnt') && ~isfield(input, 'tra') nchan = size(input.pnt,1); input.tra = eye(nchan); elseif isfield(input, 'chanpos') && ~isfield(input, 'tra') nchan = size(input.chanpos,1); input.tra = eye(nchan); end % select and keep the columns that are non-empty, i.e. remove the empty columns selcol = find(~all(montage.tra==0, 1)); montage.tra = montage.tra(:,selcol); montage.labelorg = montage.labelorg(selcol); clear selcol % select and remove the columns corresponding to channels that are not present in the original data remove = setdiff(montage.labelorg, intersect(montage.labelorg, inputlabel)); selcol = match_str(montage.labelorg, remove); % we cannot just remove the colums, all rows that depend on it should also be removed selrow = false(length(montage.labelnew),1); for i=1:length(selcol) selrow = selrow & (montage.tra(:,selcol(i))~=0); end % convert from indices to logical vector selcol = indx2logical(selcol, length(montage.labelorg)); % remove rows and columns montage.labelorg = montage.labelorg(~selcol); montage.labelnew = montage.labelnew(~selrow); montage.tra = montage.tra(~selrow, ~selcol); clear remove selcol selrow i % add columns for the channels that are present in the data but not involved in the montage, and stick to the original order in the data [add, ix] = setdiff(inputlabel, montage.labelorg); add = inputlabel(sort(ix)); m = size(montage.tra,1); n = size(montage.tra,2); k = length(add); if strcmp(keepunused, 'yes') % add the channels that are not rereferenced to the input and output montage.tra((m+(1:k)),(n+(1:k))) = eye(k); montage.labelorg = cat(1, montage.labelorg(:), add(:)); montage.labelnew = cat(1, montage.labelnew(:), add(:)); else % add the channels that are not rereferenced to the input montage only montage.tra(:,(n+(1:k))) = zeros(m,k); montage.labelorg = cat(1, montage.labelorg(:), add(:)); end clear add m n k % determine whether all channels are unique m = size(montage.tra,1); n = size(montage.tra,2); if length(unique(montage.labelnew))~=m error('not all output channels of the montage are unique'); end if length(unique(montage.labelorg))~=n error('not all input channels of the montage are unique'); end % determine whether all channels that have to be rereferenced are available if length(intersect(inputlabel, montage.labelorg))~=length(montage.labelorg) error('not all channels that are required in the montage are available in the data'); end % reorder the columns of the montage matrix [selinput, selmontage] = match_str(inputlabel, montage.labelorg); montage.tra = double(montage.tra(:,selmontage)); montage.labelorg = montage.labelorg(selmontage); % making the tra matrix sparse will speed up subsequent multiplications % but should not result in a sparse matrix if size(montage.tra,1)>1 montage.tra = sparse(montage.tra); end inputtype = 'unknown'; if isfield(input, 'labelorg') && isfield(input, 'labelnew') inputtype = 'montage'; elseif isfield(input, 'tra') inputtype = 'sens'; elseif isfield(input, 'trial') inputtype = 'raw'; elseif isfield(input, 'fourierspctrm') inputtype = 'freq'; 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; 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 sens.chanpos = nan(numel(montage.labelnew),3); %input = rmfield(input, 'chanpos'); end end if isfield(sens, 'chanori') if keepchans sens.chanori = sens.chanori(sel2,:); else sens.chanori = nan(numel(montage.labelnew),3); %input = rmfield(input, 'chanori'); end end sens.label = montage.labelnew; % keep track of the order of the balancing and which one is the current one if strcmp(inverse, 'yes') if isfield(sens, 'balance')% && isfield(sens.balance, 'previous') if isfield(sens.balance, 'previous') && numel(sens.balance.previous)>=1 sens.balance.current = sens.balance.previous{1}; sens.balance.previous = sens.balance.previous(2:end); elseif isfield(sens.balance, 'previous') sens.balance.current = 'none'; sens.balance = rmfield(sens.balance, 'previous'); else sens.balance.current = 'none'; end end elseif ~strcmp(inverse, 'yes') && ~isempty(bname) if isfield(sens, 'balance'), % 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; % 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 elseif strcmp(freq.dimord, 'rpttap_chan_freq_time') siz = size(freq.fourierspctrm); nrpt = siz(1); nchan = siz(2); nfreq = siz(3); ntime = siz(4); output = zeros(nrpt, size(montage.tra,1), nfreq, ntime); for foilop=1:nfreq for toilop = 1:ntime output(:,:,foilop,toilop) = freq.fourierspctrm(:,:,foilop,toilop) * montage.tra'; end end else error('unsupported dimord in frequency data (%s)', freq.dimord); end % replace the Fourier spectrum freq.fourierspctrm = output; freq.label = montage.labelnew; % rename the output variable input = freq; clear freq otherwise error('unrecognized input'); end % switch inputtype % check whether the input contains chantype and/or chanunit and remove these % as they may have been invalidated by the transform (e.g. with megplanar) [sel1, sel2] = match_str(montage.labelnew, inputlabel); keepchans = (length(sel1)==length(montage.labelnew)); if isfield(input, 'chantype') if keepchans % reorder them according to the montage sens.chantype = input.chantype(sel2,:); else input = rmfield(input, 'chantype'); end end if isfield(input, 'chanunit') if keepchans % reorder them according to the montage sens.chanunit = input.chanunit(sel2,:); else input = rmfield(input, 'chanunit'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = indx2logical(x, n) y = false(1,n); y(x) = true;
github
philippboehmsturm/antx-master
select3dtool.m
.m
antx-master/xspm8/external/fieldtrip/plotting/private/select3dtool.m
2,713
utf_8
fdf7d572638e6ebd059c63f233d26704
function select3dtool(arg) %SELECT3DTOOL A simple tool for interactively obtaining 3-D coordinates % % SELECT3DTOOL(FIG) Specify figure handle % % Example: % surf(peaks); % select3dtool; % % click on surface if nargin<1 arg = gcf; end if ~ishandle(arg) feval(arg); return; end %% initialize gui %% fig = arg; figure(fig); uistate = uiclearmode(fig); [tool, htext] = createUI; hmarker1 = line('marker','o','markersize',10,'markerfacecolor','k','erasemode','xor','visible','off'); hmarker2 = line('marker','o','markersize',10,'markerfacecolor','r','erasemode','xor','visible','off'); state.uistate = uistate; state.text = htext; state.tool = tool; state.fig = fig; state.marker1 = hmarker1; state.marker2 = hmarker2; setappdata(fig,'select3dtool',state); setappdata(state.tool,'select3dhost',fig); set(fig,'windowbuttondownfcn','select3dtool(''click'')'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function off state = getappdata(gcbf,'select3dtool'); if ~isempty(state) delete(state.tool); end fig = getappdata(gcbf,'select3dhost'); if ~isempty(fig) & ishandle(fig) state = getappdata(fig,'select3dtool'); uirestore(state.uistate); delete(state.marker1); delete(state.marker2); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function click [p v vi] = select3d; state = getappdata(gcbf,'select3dtool'); if ~ishandle(state.text) state.text = createUI; end if ~ishandle(state.marker1) state.marker1 = []; end if ~ishandle(state.marker2) state.marker2 = []; end setappdata(state.fig,'select3dtool',state); if isempty(v) v = [nan nan nan]; vi = nan; set(state.marker2,'visible','off'); else set(state.marker2,'visible','on','xdata',v(1),'ydata',v(2),'zdata',v(3)); end if isempty(p) p = [nan nan nan]; set(state.marker1,'visible','off'); else set(state.marker1,'visible','on','xdata',p(1),'ydata',p(2),'zdata',p(3)); end % Update tool and markers set(state.text,'string',createString(p(1),p(2),p(3),v(1),v(2),v(3),vi)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [fig, h] = createUI pos = [200 200 200 200]; % Create selection tool % fig = figure('handlevisibility','off','menubar','none','resize','off',... 'numbertitle','off','name','Select 3-D Tool','position',pos,'deletefcn','select3dtool(''off'')'); h = uicontrol('style','text','parent',fig,'string',createString(0,0,0,0,0,0,0),... 'units','norm','position',[0 0 1 1],'horizontalalignment','left'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [str] = createString(px,py,pz,vx,vy,vz,vi) str = sprintf(' Position:\n X %f\n Y: %f\n Z: %f \n\n Vertex:\n X: %f\n Y: %f\n Z: %f \n\n Vertex Index:\n %d',px,py,pz,vx,vy,vz,vi);
github
philippboehmsturm/antx-master
warning_once.m
.m
antx-master/xspm8/external/fieldtrip/plotting/private/warning_once.m
3,832
utf_8
07dc728273934663973f4c716e7a3a1c
function [ws warned] = warning_once(varargin) % % Use as one of the following % warning_once(string) % warning_once(string, timeout) % warning_once(id, string) % warning_once(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. The default timeout value is 60 seconds. % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = warning_once(...) % or as % warning_once(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, warning_once accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = warning_once(...) % 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 % warning_once('the value is %d', 10) % instead you should do % warning_once(sprintf('the value is %d', 10)) % Copyright (C) 2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: warning_once.m 7123 2012-12-06 21:21:38Z roboos $ persistent stopwatch previous if nargin < 1 error('You need to specify at least a warning message'); end warned = false; if isstruct(varargin{1}) warning(varargin{1}); return; end % 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); timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); timeout = 60; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); timeout = 60; % default timeout in seconds fname = [warningArgs{1}]; end if isempty(timeout) error('Timeout ill-specified'); end if isempty(stopwatch) stopwatch = tic; end if isempty(previous) previous = struct; end now = toc(stopwatch); % measure time since first function call fname = decomma(fixname(fname)); % make a nice string that is allowed as structure fieldname if length(fname) > 63 % MATLAB max name fname = fname(1:63); end if ~isfield(previous, fname) || ... (isfield(previous, fname) && now>previous.(fname).timeout) % warning never given before or timed out ws = warning(warningArgs{:}); previous.(fname).timeout = now+timeout; previous.(fname).ws = ws; warned = true; else % the warning has been issued before, but has not timed out yet ws = previous.(fname).ws; end end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function name = decomma(name) name(name==',')=[]; end % function
github
philippboehmsturm/antx-master
mesh2edge.m
.m
antx-master/xspm8/external/fieldtrip/plotting/private/mesh2edge.m
3,404
utf_8
cf32ba7233084e32af5fc6057ab2bba5
function [newbnd] = mesh2edge(bnd) % MESH2EDGE finds the edge lines from a triangulated mesh or the edge surfaces % from a tetrahedral or hexahedral mesh. % % Use as % [bnd] = mesh2edge(bnd) % Copyright (C) 2013, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: mesh2edge.m 7372 2013-01-23 09:15:52Z roboos $ 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, :); % the naming of the output edges depends on what they represent newbnd.pnt = bnd.pnt; if isfield(bnd, 'tri') newbnd.line = edge; elseif isfield(bnd, 'tet') newbnd.tri = edge; elseif isfield(bnd, 'hex') 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
philippboehmsturm/antx-master
intersect_plane.m
.m
antx-master/xspm8/external/fieldtrip/plotting/private/intersect_plane.m
2,894
utf_8
a79090a28892db20b0e30635228e2ac4
function [X, Y, Z, pnt1, dhk1, pnt2, dhk2] = intersect_plane(pnt, dhk, v1, v2, v3) % INTERSECT_PLANE intersection between a triangulated surface and a plane % it returns the coordinates of the vertices which form a contour % % Use as % [X, Y, Z] = intersect_plane(pnt, dhk, v1, v2, v3) % % where the intersecting plane is spanned by the vertices v1, v2, v3 % and the return values are each Nx2 for the N line segments. % Copyright (C) 2002-2012, Robert Oostenveld % % $Id: intersect_plane.m 7123 2012-12-06 21:21:38Z roboos $ npnt = size(pnt,1); ndhk = size(dhk,1); % side = zeros(npnt,1); % for i=1:npnt % side(i) = ptriside(v1, v2, v3, pnt(i,:)); % end side = ptriside(v1, v2, v3, pnt); % find the triangles which have vertices on both sides of the plane indx = find(abs(sum(side(dhk),2))~=3); cnt1 = zeros(length(indx), 3); cnt2 = zeros(length(indx), 3); for i=1:length(indx) cur = dhk(indx(i),:); tmp = side(cur); l1 = pnt(cur(1),:); l2 = pnt(cur(2),:); l3 = pnt(cur(3),:); if tmp(1)==tmp(2) % plane intersects two sides of the triangle cnt1(i,:) = ltrisect(v1, v2, v3, l3, l1); cnt2(i,:) = ltrisect(v1, v2, v3, l3, l2); elseif tmp(1)==tmp(3) cnt1(i,:) = ltrisect(v1, v2, v3, l2, l1); cnt2(i,:) = ltrisect(v1, v2, v3, l2, l3); elseif tmp(2)==tmp(3) cnt1(i,:) = ltrisect(v1, v2, v3, l1, l2); cnt2(i,:) = ltrisect(v1, v2, v3, l1, l3); elseif tmp(1)==0 && tmp(2)==0 % two vertices of the triangle lie on the plane cnt1(i,:) = l1; cnt2(i,:) = l2; elseif tmp(1)==0 && tmp(3)==0 cnt1(i,:) = l1; cnt2(i,:) = l3; elseif tmp(2)==0 && tmp(3)==0 cnt1(i,:) = l2; cnt2(i,:) = l3; elseif tmp(1)==0 && tmp(2)~=tmp(3) % one vertex of the triangle lies on the plane cnt1(i,:) = l1; cnt2(i,:) = ltrisect(v1, v2, v3, l2, l3); elseif tmp(2)==0 && tmp(3)~=tmp(1) cnt1(i,:) = l2; cnt2(i,:) = ltrisect(v1, v2, v3, l3, l1); elseif tmp(3)==0 && tmp(1)~=tmp(2) cnt1(i,:) = l3; cnt2(i,:) = ltrisect(v1, v2, v3, l1, l2); elseif tmp(1)==0 cnt1(i,:) = l1; cnt2(i,:) = l1; elseif tmp(2)==0 cnt1(i,:) = l2; cnt2(i,:) = l2; elseif tmp(3)==0 cnt1(i,:) = l3; cnt2(i,:) = l3; end end X = [cnt1(:,1) cnt2(:,1)]; Y = [cnt1(:,2) cnt2(:,2)]; Z = [cnt1(:,3) cnt2(:,3)]; if nargout>3 % also output the two meshes on either side of the plane indx1 = find(side==1); pnt1 = pnt(indx1,:); sel1 = sum(ismember(dhk, indx1), 2)==3; dhk1 = dhk(sel1,:); dhk1 = tri_reindex(dhk1); indx2 = find(side==-1); pnt2 = pnt(indx2,:); sel2 = sum(ismember(dhk, indx2), 2)==3; dhk2 = dhk(sel2,:); dhk2 = tri_reindex(dhk2); end function [newtri] = tri_reindex(tri) %this function reindexes tri such that they run from 1:number of unique vertices newtri = tri; [srt, indx] = sort(tri(:)); tmp = cumsum(double(diff([0;srt])>0)); newtri(indx) = tmp;
github
philippboehmsturm/antx-master
inside_contour.m
.m
antx-master/xspm8/external/fieldtrip/plotting/private/inside_contour.m
1,106
utf_8
37d10e5d9a05c79551aac24c328e34aa
function bool = inside_contour(pos, contour); npos = size(pos,1); ncnt = size(contour,1); x = pos(:,1); y = pos(:,2); minx = min(x); miny = min(y); maxx = max(x); maxy = max(y); bool = true(npos,1); bool(x<minx) = false; bool(y<miny) = false; bool(x>maxx) = false; bool(y>maxy) = false; % the summed angle over the contour is zero if the point is outside, and 2*pi if the point is inside the contour % leave some room for inaccurate f critval = 0.1; % the remaining points have to be investigated with more attention sel = find(bool); for i=1:length(sel) contourx = contour(:,1) - pos(sel(i),1); contoury = contour(:,2) - pos(sel(i),2); angle = atan2(contoury, contourx); % angle = unwrap(angle); angle = my_unwrap(angle); total = sum(diff(angle)); bool(sel(i)) = (abs(total)>critval); end function x = my_unwrap(x) % this is a faster implementation of the MATLAB unwrap function % with hopefully the same functionality d = diff(x); indx = find(abs(d)>pi); for i=indx(:)' if d(i)>0 x((i+1):end) = x((i+1):end) - 2*pi; else x((i+1):end) = x((i+1):end) + 2*pi; end end
github
philippboehmsturm/antx-master
ft_specest_mtmconvol.m
.m
antx-master/xspm8/external/fieldtrip/specest/ft_specest_mtmconvol.m
18,784
utf_8
72b84d395f1269a44bba64c70c978ee4
function [spectrum,ntaper,freqoi,timeoi] = ft_specest_mtmconvol(dat, time, varargin) % FT_SPECEST_MTMCONVOL performs wavelet convolution in the time domain % by multiplication in the frequency domain % % Use as % [spectrum,freqoi,timeoi] = specest_mtmconvol(dat,time,...) % where % dat = matrix of chan*sample % time = vector, containing time in seconds for each sample % spectrum = matrix of ntaper*chan*freqoi*timeoi of fourier coefficients % ntaper = vector containing the number of tapers per freqoi % freqoi = vector of frequencies in spectrum % timeoi = vector of timebins in spectrum % % Optional arguments should be specified in key-value pairs and can include: % taper = 'dpss', 'hanning' or many others, see WINDOW (default = 'dpss') % pad = number, indicating time-length of data to be padded out to in seconds % padtype = string, indicating type of padding to be used (see ft_preproc_padding, default: zero) % timeoi = vector, containing time points of interest (in seconds) % timwin = vector, containing length of time windows (in seconds) % freqoi = vector, containing frequencies (in Hz) % tapsmofrq = number, the amount of spectral smoothing through multi-tapering. Note: 4 Hz smoothing means plus-minus 4 Hz, i.e. a 8 Hz smoothing box % dimord = 'tap_chan_freq_time' (default) or 'chan_time_freqtap' for % memory efficiency % verbose = output progress to console (0 or 1, default 1) % taperopt = additional taper options to be used in the WINDOW function, see WINDOW % polyorder = number, the order of the polynomial to fitted to and removed from the data % prior to the fourier transform (default = 0 -> remove DC-component) % % See also FT_FREQANALYSIS, FT_SPECEST_MTMFFT, FT_SPECEST_TFR, FT_SPECEST_HILBERT, FT_SPECEST_WAVELET % Copyright (C) 2010, Donders Institute for Brain, Cognition and Behaviour % % $Id: ft_specest_mtmconvol.m 7123 2012-12-06 21:21:38Z roboos $ % these are for speeding up computation of tapers on subsequent calls persistent previous_argin previous_wltspctrm % get the optional input arguments taper = ft_getopt(varargin, 'taper', 'dpss'); pad = ft_getopt(varargin, 'pad'); padtype = ft_getopt(varargin, 'padtype', 'zero'); timeoi = ft_getopt(varargin, 'timeoi', 'all'); timwin = ft_getopt(varargin, 'timwin'); freqoi = ft_getopt(varargin, 'freqoi', 'all'); tapsmofrq = ft_getopt(varargin, 'tapsmofrq'); dimord = ft_getopt(varargin, 'dimord', 'tap_chan_freq_time'); fbopt = ft_getopt(varargin, 'feedback'); verbose = ft_getopt(varargin, 'verbose', true); polyorder = ft_getopt(varargin, 'polyorder', 0); tapopt = ft_getopt(varargin, 'taperopt'); if isempty(fbopt), fbopt.i = 1; fbopt.n = 1; end % throw errors for required input if isempty(tapsmofrq) && strcmp(taper, 'dpss') error('you need to specify tapsmofrq when using dpss tapers') end if isempty(timwin) error('you need to specify timwin') elseif (length(timwin) ~= length(freqoi) && ~strcmp(freqoi,'all')) error('timwin should be of equal length as freqoi') end % Set n's [nchan,ndatsample] = size(dat); % Remove polynomial fit from the data -> default is demeaning if polyorder >= 0 dat = ft_preproc_polyremoval(dat, polyorder, 1, ndatsample); end % Determine fsample and set total time-length of data fsample = 1./mean(diff(time)); dattime = ndatsample / fsample; % total time in seconds of input data % Zero padding if round(pad * fsample) < ndatsample error('the padding that you specified is shorter than the data'); end if isempty(pad) % if no padding is specified padding is equal to current data length pad = dattime; end postpad = round((pad - dattime) * fsample); endnsample = round(pad * fsample); % total number of samples of padded data endtime = pad; % total time in seconds of padded data % Set freqboi and freqoi if isnumeric(freqoi) % if input is a vector freqboi = round(freqoi ./ (fsample ./ endnsample)) + 1; % is equivalent to: round(freqoi .* endtime) + 1; freqboi = unique(freqboi); freqoi = (freqboi-1) ./ endtime; % boi - 1 because 0 Hz is included in fourier output elseif strcmp(freqoi,'all') freqboilim = round([0 fsample/2] ./ (fsample ./ endnsample)) + 1; freqboi = freqboilim(1):1:freqboilim(2); freqoi = (freqboi-1) ./ endtime; end % check for freqoi = 0 and remove it, there is no wavelet for freqoi = 0 if freqoi(1)==0 freqoi(1) = []; freqboi(1) = []; if length(timwin) == (length(freqoi) + 1) timwin(1) = []; end end nfreqboi = length(freqboi); nfreqoi = length(freqoi); % Set timeboi and timeoi offset = round(time(1)*fsample); if isnumeric(timeoi) % if input is a vector timeboi = round(timeoi .* fsample - offset) + 1; ntimeboi = length(timeboi); timeoi = round(timeoi .* fsample) ./ fsample; elseif strcmp(timeoi,'all') % if input was 'all' timeboi = 1:length(time); ntimeboi = length(timeboi); timeoi = time; end % set number of samples per time-window (timwin is in seconds) timwinsample = round(timwin .* fsample); % determine whether tapers need to be recomputed current_argin = {time, postpad, taper, timwinsample, tapsmofrq, freqoi, timeoi, tapopt}; % reasoning: if time and postpad are equal, it's the same length trial, if the rest is equal then the requested output is equal if isequal(current_argin, previous_argin) % don't recompute tapers wltspctrm = previous_wltspctrm; ntaper = cellfun(@size,wltspctrm,repmat({1},[1 nfreqoi])'); else % recompute tapers per frequency, multiply with wavelets and compute their fft wltspctrm = cell(nfreqoi,1); ntaper = zeros(nfreqoi,1); for ifreqoi = 1:nfreqoi switch taper case 'dpss' % create a sequence of DPSS tapers, ensure that the input arguments are double precision tap = double_dpss(timwinsample(ifreqoi), timwinsample(ifreqoi) .* (tapsmofrq(ifreqoi) ./ fsample))'; % remove the last taper because the last slepian taper is always messy tap = tap(1:(end-1), :); % give error/warning about number of tapers if isempty(tap) error('%.3f Hz: datalength to short for specified smoothing\ndatalength: %.3f s, smoothing: %.3f Hz, minimum smoothing: %.3f Hz',freqoi(ifreqoi), timwinsample(ifreqoi)/fsample,tapsmofrq(ifreqoi),fsample/timwinsample(ifreqoi)); elseif size(tap,1) == 1 disp([num2str(freqoi(ifreqoi)) ' Hz: WARNING: using only one taper for specified smoothing']) end case 'sine' % create and remove the last taper tap = sine_taper(timwinsample(ifreqoi), timwinsample(ifreqoi) .* (tapsmofrq(ifreqoi) ./ fsample))'; tap = tap(1:(end-1), :); case 'sine_old' % to provide compatibility with the tapers being scaled (which was default % behavior prior to 29apr2011) yet this gave different magnitude of power % when comparing with slepian multi tapers tap = sine_taper_scaled(timwinsample(ifreqoi), timwinsample(ifreqoi) .* (tapsmofrq(ifreqoi) ./ fsample))'; tap = tap(1:(end-1), :); % remove the last taper case 'alpha' tap = alpha_taper(timwinsample(ifreqoi), freqoi(ifreqoi)./ fsample)'; tap = tap./norm(tap)'; case 'hanning' tap = hanning(timwinsample(ifreqoi))'; tap = tap./norm(tap, 'fro'); otherwise % create a single taper according to the window specification as a replacement for the DPSS (Slepian) sequence if isempty(tapopt) % some windowing functions don't support nargin>1, and window.m doesn't check it tap = window(taper, timwinsample(ifreqoi))'; else tap = window(taper, timwinsample(ifreqoi),tapopt)'; end tap = tap ./ norm(tap,'fro'); % make it explicit that the frobenius norm is being used end % set number of tapers ntaper(ifreqoi) = size(tap,1); % Wavelet construction tappad = ceil(endnsample ./ 2) - floor(timwinsample(ifreqoi) ./ 2); prezero = zeros(1,tappad); postzero = zeros(1,round(endnsample) - ((tappad-1) + timwinsample(ifreqoi))-1); % phase consistency: cos must always be 1 and sin must always be centered in upgoing flank, so the centre of the wavelet (untapered) has angle = 0 anglein = (-(timwinsample(ifreqoi)-1)/2 : (timwinsample(ifreqoi)-1)/2)' .* ((2.*pi./fsample) .* freqoi(ifreqoi)); wltspctrm{ifreqoi} = complex(zeros(size(tap,1),round(endnsample))); for itap = 1:ntaper(ifreqoi) try % this try loop tries to fit the wavelet into wltspctrm, when its length is smaller than ndatsample, the rest is 'filled' with zeros because of above code % if a wavelet is longer than ndatsample, it doesn't fit and it is kept at zeros, which is translated to NaN's in the output % construct the complex wavelet coswav = horzcat(prezero, tap(itap,:) .* cos(anglein)', postzero); sinwav = horzcat(prezero, tap(itap,:) .* sin(anglein)', postzero); wavelet = complex(coswav, sinwav); % store the fft of the complex wavelet wltspctrm{ifreqoi}(itap,:) = fft(wavelet,[],2); % % debug plotting % figure('name',['taper #' num2str(itap) ' @ ' num2str(freqoi(ifreqoi)) 'Hz' ],'NumberTitle','off'); % subplot(2,1,1); % hold on; % plot(real(wavelet)); % plot(imag(wavelet),'color','r'); % legend('real','imag'); % tline = length(wavelet)/2; % if mod(tline,2)==0 % line([tline tline],[-max(abs(wavelet)) max(abs(wavelet))],'color','g','linestyle','--') % else % line([ceil(tline) ceil(tline)],[-max(abs(wavelet)) max(abs(wavelet))],'color','g','linestyle','--'); % line([floor(tline) floor(tline)],[-max(abs(wavelet)) max(abs(wavelet))],'color','g','linestyle','--'); % end; % subplot(2,1,2); % plot(angle(wavelet),'color','g'); % if mod(tline,2)==0, % line([tline tline],[-pi pi],'color','r','linestyle','--') % else % line([ceil(tline) ceil(tline)],[-pi pi],'color','r','linestyle','--') % line([floor(tline) floor(tline)],[-pi pi],'color','r','linestyle','--') % end end end end end % Switch between memory efficient representation or intuitive default representation switch dimord case 'tap_chan_freq_time' % default % compute fft, major speed increases are possible here, depending on which matlab is being used whether or not it helps, which mainly focuses on orientation of the to be fft'd matrix datspectrum = transpose(fft(transpose(ft_preproc_padding(dat, padtype, 0, postpad)))); % double explicit transpose to speedup fft spectrum = cell(max(ntaper), nfreqoi); for ifreqoi = 1:nfreqoi str = sprintf('frequency %d (%.2f Hz), %d tapers', ifreqoi,freqoi(ifreqoi),ntaper(ifreqoi)); [st, cws] = dbstack; if length(st)>1 && strcmp(st(2).name, 'ft_freqanalysis') && verbose % specest_mtmconvol has been called by ft_freqanalysis, meaning that ft_progress has been initialised ft_progress(fbopt.i./fbopt.n, ['trial %d, ',str,'\n'], fbopt.i); elseif verbose fprintf([str, '\n']); end for itap = 1:max(ntaper) % compute indices that will be used to extracted the requested fft output nsamplefreqoi = timwin(ifreqoi) .* fsample; reqtimeboiind = find((timeboi >= (nsamplefreqoi ./ 2)) & (timeboi < ndatsample - (nsamplefreqoi ./2))); reqtimeboi = timeboi(reqtimeboiind); % compute datspectrum*wavelet, if there are reqtimeboi's that have data % create a matrix of NaNs if there is no taper for this current frequency-taper-number if itap > ntaper(ifreqoi) spectrum{itap,ifreqoi} = complex(nan(nchan,ntimeboi)); else dum = fftshift(transpose(ifft(transpose(datspectrum .* repmat(wltspctrm{ifreqoi}(itap,:),[nchan 1])))),2); % double explicit transpose to speedup fft tmp = complex(nan(nchan,ntimeboi)); tmp(:,reqtimeboiind) = dum(:,reqtimeboi); tmp = tmp .* sqrt(2 ./ timwinsample(ifreqoi)); spectrum{itap,ifreqoi} = tmp; end end end spectrum = reshape(vertcat(spectrum{:}),[nchan max(ntaper) nfreqoi ntimeboi]); % collecting in a cell-array and later reshaping provides significant speedups spectrum = permute(spectrum, [2 1 3 4]); case 'chan_time_freqtap' % memory efficient representation % create tapfreqind freqtapind = cell(1,nfreqoi); tempntaper = [0; cumsum(ntaper(:))]; for ifreqoi = 1:nfreqoi freqtapind{ifreqoi} = tempntaper(ifreqoi)+1:tempntaper(ifreqoi+1); end % start fft'ing datspectrum = transpose(fft(transpose(ft_preproc_padding(dat, padtype, 0, postpad)))); % double explicit transpose to speedup fft spectrum = complex(zeros([nchan ntimeboi sum(ntaper)])); for ifreqoi = 1:nfreqoi str = sprintf('frequency %d (%.2f Hz), %d tapers', ifreqoi,freqoi(ifreqoi),ntaper(ifreqoi)); [st, cws] = dbstack; if length(st)>1 && strcmp(st(2).name, 'ft_freqanalysis') && verbose % specest_mtmconvol has been called by ft_freqanalysis, meaning that ft_progress has been initialised ft_progress(fbopt.i./fbopt.n, ['trial %d, ',str,'\n'], fbopt.i); elseif verbose fprintf([str, '\n']); end for itap = 1:ntaper(ifreqoi) % compute indices that will be used to extracted the requested fft output nsamplefreqoi = timwin(ifreqoi) .* fsample; reqtimeboiind = find((timeboi >= (nsamplefreqoi ./ 2)) & (timeboi < (ndatsample - (nsamplefreqoi ./2)))); reqtimeboi = timeboi(reqtimeboiind); % compute datspectrum*wavelet, if there are reqtimeboi's that have data dum = fftshift(transpose(ifft(transpose(datspectrum .* repmat(wltspctrm{ifreqoi}(itap,:),[nchan 1])))),2); % double explicit transpose to speedup fft tmp = complex(nan(nchan,ntimeboi),nan(nchan,ntimeboi)); tmp(:,reqtimeboiind) = dum(:,reqtimeboi); tmp = tmp .* sqrt(2 ./ timwinsample(ifreqoi)); spectrum(:,:,freqtapind{ifreqoi}(itap)) = tmp; end end % for nfreqoi end % switch dimord % remember the current input arguments, so that they can be % reused on a subsequent call in case the same input argument is given previous_argin = current_argin; previous_wltspctrm = wltspctrm; % % below code does the exact same as above, but without the trick of converting to cell-arrays for speed increases. however, when there is a huge variability in number of tapers per freqoi % % than this approach can benefit from the fact that the array can be precreated containing nans % % compute fft, major speed increases are possible here, depending on which matlab is being used whether or not it helps, which mainly focuses on orientation of the to be fft'd matrix % datspectrum = transpose(fft(transpose([dat repmat(postpad,[nchan, 1])]))); % double explicit transpose to speedup fft % spectrum = complex(nan([max(ntaper) nchan nfreqoi ntimeboi]),nan([max(ntaper) nchan nfreqoi ntimeboi])); % assumes fixed number of tapers % for ifreqoi = 1:nfreqoi % fprintf('processing frequency %d (%.2f Hz), %d tapers\n', ifreqoi,freqoi(ifreqoi),ntaper(ifreqoi)); % for itap = 1:max(ntaper) % % compute indices that will be used to extracted the requested fft output % nsamplefreqoi = timwin(ifreqoi) .* fsample; % reqtimeboiind = find((timeboi >= (nsamplefreqoi ./ 2)) & (timeboi < ndatsample - (nsamplefreqoi ./2))); % reqtimeboi = timeboi(reqtimeboiind); % % % compute datspectrum*wavelet, if there are reqtimeboi's that have data % % create a matrix of NaNs if there is no taper for this current frequency-taper-number % if itap <= ntaper(ifreqoi) % dum = fftshift(transpose(ifft(transpose(datspectrum .* repmat(wltspctrm{ifreqoi}(itap,:),[nchan 1])))),2); % double explicit transpose to speedup fft % tmp = complex(nan(nchan,ntimeboi)); % tmp(:,reqtimeboiind) = dum(:,reqtimeboi); % tmp = tmp .* sqrt(2 ./ timwinsample(ifreqoi)); % spectrum(itap,:,ifreqoi,:) = tmp; % else % break % end % end % end % Below the code used to implement variable amount of tapers in a different way, kept here for testing, please do not remove % % build tapfreq vector % tapfreq = []; % for ifreqoi = 1:nfreqoi % tapfreq = [tapfreq ones(1,ntaper(ifreqoi)) * ifreqoi]; % end % tapfreq = tapfreq(:); % % % compute fft, major speed increases are possible here, depending on which matlab is being used whether or not it helps, which mainly focuses on orientation of the to be fft'd matrix % %spectrum = complex(nan([numel(tapfreq),nchan,ntimeboi])); % datspectrum = fft([dat repmat(postpad,[nchan, 1])],[],2); % spectrum = cell(numel(tapfreq), nchan, ntimeboi); % for ifreqoi = 1:nfreqoi % fprintf('processing frequency %d (%.2f Hz), %d tapers\n', ifreqoi,freqoi(ifreqoi),ntaper(ifreqoi)); % for itap = 1:ntaper(ifreqoi) % tapfreqind = sum(ntaper(1:ifreqoi-1)) + itap; % for ichan = 1:nchan % % compute indices that will be used to extracted the requested fft output % nsamplefreqoi = timwin(ifreqoi) .* fsample; % reqtimeboiind = find((timeboi >= (nsamplefreqoi ./ 2)) & (timeboi < ndatsample - (nsamplefreqoi ./2))); % reqtimeboi = timeboi(reqtimeboiind); % % % compute datspectrum*wavelet, if there are reqtimeboi's that have data % if ~isempty(reqtimeboi) % dum = fftshift(ifft(datspectrum(ichan,:) .* wltspctrm{ifreqoi}(itap,:),[],2)); % fftshift is necessary because of post zero-padding, not necessary when pre-padding % %spectrum(tapfreqind,ichan,reqtimeboiind) = dum(reqtimeboi); % tmp = complex(nan(1,ntimeboi)); % tmp(reqtimeboiind) = dum(reqtimeboi); % spectrum{tapfreqind,ichan} = tmp; % end % end % end % end % spectrum = reshape(vertcat(spectrum{:}),[numel(tapfreq) nchan ntimeboi]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION ensure that the first two input arguments are of double % precision this prevents an instability (bug) in the computation of the % tapers for Matlab 6.5 and 7.0 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [tap] = double_dpss(a, b, varargin) tap = dpss(double(a), double(b), varargin{:});
github
philippboehmsturm/antx-master
ft_specest_mtmfft.m
.m
antx-master/xspm8/external/fieldtrip/specest/ft_specest_mtmfft.m
12,992
utf_8
9d6c9a46538d0cfc46ac075583838972
function [spectrum,ntaper,freqoi] = ft_specest_mtmfft(dat, time, varargin) % FT_SPECEST_MTMFFT computes a fast Fourier transform using multitapering with % the DPSS sequence or using a variety of single tapers % % Use as % [spectrum,freqoi] = specest_mtmfft(dat,time...) % where % dat = matrix of chan*sample % time = vector, containing time in seconds for each sample % spectrum = matrix of taper*chan*freqoi of fourier coefficients % ntaper = vector containing number of tapers per element of freqoi % freqoi = vector of frequencies in spectrum % % Optional arguments should be specified in key-value pairs and can include: % taper = 'dpss', 'hanning' or many others, see WINDOW (default = 'dpss') % pad = number, total length of data after zero padding (in seconds) % padtype = string, indicating type of padding to be used (see ft_preproc_padding, default: zero) % freqoi = vector, containing frequencies of interest % tapsmofrq = the amount of spectral smoothing through multi-tapering. Note: 4 Hz smoothing means plus-minus 4 Hz, i.e. a 8 Hz smoothing box % dimord = 'tap_chan_freq_time' (default) or 'chan_time_freqtap' for memory efficiency (only when use variable number slepian tapers) % polyorder = number, the order of the polynomial to fitted to and removed from the data % prior to the fourier transform (default = 0 -> remove DC-component) % taperopt = additional taper options to be used in the WINDOW function, see WINDOW % verbose = output progress to console (0 or 1, default 1) % % % See also FT_FREQANALYSIS, FT_SPECEST_MTMCONVOL, FT_SPECEST_TFR, FT_SPECEST_HILBERT, FT_SPECEST_WAVELET % Copyright (C) 2010, Donders Institute for Brain, Cognition and Behaviour % % $Id: ft_specest_mtmfft.m 7123 2012-12-06 21:21:38Z roboos $ % these are for speeding up computation of tapers on subsequent calls persistent previous_argin previous_tap % get the optional input arguments taper = ft_getopt(varargin, 'taper'); if isempty(taper), error('You must specify a taper'); end pad = ft_getopt(varargin, 'pad'); padtype = ft_getopt(varargin, 'padtype', 'zero'); freqoi = ft_getopt(varargin, 'freqoi', 'all'); tapsmofrq = ft_getopt(varargin, 'tapsmofrq'); dimord = ft_getopt(varargin, 'dimord', 'tap_chan_freq'); fbopt = ft_getopt(varargin, 'feedback'); verbose = ft_getopt(varargin, 'verbose', true); polyorder = ft_getopt(varargin, 'polyorder', 0); tapopt = ft_getopt(varargin, 'taperopt'); if isempty(fbopt), fbopt.i = 1; fbopt.n = 1; end % throw errors for required input if isempty(tapsmofrq) && strcmp(taper, 'dpss') error('you need to specify tapsmofrq when using dpss tapers') end % Set n's [nchan,ndatsample] = size(dat); % Remove polynomial fit from the data -> default is demeaning if polyorder >= 0 dat = ft_preproc_polyremoval(dat, polyorder, 1, ndatsample); end % Determine fsample and set total time-length of data fsample = 1./mean(diff(time)); dattime = ndatsample / fsample; % total time in seconds of input data % Zero padding if round(pad * fsample) < ndatsample error('the padding that you specified is shorter than the data'); end if isempty(pad) % if no padding is specified padding is equal to current data length pad = dattime; end postpad = ceil((pad - dattime) * fsample); endnsample = round(pad * fsample); % total number of samples of padded data endtime = pad; % total time in seconds of padded data % Set freqboi and freqoi if isnumeric(freqoi) % if input is a vector freqboi = round(freqoi ./ (fsample ./ endnsample)) + 1; % is equivalent to: round(freqoi .* endtime) + 1; freqboi = unique(freqboi); freqoi = (freqboi-1) ./ endtime; % boi - 1 because 0 Hz is included in fourier output elseif strcmp(freqoi,'all') % if input was 'all' freqboilim = round([0 fsample/2] ./ (fsample ./ endnsample)) + 1; freqboi = freqboilim(1):1:freqboilim(2); freqoi = (freqboi-1) ./ endtime; end nfreqboi = length(freqboi); nfreqoi = length(freqoi); if strcmp(taper, 'dpss') && numel(tapsmofrq)~=1 && (numel(tapsmofrq)~=nfreqoi) error('tapsmofrq needs to contain a smoothing parameter for every frequency when requesting variable number of slepian tapers') end % determine whether tapers need to be recomputed current_argin = {time, postpad, taper, tapsmofrq, freqoi, tapopt}; % reasoning: if time and postpad are equal, it's the same length trial, if the rest is equal then the requested output is equal if isequal(current_argin, previous_argin) % don't recompute tapers tap = previous_tap; else % recompute tapers switch taper case 'dpss' if numel(tapsmofrq)==1 % create a sequence of DPSS tapers, ensure that the input arguments are double precision tap = double_dpss(ndatsample,ndatsample*(tapsmofrq./fsample))'; % remove the last taper because the last slepian taper is always messy tap = tap(1:(end-1), :); % give error/warning about number of tapers if isempty(tap) error('datalength to short for specified smoothing\ndatalength: %.3f s, smoothing: %.3f Hz, minimum smoothing: %.3f Hz',ndatsample/fsample,tapsmofrq,fsample/ndatsample); elseif size(tap,1) == 1 warning_once('using only one taper for specified smoothing'); end elseif numel(tapsmofrq)>1 tap = cell(1,nfreqoi); for ifreqoi = 1:nfreqoi % create a sequence of DPSS tapers, ensure that the input arguments are double precision currtap = double_dpss(ndatsample, ndatsample .* (tapsmofrq(ifreqoi) ./ fsample))'; % remove the last taper because the last slepian taper is always messy currtap = currtap(1:(end-1), :); % give error/warning about number of tapers if isempty(currtap) error('%.3f Hz: datalength to short for specified smoothing\ndatalength: %.3f s, smoothing: %.3f Hz, minimum smoothing: %.3f Hz',freqoi(ifreqoi), ndatsample/fsample,tapsmofrq(ifreqoi),fsample/ndatsample(ifreqoi)); elseif size(currtap,1) == 1 disp([num2str(freqoi(ifreqoi)) ' Hz: WARNING: using only one taper for specified smoothing']) end tap{ifreqoi} = currtap; end end case 'sine' tap = sine_taper(ndatsample, ndatsample*(tapsmofrq./fsample))'; tap = tap(1:(end-1), :); % remove the last taper case 'sine_old' % to provide compatibility with the tapers being scaled (which was default % behavior prior to 29apr2011) yet this gave different magnitude of power % when comparing with slepian multi tapers tap = sine_taper_scaled(ndatsample, ndatsample*(tapsmofrq./fsample))'; tap = tap(1:(end-1), :); % remove the last taper case 'alpha' error('not yet implemented'); case 'hanning' tap = hanning(ndatsample)'; tap = tap./norm(tap, 'fro'); otherwise % create the taper and ensure that it is normalized if isempty(tapopt) % some windowing functions don't support nargin>1, and window.m doesn't check it tap = window(taper, ndatsample)'; else tap = window(taper, ndatsample, tapopt)'; end tap = tap ./ norm(tap,'fro'); end % switch taper end % isequal currargin % set ntaper if ~(strcmp(taper,'dpss') && numel(tapsmofrq)>1) % variable number of slepian tapers not requested ntaper = repmat(size(tap,1),nfreqoi,1); else % variable number of slepian tapers requested ntaper = cellfun(@size,tap,repmat({1},[1 nfreqoi])); end % determine phase-shift so that for all frequencies angle(t=0) = 0 timedelay = time(1); if timedelay ~= 0 angletransform = complex(zeros(1,nfreqoi)); for ifreqoi = 1:nfreqoi missedsamples = round(timedelay * fsample); % determine angle of freqoi if oscillation started at 0 % the angle of wavelet(cos,sin) = 0 at the first point of a cycle, with sine being in upgoing flank, which is the same convention as in mtmconvol anglein = (missedsamples) .* ((2.*pi./fsample) .* freqoi(ifreqoi)); coswav = cos(anglein); sinwav = sin(anglein); angletransform(ifreqoi) = angle(complex(coswav,sinwav)); end angletransform = repmat(angletransform,[nchan,1]); end % compute fft if ~(strcmp(taper,'dpss') && numel(tapsmofrq)>1) % ariable number of slepian tapers not requested str = sprintf('nfft: %d samples, datalength: %d samples, %d tapers',endnsample,ndatsample,ntaper(1)); [st, cws] = dbstack; if length(st)>1 && strcmp(st(2).name, 'ft_freqanalysis') % specest_mtmfft has been called by ft_freqanalysis, meaning that ft_progress has been initialised ft_progress(fbopt.i./fbopt.n, ['processing trial %d/%d ',str,'\n'], fbopt.i, fbopt.n); else fprintf([str, '\n']); end spectrum = cell(ntaper(1),1); for itap = 1:ntaper(1) dum = transpose(fft(transpose(ft_preproc_padding(dat .* repmat(tap(itap,:),[nchan, 1]), padtype, 0, postpad)))); % double explicit transpose to speedup fft dum = dum(:,freqboi); % phase-shift according to above angles if timedelay ~= 0 dum = dum .* exp(-1i*angletransform); end dum = dum .* sqrt(2 ./ endnsample); spectrum{itap} = dum; end spectrum = reshape(vertcat(spectrum{:}),[nchan ntaper(1) nfreqboi]);% collecting in a cell-array and later reshaping provides significant speedups spectrum = permute(spectrum, [2 1 3]); else % variable number of slepian tapers requested switch dimord case 'tap_chan_freq' % default % start fft'ing spectrum = complex(zeros([max(ntaper) nchan nfreqoi])); for ifreqoi = 1:nfreqoi str = sprintf('nfft: %d samples, datalength: %d samples, frequency %d (%.2f Hz), %d tapers',endnsample,ndatsample,ifreqoi,freqoi(ifreqoi),ntaper(ifreqoi)); [st, cws] = dbstack; if length(st)>1 && strcmp(st(2).name, 'ft_freqanalysis') && verbose % specest_mtmconvol has been called by ft_freqanalysis, meaning that ft_progress has been initialised ft_progress(fbopt.i./fbopt.n, ['processing trial %d, ',str,'\n'], fbopt.i); elseif verbose fprintf([str, '\n']); end for itap = 1:ntaper(ifreqoi) dum = transpose(fft(transpose(ft_preproc_padding(dat .* repmat(tap{ifreqoi}(itap,:),[nchan, 1]), padtype, 0, postpad)))); % double explicit transpose to speedup fft dum = dum(:,freqboi(ifreqoi)); % phase-shift according to above angles if timedelay ~= 0 dum = dum .* exp(-1i*angletransform(:,ifreqoi)); end dum = dum .* sqrt(2 ./ endnsample); currtapind = itap + ((ifreqoi-1) * max(ntaper)); spectrum(currtapind,:,ifreqoi) = dum; end end % for nfreqoi case 'chan_freqtap' % memory efficient representation % create tapfreqind freqtapind = cell(1,nfreqoi); tempntaper = [0; cumsum(ntaper(:))]; for ifreqoi = 1:nfreqoi freqtapind{ifreqoi} = tempntaper(ifreqoi)+1:tempntaper(ifreqoi+1); end % start fft'ing spectrum = complex(zeros([nchan sum(ntaper)])); for ifreqoi = 1:nfreqoi str = sprintf('nfft: %d samples, datalength: %d samples, frequency %d (%.2f Hz), %d tapers',endnsample,ndatsample,ifreqoi,freqoi(ifreqoi),ntaper(ifreqoi)); [st, cws] = dbstack; if length(st)>1 && strcmp(st(2).name, 'ft_freqanalysis') && verbose % specest_mtmconvol has been called by ft_freqanalysis, meaning that ft_progress has been initialised ft_progress(fbopt.i./fbopt.n, ['processing trial %d, ',str,'\n'], fbopt.i); elseif verbose fprintf([str, '\n']); end for itap = 1:ntaper(ifreqoi) dum = transpose(fft(transpose(ft_preproc_padding(dat .* repmat(tap{ifreqoi}(itap,:),[nchan, 1]),[nchan, 1]), padtype, 0, postpad))); % double explicit transpose to speedup fft dum = dum(:,freqboi(ifreqoi)); % phase-shift according to above angles if timedelay ~= 0 dum = dum .* exp(-1i*angletransform(:,ifreqoi)); end dum = dum .* sqrt(2 ./ endnsample); spectrum(:,freqtapind{ifreqoi}(itap)) = dum; end end % for nfreqoi end % switch dimord end % remember the current input arguments, so that they can be % reused on a subsequent call in case the same input argument is given previous_argin = current_argin; previous_tap = tap; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION ensure that the first two input arguments are of double % precision this prevents an instability (bug) in the computation of the % tapers for Matlab 6.5 and 7.0 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [tap] = double_dpss(a, b, varargin) tap = dpss(double(a), double(b), varargin{:});
github
philippboehmsturm/antx-master
postpad.m
.m
antx-master/xspm8/external/fieldtrip/specest/private/postpad.m
2,013
utf_8
2c9539d77ff0f85c9f89108f4dc811e0
% Copyright (C) 1994, 1995, 1996, 1997, 1998, 2000, 2002, 2004, 2005, % 2006, 2007, 2008, 2009 John W. Eaton % % This file is part of Octave. % % Octave is free software; you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 3 of the License, or (at % your option) any later version. % % Octave is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % % You should have received a copy of the GNU General Public License % along with Octave; see the file COPYING. If not, see % <http://www.gnu.org/licenses/>. % -*- texinfo -*- % @deftypefn {Function File} {} postpad (@var{x}, @var{l}, @var{c}) % @deftypefnx {Function File} {} postpad (@var{x}, @var{l}, @var{c}, @var{dim}) % @seealso{prepad, resize} % @end deftypefn % Author: Tony Richardson <[email protected]> % Created: June 1994 function y = postpad (x, l, c, dim) if nargin < 2 || nargin > 4 %print_usage (); error('wrong number of input arguments, should be between 2 and 4'); end if nargin < 3 || isempty(c) c = 0; else if ~isscalar(c) error ('postpad: third argument must be empty or a scalar'); end end nd = ndims(x); sz = size(x); if nargin < 4 % Find the first non-singleton dimension dim = 1; while dim < nd+1 && sz(dim)==1 dim = dim + 1; end if dim > nd dim = 1; elseif ~(isscalar(dim) && dim == round(dim)) && dim > 0 && dim< nd+1 error('postpad: dim must be an integer and valid dimension'); end end if ~isscalar(l) || l<0 error ('second argument must be a positive scalar'); end if dim > nd sz(nd+1:dim) = 1; end d = sz(dim); if d >= l idx = cell(1,nd); for i = 1:nd idx{i} = 1:sz(i); end idx{dim} = 1:l; y = x(idx{:}); else sz(dim) = l-d; y = cat(dim, x, c * ones(sz)); end
github
philippboehmsturm/antx-master
sftrans.m
.m
antx-master/xspm8/external/fieldtrip/specest/private/sftrans.m
7,947
utf_8
f64cb2e7d19bcdc6232b39d8a6d70e7c
% Copyright (C) 1999 Paul Kienzle % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop) % % Transform band edges of a generic lowpass filter (cutoff at W=1) % represented in splane zero-pole-gain form. W is the edge of the % target filter (or edges if band pass or band stop). Stop is true for % high pass and band stop filters or false for low pass and band pass % filters. Filter edges are specified in radians, from 0 to pi (the % nyquist frequency). % % Theory: Given a low pass filter represented by poles and zeros in the % splane, you can convert it to a low pass, high pass, band pass or % band stop by transforming each of the poles and zeros individually. % The following table summarizes the transformation: % % Transform Zero at x Pole at x % ---------------- ------------------------- ------------------------ % Low Pass zero: Fc x/C pole: Fc x/C % S -> C S/Fc gain: C/Fc gain: Fc/C % ---------------- ------------------------- ------------------------ % High Pass zero: Fc C/x pole: Fc C/x % S -> C Fc/S pole: 0 zero: 0 % gain: -x gain: -1/x % ---------------- ------------------------- ------------------------ % Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S^2+FhFl pole: 0 zero: 0 % S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C % S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ % Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl) % S -> C -------- gain: -x gain: -1/x % S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ % Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT) % 2 z-1 pole: -1 zero: -1 % S -> - --- gain: (2-xT)/T gain: (2-xT)/T % T z+1 % ---------------- ------------------------- ------------------------ % % where C is the cutoff frequency of the initial lowpass filter, Fc is % the edge of the target low/high pass filter and [Fl,Fh] are the edges % of the target band pass/stop filter. With abundant tedious algebra, % you can derive the above formulae yourself by substituting the % transform for S into H(S)=S-x for a zero at x or H(S)=1/(S-x) for a % pole at x, and converting the result into the form: % % H(S)=g prod(S-Xi)/prod(S-Xj) % % The transforms are from the references. The actual pole-zero-gain % changes I derived myself. % % Please note that a pole and a zero at the same place exactly cancel. % This is significant for High Pass, Band Pass and Band Stop filters % which create numerous extra poles and zeros, most of which cancel. % Those which do not cancel have a 'fill-in' effect, extending the % shorter of the sets to have the same number of as the longer of the % sets of poles and zeros (or at least split the difference in the case % of the band pass filter). There may be other opportunistic % cancellations but I will not check for them. % % Also note that any pole on the unit circle or beyond will result in % an unstable filter. Because of cancellation, this will only happen % if the number of poles is smaller than the number of zeros and the % filter is high pass or band pass. The analytic design methods all % yield more poles than zeros, so this will not be a problem. % % References: % % Proakis & Manolakis (1992). Digital Signal Processing. New York: % Macmillan Publishing Company. % Author: Paul Kienzle <[email protected]> % 2000-03-01 [email protected] % leave transformed Sg as a complex value since cheby2 blows up % otherwise (but only for odd-order low-pass filters). bilinear % will return Zg as real, so there is no visible change to the % user of the IIR filter design functions. % 2001-03-09 [email protected] % return real Sg; don't know what to do for imaginary filters function [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop) if (nargin ~= 5) usage('[Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)'); end; C = 1; p = length(Sp); z = length(Sz); if z > p || p == 0 error('sftrans: must have at least as many poles as zeros in s-plane'); end if length(W)==2 Fl = W(1); Fh = W(2); if stop % ---------------- ------------------------- ------------------------ % Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl) % S -> C -------- gain: -x gain: -1/x % S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ if (isempty(Sz)) Sg = Sg * real (1./ prod(-Sp)); elseif (isempty(Sp)) Sg = Sg * real(prod(-Sz)); else Sg = Sg * real(prod(-Sz)/prod(-Sp)); end b = (C*(Fh-Fl)/2)./Sp; Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; extend = [sqrt(-Fh*Fl), -sqrt(-Fh*Fl)]; if isempty(Sz) Sz = [extend(1+rem([1:2*p],2))]; else b = (C*(Fh-Fl)/2)./Sz; Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; if (p > z) Sz = [Sz, extend(1+rem([1:2*(p-z)],2))]; end end else % ---------------- ------------------------- ------------------------ % Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S^2+FhFl pole: 0 zero: 0 % S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C % S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ Sg = Sg * (C/(Fh-Fl))^(z-p); b = Sp*((Fh-Fl)/(2*C)); Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; if isempty(Sz) Sz = zeros(1,p); else b = Sz*((Fh-Fl)/(2*C)); Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; if (p>z) Sz = [Sz, zeros(1, (p-z))]; end end end else Fc = W; if stop % ---------------- ------------------------- ------------------------ % High Pass zero: Fc C/x pole: Fc C/x % S -> C Fc/S pole: 0 zero: 0 % gain: -x gain: -1/x % ---------------- ------------------------- ------------------------ if (isempty(Sz)) Sg = Sg * real (1./ prod(-Sp)); elseif (isempty(Sp)) Sg = Sg * real(prod(-Sz)); else Sg = Sg * real(prod(-Sz)/prod(-Sp)); end Sp = C * Fc ./ Sp; if isempty(Sz) Sz = zeros(1,p); else Sz = [C * Fc ./ Sz]; if (p > z) Sz = [Sz, zeros(1,p-z)]; end end else % ---------------- ------------------------- ------------------------ % Low Pass zero: Fc x/C pole: Fc x/C % S -> C S/Fc gain: C/Fc gain: Fc/C % ---------------- ------------------------- ------------------------ Sg = Sg * (C/Fc)^(z-p); Sp = Fc * Sp / C; Sz = Fc * Sz / C; end end
github
philippboehmsturm/antx-master
hanning.m
.m
antx-master/xspm8/external/fieldtrip/specest/private/hanning.m
2,015
utf_8
2dfc746c8c862dc8fe272cae2a733f20
function [tap] = hanning(n, str) %HANNING Hanning window. % HANNING(N) returns the N-point symmetric Hanning window in a column % vector. Note that the first and last zero-weighted window samples % are not included. % % HANNING(N,'symmetric') returns the same result as HANNING(N). % % HANNING(N,'periodic') returns the N-point periodic Hanning window, % and includes the first zero-weighted window sample. % % NOTE: Use the HANN function to get a Hanning window which has the % first and last zero-weighted samples. % % See also BARTLETT, BLACKMAN, BOXCAR, CHEBWIN, HAMMING, HANN, KAISER % and TRIANG. % % This is a drop-in replacement to bypass the signal processing toolbox % Copyright (c) 2010, Jan-Mathijs Schoffelen, DCCN Nijmegen % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: hanning.m 7123 2012-12-06 21:21:38Z roboos $ if nargin==1, str = 'symmetric'; end switch str, case 'periodic' % Includes the first zero sample tap = [0; hanningX(n-1)]; case 'symmetric' % Does not include the first and last zero sample tap = hanningX(n); end function tap = hanningX(n) % compute taper N = n+1; tap = 0.5*(1-cos((2*pi*(1:n))./N))'; % make symmetric halfn = floor(n/2); tap( (n+1-halfn):n ) = flipud(tap(1:halfn));
github
philippboehmsturm/antx-master
filtfilt.m
.m
antx-master/xspm8/external/fieldtrip/specest/private/filtfilt.m
3,297
iso_8859_1
d01a26a827bc3379f05bbc57f46ac0a9
% Copyright (C) 1999 Paul Kienzle % Copyright (C) 2007 Francesco Potortì % Copyright (C) 2008 Luca Citi % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: y = filtfilt(b, a, x) % % Forward and reverse filter the signal. This corrects for phase % distortion introduced by a one-pass filter, though it does square the % magnitude response in the process. That's the theory at least. In % practice the phase correction is not perfect, and magnitude response % is distorted, particularly in the stop band. %% % Example % [b, a]=butter(3, 0.1); % 10 Hz low-pass filter % t = 0:0.01:1.0; % 1 second sample % x=sin(2*pi*t*2.3)+0.25*randn(size(t)); % 2.3 Hz sinusoid+noise % y = filtfilt(b,a,x); z = filter(b,a,x); % apply filter % plot(t,x,';data;',t,y,';filtfilt;',t,z,';filter;') % Changelog: % 2000 02 [email protected] % - pad with zeros to load up the state vector on filter reverse. % - add example % 2007 12 [email protected] % - use filtic to compute initial and final states % - work for multiple columns as well % 2008 12 [email protected] % - fixed instability issues with IIR filters and noisy inputs % - initial states computed according to Likhterov & Kopeika, 2003 % - use of a "reflection method" to reduce end effects % - added some basic tests % TODO: (pkienzle) My version seems to have similar quality to matlab, % but both are pretty bad. They do remove gross lag errors, though. function y = filtfilt(b, a, x) if (nargin ~= 3) usage('y=filtfilt(b,a,x)'); end rotate = (size(x, 1)==1); if rotate % a row vector x = x(:); % make it a column vector end lx = size(x,1); a = a(:).'; b = b(:).'; lb = length(b); la = length(a); n = max(lb, la); lrefl = 3 * (n - 1); if la < n, a(n) = 0; end if lb < n, b(n) = 0; end % Compute a the initial state taking inspiration from % Likhterov & Kopeika, 2003. "Hardware-efficient technique for % minimizing startup transients in Direct Form II digital filters" kdc = sum(b) / sum(a); if (abs(kdc) < inf) % neither NaN nor +/- Inf si = fliplr(cumsum(fliplr(b - kdc * a))); else si = zeros(size(a)); % fall back to zero initialization end si(1) = []; y = zeros(size(x)); for c = 1:size(x, 2) % filter all columns, one by one v = [2*x(1,c)-x((lrefl+1):-1:2,c); x(:,c); 2*x(end,c)-x((end-1):-1:end-lrefl,c)]; % a column vector % Do forward and reverse filtering v = filter(b,a,v,si*v(1)); % forward filter v = flipud(filter(b,a,flipud(v),si*v(end))); % reverse filter y(:,c) = v((lrefl+1):(lx+lrefl)); end if (rotate) % x was a row vector y = rot90(y); % rotate it back end
github
philippboehmsturm/antx-master
bilinear.m
.m
antx-master/xspm8/external/fieldtrip/specest/private/bilinear.m
4,339
utf_8
17250db27826cad87fa3384823e1242f
% Copyright (C) 1999 Paul Kienzle % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T) % [Zb, Za] = bilinear(Sb, Sa, T) % % Transform a s-plane filter specification into a z-plane % specification. Filters can be specified in either zero-pole-gain or % transfer function form. The input form does not have to match the % output form. 1/T is the sampling frequency represented in the z plane. % % Note: this differs from the bilinear function in the signal processing % toolbox, which uses 1/T rather than T. % % Theory: Given a piecewise flat filter design, you can transform it % from the s-plane to the z-plane while maintaining the band edges by % means of the bilinear transform. This maps the left hand side of the % s-plane into the interior of the unit circle. The mapping is highly % non-linear, so you must design your filter with band edges in the % s-plane positioned at 2/T tan(w*T/2) so that they will be positioned % at w after the bilinear transform is complete. % % The following table summarizes the transformation: % % +---------------+-----------------------+----------------------+ % | Transform | Zero at x | Pole at x | % | H(S) | H(S) = S-x | H(S)=1/(S-x) | % +---------------+-----------------------+----------------------+ % | 2 z-1 | zero: (2+xT)/(2-xT) | zero: -1 | % | S -> - --- | pole: -1 | pole: (2+xT)/(2-xT) | % | T z+1 | gain: (2-xT)/T | gain: (2-xT)/T | % +---------------+-----------------------+----------------------+ % % With tedious algebra, you can derive the above formulae yourself by % substituting the transform for S into H(S)=S-x for a zero at x or % H(S)=1/(S-x) for a pole at x, and converting the result into the % form: % % H(Z)=g prod(Z-Xi)/prod(Z-Xj) % % Please note that a pole and a zero at the same place exactly cancel. % This is significant since the bilinear transform creates numerous % extra poles and zeros, most of which cancel. Those which do not % cancel have a 'fill-in' effect, extending the shorter of the sets to % have the same number of as the longer of the sets of poles and zeros % (or at least split the difference in the case of the band pass % filter). There may be other opportunistic cancellations but I will % not check for them. % % Also note that any pole on the unit circle or beyond will result in % an unstable filter. Because of cancellation, this will only happen % if the number of poles is smaller than the number of zeros. The % analytic design methods all yield more poles than zeros, so this will % not be a problem. % % References: % % Proakis & Manolakis (1992). Digital Signal Processing. New York: % Macmillan Publishing Company. % Author: Paul Kienzle <[email protected]> function [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T) if nargin==3 T = Sg; [Sz, Sp, Sg] = tf2zp(Sz, Sp); elseif nargin~=4 usage('[Zz, Zp, Zg]=bilinear(Sz,Sp,Sg,T) or [Zb, Za]=blinear(Sb,Sa,T)'); end; p = length(Sp); z = length(Sz); if z > p || p==0 error('bilinear: must have at least as many poles as zeros in s-plane'); end % ---------------- ------------------------- ------------------------ % Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT) % 2 z-1 pole: -1 zero: -1 % S -> - --- gain: (2-xT)/T gain: (2-xT)/T % T z+1 % ---------------- ------------------------- ------------------------ Zg = real(Sg * prod((2-Sz*T)/T) / prod((2-Sp*T)/T)); Zp = (2+Sp*T)./(2-Sp*T); if isempty(Sz) Zz = -ones(size(Zp)); else Zz = [(2+Sz*T)./(2-Sz*T)]; Zz = postpad(Zz, p, -1); end if nargout==2, [Zz, Zp] = zp2tf(Zz, Zp, Zg); end
github
philippboehmsturm/antx-master
warning_once.m
.m
antx-master/xspm8/external/fieldtrip/specest/private/warning_once.m
3,832
utf_8
07dc728273934663973f4c716e7a3a1c
function [ws warned] = warning_once(varargin) % % Use as one of the following % warning_once(string) % warning_once(string, timeout) % warning_once(id, string) % warning_once(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. The default timeout value is 60 seconds. % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = warning_once(...) % or as % warning_once(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, warning_once accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = warning_once(...) % 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 % warning_once('the value is %d', 10) % instead you should do % warning_once(sprintf('the value is %d', 10)) % Copyright (C) 2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: warning_once.m 7123 2012-12-06 21:21:38Z roboos $ persistent stopwatch previous if nargin < 1 error('You need to specify at least a warning message'); end warned = false; if isstruct(varargin{1}) warning(varargin{1}); return; end % 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); timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); timeout = 60; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); timeout = 60; % default timeout in seconds fname = [warningArgs{1}]; end if isempty(timeout) error('Timeout ill-specified'); end if isempty(stopwatch) stopwatch = tic; end if isempty(previous) previous = struct; end now = toc(stopwatch); % measure time since first function call fname = decomma(fixname(fname)); % make a nice string that is allowed as structure fieldname if length(fname) > 63 % MATLAB max name fname = fname(1:63); end if ~isfield(previous, fname) || ... (isfield(previous, fname) && now>previous.(fname).timeout) % warning never given before or timed out ws = warning(warningArgs{:}); previous.(fname).timeout = now+timeout; previous.(fname).ws = ws; warned = true; else % the warning has been issued before, but has not timed out yet ws = previous.(fname).ws; end end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function name = decomma(name) name(name==',')=[]; end % function
github
philippboehmsturm/antx-master
butter.m
.m
antx-master/xspm8/external/fieldtrip/specest/private/butter.m
3,559
utf_8
ad82b4c04911a5ea11fd6bd2cc5fd590
% Copyright (C) 1999 Paul Kienzle % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % Generate a butterworth filter. % Default is a discrete space (Z) filter. % % [b,a] = butter(n, Wc) % low pass filter with cutoff pi*Wc radians % % [b,a] = butter(n, Wc, 'high') % high pass filter with cutoff pi*Wc radians % % [b,a] = butter(n, [Wl, Wh]) % band pass filter with edges pi*Wl and pi*Wh radians % % [b,a] = butter(n, [Wl, Wh], 'stop') % band reject filter with edges pi*Wl and pi*Wh radians % % [z,p,g] = butter(...) % return filter as zero-pole-gain rather than coefficients of the % numerator and denominator polynomials. % % [...] = butter(...,'s') % return a Laplace space filter, W can be larger than 1. % % [a,b,c,d] = butter(...) % return state-space matrices % % References: % % Proakis & Manolakis (1992). Digital Signal Processing. New York: % Macmillan Publishing Company. % Author: Paul Kienzle <[email protected]> % Modified by: Doug Stewart <[email protected]> Feb, 2003 function [a, b, c, d] = butter (n, W, varargin) if (nargin>4 || nargin<2) || (nargout>4 || nargout<2) usage ('[b, a] or [z, p, g] or [a,b,c,d] = butter (n, W [, "ftype"][,"s"])'); end % interpret the input parameters if (~(length(n)==1 && n == round(n) && n > 0)) error ('butter: filter order n must be a positive integer'); end stop = 0; digital = 1; for i=1:length(varargin) switch varargin{i} case 's', digital = 0; case 'z', digital = 1; case { 'high', 'stop' }, stop = 1; case { 'low', 'pass' }, stop = 0; otherwise, error ('butter: expected [high|stop] or [s|z]'); end end [r, c]=size(W); if (~(length(W)<=2 && (r==1 || c==1))) error ('butter: frequency must be given as w0 or [w0, w1]'); elseif (~(length(W)==1 || length(W) == 2)) error ('butter: only one filter band allowed'); elseif (length(W)==2 && ~(W(1) < W(2))) error ('butter: first band edge must be smaller than second'); end if ( digital && ~all(W >= 0 & W <= 1)) error ('butter: critical frequencies must be in (0 1)'); elseif ( ~digital && ~all(W >= 0 )) error ('butter: critical frequencies must be in (0 inf)'); end % Prewarp to the band edges to s plane if digital T = 2; % sampling frequency of 2 Hz W = 2/T*tan(pi*W/T); end % Generate splane poles for the prototype butterworth filter % source: Kuc C = 1; % default cutoff frequency pole = C*exp(1i*pi*(2*[1:n] + n - 1)/(2*n)); if mod(n,2) == 1, pole((n+1)/2) = -1; end % pure real value at exp(i*pi) zero = []; gain = C^n; % splane frequency transform [zero, pole, gain] = sftrans(zero, pole, gain, W, stop); % Use bilinear transform to convert poles to the z plane if digital [zero, pole, gain] = bilinear(zero, pole, gain, T); end % convert to the correct output form if nargout==2, a = real(gain*poly(zero)); b = real(poly(pole)); elseif nargout==3, a = zero; b = pole; c = gain; else % output ss results [a, b, c, d] = zp2ss (zero, pole, gain); end
github
philippboehmsturm/antx-master
avw_hdr_make.m
.m
antx-master/xspm8/external/fieldtrip/private/avw_hdr_make.m
4,182
utf_8
df97baf07b917c62db1cde33abfc8416
function [ avw ] = avw_hdr_make % AVW_HDR_MAKE - Create Analyze format data header (avw.hdr) % % [ avw ] = avw_hdr_make % % avw.hdr - a struct, all fields returned from the header. % For details, find a good description on the web % or see the Analyze File Format pdf in the % mri_toolbox doc folder or see avw_hdr_read.m % % See also, AVW_HDR_READ AVW_HDR_WRITE % AVW_IMG_READ AVW_IMG_WRITE % % $Revision: 7123 $ $Date: 2009/01/14 09:24:45 $ % Licence: GNU GPL, no express or implied warranties % History: 06/2002, [email protected] % 02/2003, [email protected] % date/time bug at lines 97-98 % identified by [email protected] % % The Analyze format is copyright % (c) Copyright, 1986-1995 % Biomedical Imaging Resource, Mayo Foundation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% version = '[$Revision: 7123 $]'; fprintf('\nAVW_HDR_MAKE [v%s]\n',version(12:16)); tic; % Comments % The header format is flexible and can be extended for new % user-defined data types. The essential structures of the header % are the header_key and the image_dimension. See avw_hdr_read % for more detail of the header structure avw.hdr = make_header; t=toc; fprintf('...done (%5.2f sec).\n',t); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ hdr ] = make_header hdr.hk = header_key; hdr.dime = image_dimension; hdr.hist = data_history; return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [hk] = header_key hk.sizeof_hdr = int32(348); % must be 348! hk.data_type(1:10) = sprintf('%10s',''); hk.db_name(1:18) = sprintf('%18s',''); hk.extents = int32(16384); hk.session_error = int16(0); hk.regular = sprintf('%1s','r'); % might be uint8 hk.hkey_un0 = uint8(0); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ dime ] = image_dimension dime.dim(1:8) = int16([4 256 256 256 1 0 0 0]); dime.vox_units(1:4) = sprintf('%4s','mm'); dime.cal_units(1:8) = sprintf('%8s',''); dime.unused1 = int16(0); dime.datatype = int16(2); dime.bitpix = int16(8); dime.dim_un0 = int16(0); dime.pixdim(1:8) = single([0 1 1 1 1000 0 0 0]); dime.vox_offset = single(0); dime.funused1 = single(0); dime.funused2 = single(0); % Set default 8bit intensity scale (from MRIcro), otherwise funused3 dime.roi_scale = single(1); dime.cal_max = single(0); dime.cal_min = single(0); dime.compressed = int32(0); dime.verified = int32(0); dime.glmax = int32(255); dime.glmin = int32(0); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ hist ] = data_history datime = clock; hist.descrip(1:80) = sprintf('%-80s','mri_toolbox @ http://eeg.sf.net/'); hist.aux_file(1:24) = sprintf('%-24s',''); hist.orient = uint8(0); % sprintf( '%1s',''); % see notes in avw_hdr_read hist.originator(1:10) = sprintf('%-10s',''); hist.generated(1:10) = sprintf('%-10s','mri_toolbx'); hist.scannum(1:10) = sprintf('%-10s',''); hist.patient_id(1:10) = sprintf('%-10s',''); hist.exp_date(1:10) = sprintf('%02d-%02d-%04d',datime(3),datime(2),datime(1)); hist.exp_time(1:10) = sprintf('%02d-%02d-%04.1f',datime(4),datime(5),datime(6)); hist.hist_un0(1:3) = sprintf( '%-3s',''); hist.views = int32(0); hist.vols_added = int32(0); hist.start_field = int32(0); hist.field_skip = int32(0); hist.omax = int32(0); hist.omin = int32(0); hist.smax = int32(0); hist.smin = int32(0); return
github
philippboehmsturm/antx-master
prepare_mesh_headshape.m
.m
antx-master/xspm8/external/fieldtrip/private/prepare_mesh_headshape.m
9,151
utf_8
390bfd19f99b4c31bf0dda1ebd8c6c37
function bnd = prepare_mesh_headshape(cfg) % PREPARE_MESH_HEADSHAPE % % See also PREPARE_MESH_MANUAL, PREPARE_MESH_SEGMENTATION % Copyrights (C) 2009, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: prepare_mesh_headshape.m 7381 2013-01-23 13:08:59Z johzum $ % get the surface describing the head shape if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt') % use the headshape surface specified in the configuration headshape = cfg.headshape; elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3 % use the headshape points specified in the configuration headshape.pnt = cfg.headshape; elseif ischar(cfg.headshape) % read the headshape from file headshape = ft_read_headshape(cfg.headshape); else error('cfg.headshape is not specified correctly') end % usually a headshape only describes a single surface boundaries, but there are cases % that multiple surfaces are included, e.g. skin_surface, outer_skull_surface, inner_skull_surface nbnd = numel(headshape); if ~isfield(headshape, 'tri') % generate a closed triangulation from the surface points for i=1:nbnd headshape(i).pnt = unique(headshape(i).pnt, 'rows'); headshape(i).tri = projecttri(headshape(i).pnt); end end if ~isempty(cfg.numvertices) && ~strcmp(cfg.numvertices, 'same') for i=1:nbnd tri1 = headshape(i).tri; pnt1 = headshape(i).pnt; % The number of vertices is multiplied by 3 in order to have more % points on the original mesh than on the sphere mesh (see below). % The rationale for this is that every projection point on the sphere % has three corresponding points on the mesh if (cfg.numvertices>size(pnt1,1)) [tri1, pnt1] = refinepatch(headshape(i).tri, headshape(i).pnt, 3*cfg.numvertices); else [tri1, pnt1] = reducepatch(headshape(i).tri, headshape(i).pnt, 3*cfg.numvertices); end % remove double vertices [pnt1, tri1] = remove_double_vertices(pnt1, tri1); % replace the probably unevenly distributed triangulation with a regular one % and retriangulate it to the desired accuracy [pnt2, tri2] = mysphere(cfg.numvertices); % this is a regular triangulation [pnt1, tri1] = retriangulate(pnt1, tri1, pnt2, tri2, 2); [pnt1, tri1] = fairsurface(pnt1, tri1, 1);% this helps redistribute the superimposed points % remove double vertices [headshape(i).pnt,headshape(i).tri] = remove_double_vertices(pnt1, tri1); fprintf('returning %d vertices, %d triangles\n', size(headshape(i).pnt,1), size(headshape(i).tri,1)); end end % the output should only describe one or multiple boundaries and should not % include any other fields bnd = rmfield(headshape, setdiff(fieldnames(headshape), {'pnt', 'tri'})); function [tri1, pnt1] = refinepatch(tri, pnt, numvertices) fprintf('the original mesh has %d vertices against the %d requested\n',size(pnt,1),numvertices/3); fprintf('trying to refine the compartment...\n'); [pnt1, tri1] = refine(pnt, tri, 'updown', numvertices); function [pnt, tri] = mysphere(N) % This is a copy of MSPHERE without the confusing output message % Returns a triangulated sphere with approximately M vertices % that are nicely distributed over the sphere. The vertices are aligned % along equally spaced horizontal contours according to an algorithm of % Dave Russel. % % Use as % [pnt, tri] = msphere(M) % % See also SPHERE, NSPHERE, ICOSAHEDRON, REFINE % Copyright (C) 1994, Dave Rusin storeM = []; storelen = []; increaseM = 0; while (1) % put a single vertex at the top phi = [0]; th = [0]; M = round((pi/4)*sqrt(N)) + increaseM; for k=1:M newphi = (k/M)*pi; Q = round(2*M*sin(newphi)); for j=1:Q phi(end+1) = newphi; th(end+1) = (j/Q)*2*pi; % in case of even number of contours if mod(M,2) & k>(M/2) th(end) = th(end) + pi/Q; end end end % put a single vertex at the bottom phi(end+1) = [pi]; th(end+1) = [0]; % store this vertex packing storeM(end+1).th = th; storeM(end ).phi = phi; storelen(end+1) = length(phi); if storelen(end)>N break; else increaseM = increaseM+1; % fprintf('increasing M by %d\n', increaseM); end end % take the vertex packing that most closely matches the requirement [m, i] = min(abs(storelen-N)); th = storeM(i).th; phi = storeM(i).phi; % convert from spherical to cartehsian coordinates [x, y, z] = sph2cart(th, pi/2-phi, 1); pnt = [x' y' z']; tri = convhulln(pnt); function [pntR, triR] = remove_double_vertices(pnt, tri) % REMOVE_VERTICES removes specified vertices from a triangular mesh % renumbering the vertex-indices for the triangles and removing all % triangles with one of the specified vertices. % % Use as % [pnt, tri] = remove_double_vertices(pnt, tri) pnt1 = unique(pnt, 'rows'); keeppnt = find(ismember(pnt1,pnt,'rows')); removepnt = setdiff([1:size(pnt,1)],keeppnt); npnt = size(pnt,1); ntri = size(tri,1); if all(removepnt==0 | removepnt==1) removepnt = find(removepnt); end % remove the vertices and determine the new numbering (indices) in numb keeppnt = setdiff(1:npnt, removepnt); numb = zeros(1,npnt); numb(keeppnt) = 1:length(keeppnt); % look for triangles referring to removed vertices removetri = false(ntri,1); removetri(ismember(tri(:,1), removepnt)) = true; removetri(ismember(tri(:,2), removepnt)) = true; removetri(ismember(tri(:,3), removepnt)) = true; % remove the vertices and triangles pntR = pnt(keeppnt, :); triR = tri(~removetri,:); % renumber the vertex indices for the triangles triR = numb(triR); function [pnt1, tri1] = fairsurface(pnt, tri, N) % FAIRSURFACE modify the mesh in order to reduce overlong edges, and % smooth out "rough" areas. This is a non-shrinking smoothing algorithm. % The procedure uses an elastic model : At each vertex, the neighbouring % triangles and vertices connected directly are used. Each edge is % considered elastic and can be lengthened or shortened, depending % on their length. Displacement are done in 3D, so that holes and % bumps are attenuated. % % Use as % [pnt, tri] = fairsurface(pnt, tri, N); % where N is the number of smoothing iterations. % % This implements: % G.Taubin, A signal processing approach to fair surface design, 1995 % This function corresponds to spm_eeg_inv_ElastM % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Christophe Phillips & Jeremie Mattout % spm_eeg_inv_ElastM.m 1437 2008-04-17 10:34:39Z christophe % % $Id: prepare_mesh_headshape.m 7381 2013-01-23 13:08:59Z johzum $ ts = []; ts.XYZmm = pnt'; ts.tri = tri'; ts.nr(1) = size(pnt,1); ts.nr(2) = size(tri,1); % Connection vertex-to-vertex %-------------------------------------------------------------------------- M_con = sparse([ts.tri(1,:)';ts.tri(1,:)';ts.tri(2,:)';ts.tri(3,:)';ts.tri(2,:)';ts.tri(3,:)'], ... [ts.tri(2,:)';ts.tri(3,:)';ts.tri(1,:)';ts.tri(1,:)';ts.tri(3,:)';ts.tri(2,:)'], ... ones(ts.nr(2)*6,1),ts.nr(1),ts.nr(1)); kpb = .1; % Cutt-off frequency lam = .5; mu = lam/(lam*kpb-1); % Parameters for elasticity. XYZmm = ts.XYZmm; % smoothing iterations %-------------------------------------------------------------------------- for j=1:N XYZmm_o = zeros(3,ts.nr(1)) ; XYZmm_o2 = zeros(3,ts.nr(1)) ; for i=1:ts.nr(1) ln = find(M_con(:,i)); d_i = sqrt(sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).^2)); if sum(d_i)==0 w_i = zeros(size(d_i)); else w_i = d_i/sum(d_i); end XYZmm_o(:,i) = XYZmm(:,i) + ... lam * sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).*(ones(3,1)*w_i),2); end for i=1:ts.nr(1) ln = find(M_con(:,i)); d_i = sqrt(sum((XYZmm(:,ln)-XYZmm(:,i)*ones(1,length(ln))).^2)); if sum(d_i)==0 w_i = zeros(size(d_i)); else w_i = d_i/sum(d_i); end XYZmm_o2(:,i) = XYZmm_o(:,i) + ... mu * sum((XYZmm_o(:,ln)-XYZmm_o(:,i)*ones(1,length(ln))).*(ones(3,1)*w_i),2); end XYZmm = XYZmm_o2; end % collect output results %-------------------------------------------------------------------------- pnt1 = XYZmm'; tri1 = tri; if 0 % this is some test/demo code bnd = []; [bnd.pnt, bnd.tri] = icosahedron162; scale = 1+0.3*randn(size(pnt,1),1); bnd.pnt = bnd.pnt .* [scale scale scale]; figure ft_plot_mesh(bnd) [bnd.pnt, bnd.tri] = fairsurface(bnd.pnt, bnd.tri, 10); figure ft_plot_mesh(bnd) end
github
philippboehmsturm/antx-master
normals.m
.m
antx-master/xspm8/external/fieldtrip/private/normals.m
2,582
utf_8
c474f14b83010d46459376013fa6e047
function [nrm] = normals(pnt, dhk, opt); % NORMALS compute the surface normals of a triangular mesh % for each triangle or for each vertex % % [nrm] = normals(pnt, dhk, opt) % where opt is either 'vertex' or 'triangle' % Copyright (C) 2002-2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: normals.m 7123 2012-12-06 21:21:38Z roboos $ if nargin<3 opt='vertex'; elseif (opt(1)=='v' | opt(1)=='V') opt='vertex'; elseif (opt(1)=='t' | opt(1)=='T') opt='triangle'; else error('invalid optional argument'); end npnt = size(pnt,1); ndhk = size(dhk,1); % shift to center pnt(:,1) = pnt(:,1)-mean(pnt(:,1),1); pnt(:,2) = pnt(:,2)-mean(pnt(:,2),1); pnt(:,3) = pnt(:,3)-mean(pnt(:,3),1); % compute triangle normals % nrm_dhk = zeros(ndhk, 3); % for i=1:ndhk % v2 = pnt(dhk(i,2),:) - pnt(dhk(i,1),:); % v3 = pnt(dhk(i,3),:) - pnt(dhk(i,1),:); % nrm_dhk(i,:) = cross(v2, v3); % end % vectorized version of the previous part v2 = pnt(dhk(:,2),:) - pnt(dhk(:,1),:); v3 = pnt(dhk(:,3),:) - pnt(dhk(:,1),:); nrm_dhk = cross(v2, v3); if strcmp(opt, 'vertex') % compute vertex normals nrm_pnt = zeros(npnt, 3); for i=1:ndhk nrm_pnt(dhk(i,1),:) = nrm_pnt(dhk(i,1),:) + nrm_dhk(i,:); nrm_pnt(dhk(i,2),:) = nrm_pnt(dhk(i,2),:) + nrm_dhk(i,:); nrm_pnt(dhk(i,3),:) = nrm_pnt(dhk(i,3),:) + nrm_dhk(i,:); end % normalise the direction vectors to have length one nrm = nrm_pnt ./ (sqrt(sum(nrm_pnt.^2, 2)) * ones(1,3)); else % normalise the direction vectors to have length one nrm = nrm_dhk ./ (sqrt(sum(nrm_dhk.^2, 2)) * ones(1,3)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fast cross product to replace the Matlab standard version function [c] = cross(a,b) c = [a(:,2).*b(:,3)-a(:,3).*b(:,2) a(:,3).*b(:,1)-a(:,1).*b(:,3) a(:,1).*b(:,2)-a(:,2).*b(:,1)];
github
philippboehmsturm/antx-master
rejectvisual_trial.m
.m
antx-master/xspm8/external/fieldtrip/private/rejectvisual_trial.m
9,172
utf_8
806a4d411be2efeca6ab8e316737ed41
function [chansel, trlsel, cfg] = rejectvisual_trial(cfg, data); % SUBFUNCTION for ft_rejectvisual % determine the initial selection of trials and channels nchan = length(data.label); ntrl = length(data.trial); cfg.channel = ft_channelselection(cfg.channel, data.label); trlsel = true(1,ntrl); chansel = false(1,nchan); chansel(match_str(data.label, cfg.channel)) = 1; % compute the sampling frequency from the first two timepoints fsample = 1/mean(diff(data.time{1})); % compute the offset from the time axes offset = zeros(ntrl,1); for i=1:ntrl offset(i) = time2offset(data.time{i}, fsample); end if (isfield(cfg, 'preproc') && ~isempty(cfg.preproc)) ft_progress('init', cfg.feedback, 'filtering data'); for i=1:ntrl ft_progress(i/ntrl, 'filtering data in trial %d of %d\n', i, ntrl); [data.trial{i}, label, time, cfg.preproc] = preproc(data.trial{i}, data.label, data.time{i}, cfg.preproc); end ft_progress('close'); end % select the specified latency window from the data % this is done AFTER the filtering to prevent edge artifacts for i=1:ntrl begsample = nearest(data.time{i}, cfg.latency(1)); endsample = nearest(data.time{i}, cfg.latency(2)); data.time{i} = data.time{i}(begsample:endsample); data.trial{i} = data.trial{i}(:,begsample:endsample); end h = figure; axis([0 1 0 1]); axis off % the info structure will be attached to the figure % and passed around between the callback functions if strcmp(cfg.plotlayout,'1col') % hidden config option for plotting trials differently info = []; info.ncols = 1; info.nrows = nchan; info.chanlop = 1; info.trlop = 1; info.ltrlop = 0; info.quit = 0; info.ntrl = ntrl; info.nchan = nchan; info.data = data; info.cfg = cfg; info.offset = offset; info.chansel = chansel; info.trlsel = trlsel; % determine the position of each subplot within the axis for row=1:info.nrows for col=1:info.ncols indx = (row-1)*info.ncols + col; if indx>info.nchan continue end info.x(indx) = (col-0.9)/info.ncols; info.y(indx) = 1 - (row-0.45)/(info.nrows+1); end end info.label = info.data.label; elseif strcmp(cfg.plotlayout,'square') info = []; info.ncols = ceil(sqrt(nchan)); info.nrows = ceil(sqrt(nchan)); info.chanlop = 1; info.trlop = 1; info.ltrlop = 0; info.quit = 0; info.ntrl = ntrl; info.nchan = nchan; info.data = data; info.cfg = cfg; info.offset = offset; info.chansel = chansel; info.trlsel = trlsel; % determine the position of each subplot within the axis for row=1:info.nrows for col=1:info.ncols indx = (row-1)*info.ncols + col; if indx>info.nchan continue end info.x(indx) = (col-0.9)/info.ncols; info.y(indx) = 1 - (row-0.45)/(info.nrows+1); end end info.label = info.data.label; end info.ui.quit = uicontrol(h,'units','pixels','position',[ 5 5 40 18],'String','quit','Callback',@stop); info.ui.prev = uicontrol(h,'units','pixels','position',[ 50 5 25 18],'String','<','Callback',@prev); info.ui.next = uicontrol(h,'units','pixels','position',[ 75 5 25 18],'String','>','Callback',@next); info.ui.prev10 = uicontrol(h,'units','pixels','position',[105 5 25 18],'String','<<','Callback',@prev10); info.ui.next10 = uicontrol(h,'units','pixels','position',[130 5 25 18],'String','>>','Callback',@next10); info.ui.bad = uicontrol(h,'units','pixels','position',[160 5 50 18],'String','bad','Callback',@markbad); info.ui.good = uicontrol(h,'units','pixels','position',[210 5 50 18],'String','good','Callback',@markgood); info.ui.badnext = uicontrol(h,'units','pixels','position',[270 5 50 18],'String','bad>','Callback',@markbad_next); info.ui.goodnext = uicontrol(h,'units','pixels','position',[320 5 50 18],'String','good>','Callback',@markgood_next); set(gcf, 'WindowButtonUpFcn', @button); set(gcf, 'KeyPressFcn', @key); guidata(h,info); interactive = 1; while interactive && ishandle(h) redraw(h); info = guidata(h); if info.quit == 0, uiwait; else chansel = info.chansel; trlsel = info.trlsel; delete(h); break end end % while interactive %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function varargout = markbad_next(varargin) markbad(varargin{:}); next(varargin{:}); function varargout = markgood_next(varargin) markgood(varargin{:}); next(varargin{:}); function varargout = next(h, eventdata, handles, varargin) info = guidata(h); info.ltrlop = info.trlop; if info.trlop < info.ntrl, info.trlop = info.trlop + 1; end; guidata(h,info); uiresume; function varargout = prev(h, eventdata, handles, varargin) info = guidata(h); info.ltrlop = info.trlop; if info.trlop > 1, info.trlop = info.trlop - 1; end; guidata(h,info); uiresume; function varargout = next10(h, eventdata, handles, varargin) info = guidata(h); info.ltrlop = info.trlop; if info.trlop < info.ntrl - 10, info.trlop = info.trlop + 10; else info.trlop = info.ntrl; end; guidata(h,info); uiresume; function varargout = prev10(h, eventdata, handles, varargin) info = guidata(h); info.ltrlop = info.trlop; if info.trlop > 10, info.trlop = info.trlop - 10; else info.trlop = 1; end; guidata(h,info); uiresume; function varargout = markgood(h, eventdata, handles, varargin) info = guidata(h); info.trlsel(info.trlop) = 1; fprintf(description_trial(info)); title(description_trial(info)); guidata(h,info); % uiresume; function varargout = markbad(h, eventdata, handles, varargin) info = guidata(h); info.trlsel(info.trlop) = 0; fprintf(description_trial(info)); title(description_trial(info)); guidata(h,info); % uiresume; function varargout = key(h, eventdata, handles, varargin) info = guidata(h); switch lower(eventdata.Key) case 'rightarrow' if info.trlop ~= info.ntrl next(h); else fprintf('at last trial\n'); end case 'leftarrow' if info.trlop ~= 1 prev(h); else fprintf('at first trial\n'); end case 'g' markgood(h); case 'b' markbad(h); case 'q' stop(h); otherwise fprintf('unknown key pressed\n'); end function varargout = button(h, eventdata, handles, varargin) pos = get(gca, 'CurrentPoint'); x = pos(1,1); y = pos(1,2); info = guidata(h); dx = info.x - x; dy = info.y - y; dd = sqrt(dx.^2 + dy.^2); [d, i] = min(dd); if d<0.5/max(info.nrows, info.ncols) && i<=info.nchan info.chansel(i) = ~info.chansel(i); % toggle info.chanlop = i; fprintf(description_channel(info)); guidata(h,info); uiresume; else fprintf('button clicked\n'); return end function varargout = stop(h, eventdata, handles, varargin) info = guidata(h); info.quit = 1; guidata(h,info); uiresume; function str = description_channel(info); if info.chansel(info.chanlop) str = sprintf('channel %s marked as GOOD\n', info.data.label{info.chanlop}); else str = sprintf('channel %s marked as BAD\n', info.data.label{info.chanlop}); end function str = description_trial(info); if info.trlsel(info.trlop) str = sprintf('trial %d marked as GOOD\n', info.trlop); else str = sprintf('trial %d marked as BAD\n', info.trlop); end function redraw(h) if ~ishandle(h) return end info = guidata(h); fprintf(description_trial(info)); cla; title(''); drawnow hold on dat = info.data.trial{info.trlop}; time = info.data.time{info.trlop}; if ~isempty(info.cfg.alim) % use fixed amplitude limits for amplitude scaling amax = info.cfg.alim; else % use automatic amplitude limits for scaling, these are different for each trial amax = max(max(abs(dat(info.chansel,:)))); end tmin = time(1); tmax = time(end); % scale the time values between 0.1 and 0.9 time = 0.1 + 0.8*(time-tmin)/(tmax-tmin); % scale the amplitude values between -0.5 and 0.5, offset should not be removed dat = dat ./ (2*amax); for row=1:info.nrows for col=1:info.ncols chanindx = (row-1)*info.ncols + col; if chanindx>info.nchan || ~info.chansel(chanindx) continue end % scale the time values for this subplot tim = (col-1)/info.ncols + time/info.ncols; % scale the amplitude values for this subplot amp = dat(chanindx,:)./info.nrows + 1 - row/(info.nrows+1); plot(tim, amp, 'k') end end % enable or disable buttons as appropriate if info.trlop == 1 set(info.ui.prev, 'Enable', 'off'); set(info.ui.prev10, 'Enable', 'off'); else set(info.ui.prev, 'Enable', 'on'); set(info.ui.prev10, 'Enable', 'on'); end if info.trlop == info.ntrl set(info.ui.next, 'Enable', 'off'); set(info.ui.next10, 'Enable', 'off'); else set(info.ui.next, 'Enable', 'on'); set(info.ui.next10, 'Enable', 'on'); end if info.ltrlop == info.trlop && info.trlop == info.ntrl set(info.ui.badnext,'Enable', 'off'); set(info.ui.goodnext,'Enable', 'off'); else set(info.ui.badnext,'Enable', 'on'); set(info.ui.goodnext,'Enable', 'on'); end text(info.x, info.y, info.label); title(description_trial(info)); hold off
github
philippboehmsturm/antx-master
wizard_base.m
.m
antx-master/xspm8/external/fieldtrip/private/wizard_base.m
11,679
utf_8
d5e26be7986669db7dbb81191ca5a328
function h = wizard_gui(filename) % This is the low level wizard function. It evaluates the matlab content % in the workspace of the calling function. To prevent overwriting % variables in the BASE workspace, this function should be called from a % wrapper function. The wrapper function whoudl pause execution untill the % wizard figure is deleted. % Copyright (C) 2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: wizard_base.m 7123 2012-12-06 21:21:38Z roboos $ % create a new figure h = figure('Name','Wizard',... 'NumberTitle','off',... 'MenuBar','none',... 'KeyPressFcn', @cb_keyboard,... 'resizeFcn', @cb_resize,... 'closeRequestFcn', @cb_cancel); % movegui(h,'center'); % set(h, 'ToolBar', 'figure'); if nargin>0 filename = which(filename); [p, f, x] = fileparts(filename); data = []; data.path = p; data.file = f; data.ext = x; data.current = 0; data.script = script_parse(filename); guidata(h, data); % attach the data to the GUI figure else data = []; data.path = []; data.file = []; data.ext = []; data.current = 0; data.script = script_parse([]); guidata(h, data); % attach the data to the GUI figure cb_load(h); end cb_show(h); % show the GUI figure return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_keyboard(h, eventdata) h = parentfig(h); dbstack if isequal(eventdata.Key, 'o') && isequal(eventdata.Modifier, {'control'}) cb_load(h); elseif isequal(eventdata.Key, 's') && isequal(eventdata.Modifier, {'control'}) cb_save(h); elseif isequal(eventdata.Key, 'e') && isequal(eventdata.Modifier, {'control'}) cb_edit(h); elseif isequal(eventdata.Key, 'p') && isequal(eventdata.Modifier, {'control'}) cb_prev(h); elseif isequal(eventdata.Key, 'n') && isequal(eventdata.Modifier, {'control'}) cb_next(h); elseif isequal(eventdata.Key, 'q') && isequal(eventdata.Modifier, {'control'}) cb_cancel(h); elseif isequal(eventdata.Key, 'x') && isequal(eventdata.Modifier, {'control'}) % FIXME this does not work cb_done(h); elseif isequal(eventdata.Key, 'n') && any(strcmp(eventdata.Modifier, 'shift')) && any(strcmp(eventdata.Modifier, 'control')) % FIXME this does not always work correctly cb_skip(h); end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_show(h, eventdata) h = parentfig(h); data = guidata(h); clf(h); if data.current<1 % introduction, construct the GUI elements ui_next = uicontrol(h, 'tag', 'ui_next', 'KeyPressFcn', @cb_keyboard, 'style', 'pushbutton', 'string', 'next >', 'callback', @cb_next); ui_help = uicontrol(h, 'tag', 'ui_help', 'KeyPressFcn', @cb_keyboard, 'style', 'text', 'max', 10, 'horizontalAlignment', 'left', 'FontName', '', 'backgroundColor', get(h, 'color')); % display the introduction text title = cat(2, data.file, ' - introduction'); tmp = {data.script.title}; help = sprintf('%s\n', tmp{:}); help = sprintf('This wizard will help you through the following steps:\n\n%s', help); set(ui_help, 'string', help); set(h, 'Name', title); elseif data.current>length(data.script) % finalization, construct the GUI elements ui_prev = uicontrol(h, 'tag', 'ui_prev', 'KeyPressFcn', @cb_keyboard, 'style', 'pushbutton', 'string', '< prev', 'callback', @cb_prev); ui_next = uicontrol(h, 'tag', 'ui_next', 'KeyPressFcn', @cb_keyboard, 'style', 'pushbutton', 'string', 'finish', 'callback', @cb_done); ui_help = uicontrol(h, 'tag', 'ui_help', 'KeyPressFcn', @cb_keyboard, 'style', 'text', 'max', 10, 'horizontalAlignment', 'left', 'FontName', '', 'backgroundColor', get(h, 'color')); % display the finalization text title = cat(2, data.file, ' - finish'); help = sprintf('If you click finish, the variables created by the script will be exported to the Matlab workspace\n'); set(ui_help, 'string', help); set(h, 'Name', title); else % normal wizard step, construct the GUI elements ui_prev = uicontrol(h, 'tag', 'ui_prev', 'KeyPressFcn', @cb_keyboard, 'style', 'pushbutton', 'string', '< prev', 'callback', @cb_prev); ui_next = uicontrol(h, 'tag', 'ui_next', 'KeyPressFcn', @cb_keyboard, 'style', 'pushbutton', 'string', 'next >', 'callback', @cb_next); ui_help = uicontrol(h, 'tag', 'ui_help', 'KeyPressFcn', @cb_keyboard, 'style', 'text', 'max', 10, 'horizontalAlignment', 'left', 'FontName', '', 'backgroundColor', get(h, 'color')); ui_code = uicontrol(h, 'tag', 'ui_code', 'KeyPressFcn', @cb_keyboard, 'style', 'edit', 'max', 10, 'horizontalAlignment', 'left', 'FontName', 'Courier', 'backgroundColor', 'white'); % display the current wizard content help = data.script(data.current).help; code = data.script(data.current).code; title = cat(2, data.file, ' - ', data.script(data.current).title); set(ui_help, 'string', help); set(ui_code, 'string', code); set(h, 'Name', title); end cb_resize(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_resize(h, eventdata) h = parentfig(h); ui_prev = findobj(h, 'tag', 'ui_prev'); ui_next = findobj(h, 'tag', 'ui_next'); ui_help = findobj(h, 'tag', 'ui_help'); ui_code = findobj(h, 'tag', 'ui_code'); siz = get(h, 'position'); x = siz(3); y = siz(4); w = (y-40-20)/2; if ~isempty(ui_prev) set(ui_prev, 'position', [x-150 10 60 20]); end if ~isempty(ui_next) set(ui_next, 'position', [x-080 10 60 20]); end if ~isempty(ui_code) && ~isempty(ui_help) set(ui_code, 'position', [10 40 x-20 w]); set(ui_help, 'position', [10 50+w x-20 w]); else set(ui_help, 'position', [10 40 x-20 y-50]); end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_prev(h, eventdata) h = parentfig(h); cb_disable(h); data = guidata(h); if data.current>0 data.current = data.current - 1; end guidata(h, data); cb_show(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_next(h, eventdata) h = parentfig(h); cb_disable(h); data = guidata(h); if data.current>0 title = cat(2, data.file, ' - busy'); set(h, 'Name', title); ui_code = findobj(h, 'tag', 'ui_code'); code = get(ui_code, 'string'); try for i=1:size(code,1) evalin('caller', code(i,:)); end catch lasterr; end data.script(data.current).code = code; end data.current = data.current+1; guidata(h, data); cb_show(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_skip(h, eventdata) h = parentfig(h); cb_disable(h); data = guidata(h); data.current = data.current+1; guidata(h, data); cb_show(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_disable(h, eventdata) h = parentfig(h); ui_prev = findobj(h, 'tag', 'ui_prev'); ui_next = findobj(h, 'tag', 'ui_next'); ui_help = findobj(h, 'tag', 'ui_help'); ui_code = findobj(h, 'tag', 'ui_code'); set(ui_prev, 'Enable', 'off'); set(ui_next, 'Enable', 'off'); set(ui_help, 'Enable', 'off'); set(ui_code, 'Enable', 'off'); drawnow return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_enable(h, eventdata) h = parentfig(h); ui_prev = findobj(h, 'tag', 'ui_prev'); ui_next = findobj(h, 'tag', 'ui_next'); ui_help = findobj(h, 'tag', 'ui_help'); ui_code = findobj(h, 'tag', 'ui_code'); set(ui_prev, 'Enable', 'on'); set(ui_next, 'Enable', 'on'); set(ui_help, 'Enable', 'on'); set(ui_code, 'Enable', 'on'); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_edit(h, eventdata) h = parentfig(h); data = guidata(h); filename = fullfile(data.path, [data.file data.ext]); edit(filename); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_load(h, eventdata) h = parentfig(h); cb_disable(h); [f, p] = uigetfile('*.m', 'Load script from an M-file'); if ~isequal(f,0) data = guidata(h); filename = fullfile(p, f); [p, f, x] = fileparts(filename); str = script_parse(filename); data.script = str; data.current = 0; data.path = p; data.file = f; data.ext = x; guidata(h, data); cb_show(h); end cb_enable(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_save(h, eventdata) cb_disable(h); data = guidata(h); filename = fullfile(data.path, [data.file data.ext]); [f, p] = uiputfile('*.m', 'Save script to an M-file', filename); if ~isequal(f,0) filename = fullfile(p, f); [p, f, x] = fileparts(filename); fid = fopen(filename, 'wt'); script = data.script; for k=1:length(script) fprintf(fid, '%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n'); for i=1:size(script(k).help, 1) fprintf(fid, '%% %s\n', deblank(script(k).help(i,:))); end for i=1:size(script(k).code, 1) fprintf(fid, '%s\n', deblank(script(k).code(i,:))); end end fclose(fid); data.path = p; data.file = f; data.ext = x; guidata(h, data); cb_show(h); end cb_enable(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_done(h, eventdata) h = parentfig(h); cb_disable(h); assignin('caller', 'wizard_ok', 1); delete(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_cancel(h, eventdata) h = parentfig(h); cb_disable(h); assignin('caller', 'wizard_ok', 0); delete(h); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function script = script_parse(filename) if isempty(filename) script.title = ''; script.help = ''; script.code = ''; return end fid = fopen(filename); str = {}; while ~feof(fid) str{end+1} = fgetl(fid); end str = str(:); fclose(fid); i = 1; % line number k = 1; % block number script = []; while i<=length(str) script(k).title = {}; script(k).help = {}; script(k).code = {}; while i<=length(str) && ~isempty(regexp(str{i}, '^%%%%', 'once')) % skip the seperator lines i = i+1; end while i<=length(str) && ~isempty(regexp(str{i}, '^%', 'once')) script(k).help{end+1} = str{i}(2:end); i = i+1; end while i<=length(str) && isempty(regexp(str{i}, '^%%%%', 'once')) script(k).code{end+1} = str{i}; i = i+1; end k = k+1; end sel = false(size(script)); for k=1:length(script) sel(k) = isempty(script(k).help) && isempty(script(k).code); if length(script(k).help)>0 script(k).title = char(script(k).help{1}); else script(k).title = '<unknown>'; end script(k).help = char(script(k).help(:)); script(k).code = char(script(k).code(:)); end script(sel) = []; return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = parentfig(h) while get(h, 'parent') h = get(h, 'parent'); end return
github
philippboehmsturm/antx-master
spikesort.m
.m
antx-master/xspm8/external/fieldtrip/private/spikesort.m
5,888
utf_8
07eeb9336688a2791adebdd3a8441a50
function [numA, numB, indA, indB] = spikesort(numA, numB, varargin); % SPIKESORT uses a variation on the cocktail sort algorithm in combination % with a city block distance to achieve N-D trial pairing between spike % counts. The sorting is not guaranteed to result in the optimal pairing. A % linear pre-sorting algorithm is used to create good initial starting % positions. % % The goal of this function is to achieve optimal trial-pairing prior to % stratifying the spike numbers in two datasets by random removal of some % spikes in the trial and channel with the largest numnber of spikes. % Pre-sorting based on the city-block distance between the spike count % ensures that as few spikes as possible are lost. % % Use as % [srtA, srtB, indA, indB] = spikesort(numA, numB, ...) % % Optional arguments should be specified as key-value pairs and can include % 'presort' number representing the column, 'rowwise' or 'global' % % Example % numA = reshape(randperm(100*3), 100, 3); % numB = reshape(randperm(100*3), 100, 3); % [srtA, srtB, indA, indB] = spikesort(numA, numB); % % check that the order is correct, the following should be zero % numA(indA,:) - srtA % numB(indB,:) - srtB % % See also COCKTAILSORT % Copyright (C) 2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: spikesort.m 7123 2012-12-06 21:21:38Z roboos $ % this can be used for printing detailled user feedback fb = false; % get the options presort = ft_getopt(varargin, 'presort'); if any(size(numA)~=size(numB)) error('input dimensions should be the same'); end bottom = 1; top = size(numA,1); swapped = true; dist = zeros(1,top); % this will hold the distance between the trials in each pair distswap = zeros(1,2); % this will hold the distance for two trials after swapping % this is to keep track of the row-ordering during sorting sel = 1:size(numA,2); numA(:,end+1) = 1:top; numB(:,end+1) = 1:top; % compute the initial distance between the trial pairs using city block distance metric for i=1:top dist(i) = sum(abs(numA(i,sel)-numB(i,sel))); end if fb fprintf('initial cost = %d\n', sum(dist)); end if isnumeric(presort) % start by pre-sorting on the first column only [dum, indA] = sort(numA(:,presort)); [dum, indB] = sort(numB(:,presort)); numA = numA(indA,:); numB = numB(indB,:); elseif strcmp(presort, 'rowwise') full = cityblock(numA(:,sel), numB(:,sel)); link = zeros(1,top); for i=1:top d = full(i,:); d(link(1:(i-1))) = inf; [m, ind] = min(d); link(i) = ind; end indA = 1:top; indB = link; numB = numB(link,:); elseif strcmp(presort, 'global') full = cityblock(numA(:,sel), numB(:,sel)); link = zeros(1,top); while ~all(link) [m, i] = min(full(:)); [j, k] = ind2sub(size(full), i); full(j,:) = inf; full(:,k) = inf; link(j) = k; end indA = 1:top; indB = link; numB = numB(link,:); end % compute the initial distance between the trial pairs % using city block distance metric for i=1:top dist(i) = sum(abs(numA(i,sel)-numB(i,sel))); end if fb fprintf('cost after pre-sort = %d\n', sum(dist)); end while swapped swapped = false; for i=bottom:(top-1) % compute the distances between the trials after swapping % using city block distance metric distswap(1) = sum(abs(numA(i,sel)-numB(i+1,sel))); distswap(2) = sum(abs(numA(i+1,sel)-numB(i,sel))); costNow = sum(dist([i i+1])); costSwp = sum(distswap); if costNow>costSwp % test whether the two elements are in the correct order numB([i i+1], :) = numB([i+1 i], :); % let the two elements change places dist([i i+1]) = distswap; % update the distance vector swapped = true; end end % decreases `top` because the element with the largest value in the unsorted % part of the list is now on the position top top = top - 1; for i=top:-1:(bottom+1) % compute the distances between the trials after swapping % using city block distance metric distswap(1) = sum(abs(numA(i,sel)-numB(i-1,sel))); distswap(2) = sum(abs(numA(i-1,sel)-numB(i,sel))); costNow = sum(dist([i i-1])); costSwp = sum(distswap); if costNow>costSwp numB([i i-1], :) = numB([i-1 i], :); % let the two elements change places dist([i i-1]) = distswap; % update the distance vector swapped = true; end end % increases `bottom` because the element with the smallest value in the unsorted % part of the list is now on the position bottom bottom = bottom + 1; end % while swapped if fb fprintf('final cost = %d\n', sum(dist)); end indA = numA(:,end); numA = numA(:,sel); indB = numB(:,end); numB = numB(:,sel); end % function spikesort %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function d = cityblock(a, b) d = zeros(size(a,1), size(b,1)); for i=1:size(a,1) for j=1:size(b,1) d(i,j) = sum(abs(a(i,:)-b(j,:))); end end end % function cityblock
github
philippboehmsturm/antx-master
nansum.m
.m
antx-master/xspm8/external/fieldtrip/private/nansum.m
185
utf_8
4859ec062780c478011dd7a8d94684a0
% NANSUM provides a replacement for MATLAB's nanmean. % % For usage see SUM. function y = nansum(x, dim) if nargin == 1 dim = 1; end idx = isnan(x); x(idx) = 0; y = sum(x, dim); end
github
philippboehmsturm/antx-master
shiftpredict.m
.m
antx-master/xspm8/external/fieldtrip/private/shiftpredict.m
8,738
utf_8
09de5132a8fd351c7122d799783ae0ff
function [prb, cohobs, mcohrnd] = shiftpredict(cfg, dat, datindx, refindx, trltapcnt); % SHIFTPREDICT implements a shift-predictor for testing significance % of coherence within a single condition. This function is a subfunction % for SOURCESTATISTICS_SHIFTPREDICT and FREQSTATISTICS_SHIFTPREDICT. % % cfg.method % cfg.numrandomization % cfg.method % cfg.method % cfg.loopdim % cfg.feedback % cfg.method % cfg.loopdim % cfg.correctm % cfg.tail % TODO this function should be reimplemented as statfun_shiftpredict for the general statistics framework % Copyright (C) 2005, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: shiftpredict.m 7123 2012-12-06 21:21:38Z roboos $ nsgn = size(dat,1); ntap = size(dat,2); % total number of tapers over all trials nfrq = size(dat,3); if nargin<4 % assume that each trial consists of a single taper only ntrl = size(dat,2); trltapcnt = ones(1,ntrl); fprintf('assuming one taper per trial\n'); else % each trial contains multiple tapers ntrl = length(trltapcnt); trltapcnt = trltapcnt(:)'; fprintf('number of tapers varies from %d to %d\n', min(trltapcnt), max(trltapcnt)); end % allocate memory to hold the probabilities if version('-release')>=14 prb_pos = zeros(length(refindx),length(datindx),nfrq, 'single'); prb_neg = zeros(length(refindx),length(datindx),nfrq, 'single'); else prb_pos = zeros(length(refindx),length(datindx),nfrq); prb_neg = zeros(length(refindx),length(datindx),nfrq); end % compute the power per taper, per trial, and in total pow_tap = (abs(dat).^2); pow_trl = zeros(nsgn,ntrl,nfrq); for i=1:ntrl % this is the taper selection if the number of tapers per trial is different tapbeg = 1 + sum([0 trltapcnt(1:(i-1))]); tapend = sum([0 trltapcnt(1:(i ))]); % this would be the taper selection if the number of tapers per trial is identical % tapbeg = 1 + (i-1)*ntap; % tapend = (i )*ntap; % average the power per trial over the tapers in that trial pow_trl(:,i,:) = mean(pow_tap(:,tapbeg:tapend,:),2); end pow_tot = reshape(mean(pow_trl,2), nsgn, nfrq); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % normalise the data, also see the COMPUTECOH subfunction switch cfg.method case {'abscoh', 'imagcoh', 'absimagcoh', 'atanh', 'atanh_randphase'} % normalise, so that the complex conjugate multiplication immediately results in coherence if ~all(trltapcnt==trltapcnt(1)) error('all trials should have the same number of tapers'); end for i=1:nsgn for k=1:nfrq dat(i,:,k) = dat(i,:,k) ./ sqrt(pow_tot(i,k)*ntrl*trltapcnt(1)); end end case {'amplcorr', 'absamplcorr'} % normalize so that the multiplication immediately results in correlation % this uses the amplitude, which is the sqrt of the power per trial dat = sqrt(pow_trl); % each signal should have zero mean fa = reshape(mean(dat,2), nsgn, nfrq); % mean over trials for i=1:ntrl dat(:,i,:) = (dat(:,i,:) - fa); end % each signal should have unit variance fs = reshape(sqrt(sum(dat.^2,2)/ntrl), nsgn, nfrq); % standard deviation over trials for i=1:ntrl dat(:,i,:) = dat(:,i,:)./fs; end % also normalize for the number of trials dat = dat./sqrt(ntrl); otherwise error('unknown method for shift-predictor') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % create the random shuffling index vectors nrnd = cfg.numrandomization; randsel = []; switch cfg.method case {'abscoh', 'imagcoh', 'absimagcoh', 'atanh'} for i=1:nrnd % the number of tapers is identical for each trial randsel(i,:) = randblockshift(1:sum(trltapcnt), trltapcnt(1)); end case {'amplcorr', 'absamplcorr'} for i=1:nrnd randsel(i,:) = randperm(ntrl); end case {'atanh_randphase'}, for i=1:nrnd rndphs = exp(j.*2.*pi.*rand(length(unique(cfg.origtrl)))); randsel(i,:) = rndphs(cfg.origtrl); end end % select the subset of reference signals if all(refindx(:)'==1:size(dat,1)) % only make a shallow copy to save memory datref = dat; else % make a deep copy of the selected data datref = dat(refindx,:,:); end % select the subset of target signals if all(datindx(:)'==1:size(dat,1)) % only make a shallow copy to save memory dat = dat; else % make a deep copy of the selected data dat = dat(datindx,:,:); end % compute the observed coherence cohobs = computecoh(datref, dat, cfg.method, cfg.loopdim); mcohrnd = zeros(size(cohobs)); progress('init', cfg.feedback, 'Computing shift-predicted coherence'); for i=1:nrnd progress(i/nrnd, 'Computing shift-predicted coherence %d/%d\n', i, nrnd); % randomize the reference signal and re-compute coherence if all(isreal(randsel(i,:))), datrnd = datref(:,randsel(i,:),:); else datrnd = datref.*conj(repmat(randsel(i,:), [size(datref,1) 1 size(datref,3)])); end cohrnd = computecoh(datrnd, dat, cfg.method, cfg.loopdim); mcohrnd = cohrnd + mcohrnd; % compare the observed coherence with the randomized one if strcmp(cfg.correctm, 'yes') prb_pos = prb_pos + (cohobs<max(cohrnd(:))); prb_neg = prb_neg + (cohobs>min(cohrnd(:))); else prb_pos = prb_pos + (cohobs<cohrnd); prb_neg = prb_neg + (cohobs>cohrnd); end end progress('close'); mcohrnd = mcohrnd./nrnd; if cfg.tail==1 clear prb_neg % not needed any more, free some memory prb = prb_pos./nrnd; elseif cfg.tail==-1 clear prb_pos % not needed any more, free some memory prb = prb_neg./nrnd; else prb_neg = prb_neg./nrnd; prb_pos = prb_pos./nrnd; % for each observation select the tail that corresponds with the lowest probability prb = min(prb_neg, prb_pos); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION % this assumes that the data is properly normalised % and assumes that all trials have the same number of tapers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function coh = computecoh(datref, dat, method, loopdim) nref = size(datref,1); nsgn = size(dat,1); nfrq = size(dat,3); coh = zeros(nref,nsgn,nfrq); switch loopdim case 3 % for each frequency, simultaneously compute coherence between all reference and target signals for i=1:nfrq switch method case 'abscoh' coh(:,:,i) = abs( datref(:,:,i) * dat(:,:,i)'); case 'imagcoh' coh(:,:,i) = imag(datref(:,:,i) * dat(:,:,i)'); case 'absimagcoh' coh(:,:,i) = abs(imag(datref(:,:,i) * dat(:,:,i)')); case {'atanh' 'atanh_randphase'} coh(:,:,i) = atanh(abs(datref(:,:,i)* dat(:,:,i)')); case 'amplcorr' coh(:,:,i) = datref(:,:,i) * dat(:,:,i)'; case 'absamplcorr' coh(:,:,i) = abs( datref(:,:,i) * dat(:,:,i)'); otherwise error('unsupported method'); end end case 1 % for each reference and target signal, simultaneously compute coherence over all frequencies for i=1:nref for k=1:nsgn switch method case 'abscoh' coh(i,k,:) = abs( sum(datref(i,:,:) .* conj(dat(k,:,:)), 2)); case 'imagcoh' coh(i,k,:) = imag(sum(datref(i,:,:) .* conj(dat(k,:,:)), 2)); case 'absimagcoh' coh(i,k,:) = abs(imag(sum(datref(i,:,:) .* conj(dat(k,:,:)), 2))); case {'atanh' 'atanh_randphase'} coh(i,k,:) = atanh(abs(sum(datref(i,:,:).* conj(dat(k,:,:)), 2))); case 'amplcorr' coh(i,k,:) = sum(datref(i,:,:) .* conj(dat(k,:,:)), 2); case 'absamplcorr' coh(i,k,:) = abs( sum(datref(i,:,:) .* conj(dat(k,:,:)), 2)); otherwise error('unsupported method'); end end end otherwise error('unsupported loopdim'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that shuffles in blocks %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [out] = randblockshift(n, k); n = n(:); nbin = length(n)/k; n = reshape(n, [k nbin]); n = n(:,randperm(nbin)); out = n(:);
github
philippboehmsturm/antx-master
volumeedit.m
.m
antx-master/xspm8/external/fieldtrip/private/volumeedit.m
12,966
utf_8
f4a7c8f761e54de2e765c80d04d462bb
function [dataout] = volumeedit(data, varargin) % VOLUMEEDIT allows for editing of a (booleanized) volume, in order to % remove unwanted voxels. Interaction proceeds with the keyboard and the % mouse. % Copyright (C) 2013, Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.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:$ revision = '$Id: ft_sourceplot.m 7192 2012-12-13 22:32:56Z roboos $'; datain = data; data = data~=0; dim = size(data); xi = round(dim(1)/2); yi = round(dim(2)/2); zi = round(dim(3)/2); xi = max(xi, 1); xi = min(xi, dim(1)); yi = max(yi, 1); yi = min(yi, dim(2)); zi = max(zi, 1); zi = min(zi, dim(3)); % enforce the size of the subplots to be isotropic xdim = dim(1) + dim(2); ydim = dim(2) + dim(3); xsize(1) = 0.82*dim(1)/xdim; xsize(2) = 0.82*dim(2)/xdim; ysize(1) = 0.82*dim(3)/ydim; ysize(2) = 0.82*dim(2)/ydim; % create figure h = figure; set(h, 'color', [1 1 1]); set(h, 'visible', 'on'); set(h, 'windowbuttondownfcn', @cb_buttonpress); set(h, 'windowbuttonupfcn', @cb_buttonrelease); set(h, 'windowkeypressfcn', @cb_keyboard); % axis handles h1 = axes('position',[0.07 0.07+ysize(2)+0.05 xsize(1) ysize(1)]); h2 = axes('position',[0.07+xsize(1)+0.05 0.07+ysize(2)+0.05 xsize(2) ysize(1)]); h3 = axes('position',[0.07 0.07 xsize(1) ysize(2)]); % slice handles hs1 = imagesc(squeeze(data(xi,:,:)),'parent',h1); colormap gray; hs2 = imagesc(data(:,:,zi)', 'parent',h2); colormap gray; hs3 = imagesc(squeeze(data(:,yi,:)),'parent',h3); colormap gray; set(h1, 'tag', 'jk', 'clim', [0 1]); set(h2, 'tag', 'ji', 'clim', [0 1]); set(h3, 'tag', 'ik', 'clim', [0 1]); % crosshair handles hch1 = crosshair([zi yi], 'parent', h1, 'color', 'y'); hch2 = crosshair([xi yi], 'parent', h2, 'color', 'y'); hch3 = crosshair([zi xi], 'parent', h3, 'color', 'y'); % erasercontour he1(1,:) = line(zi-3.5+[0 0 7 7 0],yi-3.5+[0 7 7 0 0],'color','r','parent',h1); he2(1,:) = line(xi-3.5+[0 0 7 7 0],yi-3.5+[0 7 7 0 0],'color','r','parent',h2); he3(1,:) = line(zi-3.5+[0 0 7 7 0],xi-3.5+[0 7 7 0 0],'color','r','parent',h3); % create structure to be passed to gui opt.data = data~=0; opt.handlesaxes = [h1 h2 h3]; opt.handlescross = [hch1(:)';hch2(:)';hch3(:)']; opt.handlesslice = [hs1 hs2 hs3]; opt.handleseraser = [he1(:)';he2(:)';he3(:)']; opt.ijk = [xi yi zi]; opt.dim = dim; opt.quit = 0; opt.mask = true(dim); opt.radius = 3; setappdata(h, 'opt', opt); cb_redraw(h); while opt.quit==0 uiwait(h); opt = getappdata(h, 'opt'); % needed to update the opt.quit end opt = getappdata(h, 'opt'); delete(h); dataout = datain; dataout(opt.mask==0) = 0; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_keyboard(h, eventdata) if isempty(eventdata) % determine the key that corresponds to the uicontrol element that was activated key = get(h, 'userdata'); else % determine the key that was pressed on the keyboard key = parseKeyboardEvent(eventdata); end % get focus back to figure if ~strcmp(get(h, 'type'), 'figure') set(h, 'enable', 'off'); drawnow; set(h, 'enable', 'on'); end h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); tag = get(curr_ax, 'tag'); switch tag case 'jk' xy = [2 3]; case 'ji' xy = [2 1]; case 'ik' xy = [1 3]; otherwise end switch key case 'leftarrow' opt.ijk(xy(2)) = opt.ijk(xy(2)) - 1; setappdata(h, 'opt', opt); cb_redraw(h); case 'rightarrow' opt.ijk(xy(2)) = opt.ijk(xy(2)) + 1; setappdata(h, 'opt', opt); cb_redraw(h); case 'uparrow' opt.ijk(xy(1)) = opt.ijk(xy(1)) - 1; setappdata(h, 'opt', opt); cb_redraw(h); case 'downarrow' opt.ijk(xy(1)) = opt.ijk(xy(1)) + 1; setappdata(h, 'opt', opt); cb_redraw(h); case 'd' % delete current voxel cb_eraser(h); cb_redraw(h); case 'q' setappdata(h, 'opt', opt); cb_cleanup(h); case 'r' % select the radius of the eraser box response = inputdlg(sprintf('radius of eraser box (in voxels)'), 'specify', 1, {num2str(opt.radius)}); if ~isempty(response) response = str2double(tokenize(response{1},' ')); opt.radius = round(response); opt.radius = min(opt.radius, 100); opt.radius = max(opt.radius, 1); setappdata(h, 'opt', opt); cb_erasercontour(h); end case 'control+control' % do nothing case 'shift+shift' % do nothing case 'alt+alt' % do nothing otherwise setappdata(h, 'opt', opt); %cb_help(h); end uiresume(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_eraser(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); n = opt.radius; if numel(n)==1, n = [n n n]; end xi = opt.ijk(1)+(-n(1):n(1)); yi = opt.ijk(2)+(-n(2):n(2)); zi = opt.ijk(3)+(-n(3):n(3)); opt.mask(xi,yi,zi) = false; opt.data = opt.data & opt.mask; setappdata(h, 'opt', opt); uiresume(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_erasercontour(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); ijk = opt.ijk; n = opt.radius*2+1; if numel(n)==1, n = [n n n]; end set(opt.handleseraser(1),'xdata',ijk(3)-n(3)/2+[0 0 n(3) n(3) 0]); set(opt.handleseraser(1),'ydata',ijk(2)-n(2)/2+[0 n(2) n(2) 0 0]); set(opt.handleseraser(2),'xdata',ijk(1)-n(1)/2+[0 0 n(1) n(1) 0]); set(opt.handleseraser(2),'ydata',ijk(2)-n(2)/2+[0 n(2) n(2) 0 0]); set(opt.handleseraser(3),'xdata',ijk(3)-n(3)/2+[0 0 n(3) n(3) 0]); set(opt.handleseraser(3),'ydata',ijk(1)-n(1)/2+[0 n(1) n(1) 0 0]); uiresume(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_redraw(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); xi = opt.ijk(1); yi = opt.ijk(2); zi = opt.ijk(3); dat1 = squeeze(opt.data(xi,:,:)); dat2 = opt.data(:,:,zi)'; dat3 = squeeze(opt.data(:,yi,:)); set(opt.handlesslice(1), 'CData', dat1); set(opt.handlesslice(2), 'CData', dat2); set(opt.handlesslice(3), 'CData', dat3); crosshair([zi yi], 'handle', opt.handlescross(1,:)); crosshair([xi yi], 'handle', opt.handlescross(2,:)); crosshair([zi xi], 'handle', opt.handlescross(3,:)); cb_erasercontour(h); set(h, 'currentaxes', curr_ax); setappdata(h, 'opt', opt); uiresume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_buttonpress(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); cb_getposition(h); opt = getappdata(h, 'opt'); seltype = get(h, 'selectiontype'); switch seltype case 'normal' % just update to new position, nothing else to be done here cb_redraw(h); case 'alt' cb_eraser(h); set(h, 'windowbuttonmotionfcn', @cb_tracemouse); opt = getappdata(h, 'opt'); cb_redraw(h); otherwise end setappdata(h, 'opt', opt); uiresume; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_buttonrelease(h, eventdata) seltype = get(h, 'selectiontype'); switch seltype case 'normal' % just update to new position, nothing else to be done here case 'alt' set(h, 'windowbuttonmotionfcn', ''); otherwise end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_tracemouse(h, eventdata) h = getparent(h); cb_getposition(h); opt = getappdata(h, 'opt'); n = opt.radius; if numel(n)==1, n = [n n n]; end xi = opt.ijk(1)+(-n(1):n(1)); xi(xi>opt.dim(1)) = []; xi(xi<1) = []; yi = opt.ijk(2)+(-n(2):n(2)); yi(yi>opt.dim(2)) = []; yi(yi<1) = []; zi = opt.ijk(3)+(-n(3):n(3)); zi(zi>opt.dim(3)) = []; zi(zi<1) = []; opt.mask(xi,yi,zi) = 0; opt.data = opt.data & opt.mask; setappdata(h, 'opt', opt); cb_redraw(h); uiresume; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_getposition(h, eventdata) h = getparent(h); opt = getappdata(h, 'opt'); curr_ax = get(h, 'currentaxes'); pos = get(curr_ax, 'currentpoint'); tag = get(curr_ax, 'tag'); switch tag case 'jk' opt.ijk([3,2]) = round(pos(1,1:2)); case 'ji' opt.ijk([1,2]) = round(pos(1,1:2)); case 'ik' opt.ijk([3,1]) = round(pos(1,1:2)); otherwise end opt.ijk = min(opt.ijk, opt.dim); opt.ijk = max(opt.ijk, [1 1 1]); setappdata(h, 'opt', opt); uiresume; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_cleanup(h, eventdata) opt = getappdata(h, 'opt'); opt.quit = true; setappdata(h, 'opt', opt); uiresume %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function h = getparent(h) p = h; while p~=0 h = p; p = get(h, 'parent'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = parseKeyboardEvent(eventdata) key = eventdata.Key; % handle possible numpad events (different for Windows and UNIX systems) % NOTE: shift+numpad number does not work on UNIX, since the shift % modifier is always sent for numpad events if isunix() shiftInd = match_str(eventdata.Modifier, 'shift'); if ~isnan(str2double(eventdata.Character)) && ~isempty(shiftInd) % now we now it was a numpad keystroke (numeric character sent AND % shift modifier present) key = eventdata.Character; eventdata.Modifier(shiftInd) = []; % strip the shift modifier end elseif ispc() if strfind(eventdata.Key, 'numpad') key = eventdata.Character; end end if ~isempty(eventdata.Modifier) key = [eventdata.Modifier{1} '+' key]; end
github
philippboehmsturm/antx-master
postpad.m
.m
antx-master/xspm8/external/fieldtrip/private/postpad.m
2,013
utf_8
2c9539d77ff0f85c9f89108f4dc811e0
% Copyright (C) 1994, 1995, 1996, 1997, 1998, 2000, 2002, 2004, 2005, % 2006, 2007, 2008, 2009 John W. Eaton % % This file is part of Octave. % % Octave is free software; you can redistribute it and/or modify it % under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 3 of the License, or (at % your option) any later version. % % Octave is distributed in the hope that it will be useful, but % WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU % General Public License for more details. % % You should have received a copy of the GNU General Public License % along with Octave; see the file COPYING. If not, see % <http://www.gnu.org/licenses/>. % -*- texinfo -*- % @deftypefn {Function File} {} postpad (@var{x}, @var{l}, @var{c}) % @deftypefnx {Function File} {} postpad (@var{x}, @var{l}, @var{c}, @var{dim}) % @seealso{prepad, resize} % @end deftypefn % Author: Tony Richardson <[email protected]> % Created: June 1994 function y = postpad (x, l, c, dim) if nargin < 2 || nargin > 4 %print_usage (); error('wrong number of input arguments, should be between 2 and 4'); end if nargin < 3 || isempty(c) c = 0; else if ~isscalar(c) error ('postpad: third argument must be empty or a scalar'); end end nd = ndims(x); sz = size(x); if nargin < 4 % Find the first non-singleton dimension dim = 1; while dim < nd+1 && sz(dim)==1 dim = dim + 1; end if dim > nd dim = 1; elseif ~(isscalar(dim) && dim == round(dim)) && dim > 0 && dim< nd+1 error('postpad: dim must be an integer and valid dimension'); end end if ~isscalar(l) || l<0 error ('second argument must be a positive scalar'); end if dim > nd sz(nd+1:dim) = 1; end d = sz(dim); if d >= l idx = cell(1,nd); for i = 1:nd idx{i} = 1:sz(i); end idx{dim} = 1:l; y = x(idx{:}); else sz(dim) = l-d; y = cat(dim, x, c * ones(sz)); end
github
philippboehmsturm/antx-master
statistics_wrapper.m
.m
antx-master/xspm8/external/fieldtrip/private/statistics_wrapper.m
27,008
utf_8
75f15bd59bcd26d5103082e24f4a0568
function [stat, cfg] = statistics_wrapper(cfg, varargin) % STATISTICS_WRAPPER performs the selection of the biological data for % timelock, frequency or source data and sets up the design vector or % matrix. % % The specific configuration options for selecting timelock, frequency % of source data are described in FT_TIMELOCKSTATISTICS, FT_FREQSTATISTICS and % FT_SOURCESTATISTICS, respectively. % % After selecting the data, control is passed on to a data-independent % statistical subfunction that computes test statistics plus their associated % significance probabilities and critical values under some null-hypothesis. The statistical % subfunction that is called is FT_STATISTICS_xxx, where cfg.method='xxx'. At % this moment, we have implemented two statistical subfunctions: % FT_STATISTICS_ANALYTIC, which calculates analytic significance probabilities and critical % values (exact or asymptotic), and FT_STATISTICS_MONTECARLO, which calculates % Monte-Carlo approximations of the significance probabilities and critical values. % % The specific configuration options for the statistical test are % described in FT_STATISTICS_xxx. % This function depends on PREPARE_TIMEFREQ_DATA which has the following options: % cfg.avgoverchan % cfg.avgoverfreq % cfg.avgovertime % cfg.channel % cfg.channelcmb % cfg.datarepresentation (set in STATISTICS_WRAPPER cfg.datarepresentation = 'concatenated') % cfg.frequency % cfg.latency % cfg.precision % cfg.previous (set in STATISTICS_WRAPPER cfg.previous = []) % cfg.version (id and name set in STATISTICS_WRAPPER) % Copyright (C) 2005-2006, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: statistics_wrapper.m 7393 2013-01-23 14:33:27Z jorhor $ % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamed', {'approach', 'method'}); cfg = ft_checkconfig(cfg, 'required', {'method'}); cfg = ft_checkconfig(cfg, 'forbidden', {'transform'}); % set the defaults if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end if ~isfield(cfg, 'latency'), cfg.latency = 'all'; end if ~isfield(cfg, 'frequency'), cfg.frequency = 'all'; end if ~isfield(cfg, 'roi'), cfg.roi = []; end if ~isfield(cfg, 'avgoverchan'), cfg.avgoverchan = 'no'; end if ~isfield(cfg, 'avgovertime'), cfg.avgovertime = 'no'; end if ~isfield(cfg, 'avgoverfreq'), cfg.avgoverfreq = 'no'; end if ~isfield(cfg, 'avgoverroi'), cfg.avgoverroi = 'no'; end % determine the type of the input and hence the output data if ~exist('OCTAVE_VERSION') [s, i] = dbstack; if length(s)>1 [caller_path, caller_name, caller_ext] = fileparts(s(2).name); else caller_path = ''; caller_name = ''; caller_ext = ''; end % evalin('caller', 'mfilename') does not work for Matlab 6.1 and 6.5 istimelock = strcmp(caller_name,'ft_timelockstatistics'); isfreq = strcmp(caller_name,'ft_freqstatistics'); issource = strcmp(caller_name,'ft_sourcestatistics'); else % cannot determine the calling function in Octave, try looking at the % data instead istimelock = isfield(varargin{1},'time') && ~isfield(varargin{1},'freq') && isfield(varargin{1},'avg'); isfreq = isfield(varargin{1},'time') && isfield(varargin{1},'freq'); issource = isfield(varargin{1},'pos') || isfield(varargin{1},'transform'); end if (istimelock+isfreq+issource)~=1 error('Could not determine the type of the input data'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % collect the biological data (the dependent parameter) % and the experimental design (the independent parameter) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if issource % test that all source inputs have the same dimensions and are spatially aligned for i=2:length(varargin) if isfield(varargin{1}, 'dim') && (length(varargin{i}.dim)~=length(varargin{1}.dim) || ~all(varargin{i}.dim==varargin{1}.dim)) error('dimensions of the source reconstructions do not match, use NORMALISEVOLUME first'); end if isfield(varargin{1}, 'pos') && (length(varargin{i}.pos(:))~=length(varargin{1}.pos(:)) || ~all(varargin{i}.pos(:)==varargin{1}.pos(:))) error('grid locations of the source reconstructions do not match, use NORMALISEVOLUME first'); end if isfield(varargin{1}, 'transform') && ~all(varargin{i}.transform(:)==varargin{1}.transform(:)) error('spatial coordinates of the source reconstructions do not match, use NORMALISEVOLUME first'); end end Nsource = length(varargin); Nvoxel = length(varargin{1}.inside) + length(varargin{1}.outside); if ~isempty(cfg.roi) if ischar(cfg.roi) cfg.roi = {cfg.roi}; end % the source representation should specify the position of each voxel in MNI coordinates x = varargin{1}.pos(:,1); % this is from left (negative) to right (positive) % determine the mask to restrict the subsequent analysis % process each of the ROIs, and optionally also left and/or right seperately roimask = {}; roilabel = {}; for i=1:length(cfg.roi) if islogical(cfg.roi{i}) tmp = cfg.roi{i}; else tmpcfg.roi = cfg.roi{i}; tmpcfg.inputcoord = cfg.inputcoord; tmpcfg.atlas = cfg.atlas; tmp = volumelookup(tmpcfg, varargin{1}); end if strcmp(cfg.avgoverroi, 'no') && ~isfield(cfg, 'hemisphere') % no reason to deal with seperated left/right hemispheres cfg.hemisphere = 'combined'; end if strcmp(cfg.hemisphere, 'left') tmp(x>=0) = 0; % exclude the right hemisphere roimask{end+1} = tmp; roilabel{end+1} = ['Left ' cfg.roi{i}]; elseif strcmp(cfg.hemisphere, 'right') tmp(x<=0) = 0; % exclude the right hemisphere roimask{end+1} = tmp; roilabel{end+1} = ['Right ' cfg.roi{i}]; elseif strcmp(cfg.hemisphere, 'both') % deal seperately with the voxels on the left and right side of the brain tmpL = tmp; tmpL(x>=0) = 0; % exclude the right hemisphere tmpR = tmp; tmpR(x<=0) = 0; % exclude the left hemisphere roimask{end+1} = tmpL; roimask{end+1} = tmpR; roilabel{end+1} = ['Left ' cfg.roi{i}]; roilabel{end+1} = ['Right ' cfg.roi{i}]; clear tmpL tmpR elseif strcmp(cfg.hemisphere, 'combined') % all voxels of the ROI can be combined roimask{end+1} = tmp; if ischar(cfg.roi{i}) roilabel{end+1} = cfg.roi{i}; else roilabel{end+1} = ['ROI ' num2str(i)]; end else error('incorrect specification of cfg.hemisphere'); end clear tmp end % for each roi % note that avgoverroi=yes is implemented differently at a later stage % avgoverroi=no is implemented using the inside/outside mask if strcmp(cfg.avgoverroi, 'no') for i=2:length(roimask) % combine them all in the first mask roimask{1} = roimask{1} | roimask{i}; end roimask = roimask{1}; % only keep the combined mask % the source representation should have an inside and outside vector containing indices sel = find(~roimask); varargin{1}.inside = setdiff(varargin{1}.inside, sel); varargin{1}.outside = union(varargin{1}.outside, sel); clear roimask roilabel end % if avgoverroi=no end % get the source parameter on which the statistic should be evaluated if strcmp(cfg.parameter, 'mom') && isfield(varargin{1}, 'avg') && isfield(varargin{1}.avg, 'csdlabel') && isfield(varargin{1}, 'cumtapcnt') [dat, cfg] = get_source_pcc_mom(cfg, varargin{:}); elseif strcmp(cfg.parameter, 'mom') && isfield(varargin{1}, 'avg') && ~isfield(varargin{1}.avg, 'csdlabel') [dat, cfg] = get_source_lcmv_mom(cfg, varargin{:}); elseif isfield(varargin{1}, 'trial') [dat, cfg] = get_source_trial(cfg, varargin{:}); else [dat, cfg] = get_source_avg(cfg, varargin{:}); end cfg.dimord = 'voxel'; % note that avgoverroi=no is implemented differently at an earlier stage if strcmp(cfg.avgoverroi, 'yes') tmp = zeros(length(roimask), size(dat,2)); for i=1:length(roimask) % the data only reflects those points that are inside the brain, % the atlas-based mask reflects points inside and outside the brain roi = roimask{i}(varargin{1}.inside); tmp(i,:) = mean(dat(roi,:), 1); end % replace the original data with the average over each ROI dat = tmp; clear tmp roi roimask % remember the ROIs cfg.dimord = 'roi'; end elseif isfreq || istimelock % get the ERF/TFR data by means of PREPARE_TIMEFREQ_DATA cfg.datarepresentation = 'concatenated'; [cfg, data] = prepare_timefreq_data(cfg, varargin{:}); cfg = rmfield(cfg, 'datarepresentation'); dim = size(data.biol); if length(dim)<3 % seems to be singleton frequency and time dimension dim(3)=1; dim(4)=1; elseif length(dim)<4 % seems to be singleton time dimension dim(4)=1; end cfg.dimord = 'chan_freq_time'; % the dimension of the original data (excluding the replication dimension) has to be known for clustering cfg.dim = dim(2:end); % all dimensions have to be concatenated except the replication dimension and the data has to be transposed dat = transpose(reshape(data.biol, dim(1), prod(dim(2:end)))); % remove to save some memory data.biol = []; % add gradiometer/electrode information to the configuration if ~isfield(cfg,'neighbours') && isfield(cfg, 'correctm') && strcmp(cfg.correctm, 'cluster') error('You need to specify a neighbourstructure'); %cfg.neighbours = ft_neighbourselection(cfg,varargin{1}); end end % get the design from the information in cfg and data. if ~isfield(cfg,'design') warning('Please think about how you would create cfg.design. Soon the call to prepare_design will be deprecated') cfg.design = data.design; [cfg] = prepare_design(cfg); end if size(cfg.design,2)~=size(dat,2) cfg.design = transpose(cfg.design); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute the statistic, using the data-independent statistical subfunction %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % determine the function handle to the intermediate-level statistics function if exist(['ft_statistics_' cfg.method]) statmethod = str2func(['ft_statistics_' cfg.method]); else error(sprintf('could not find the corresponding function for cfg.method="%s"\n', cfg.method)); end fprintf('using "%s" for the statistical testing\n', func2str(statmethod)); % check that the design completely describes the data if size(dat,2) ~= size(cfg.design,2) error('the size of the design matrix does not match the number of observations in the data'); end % determine the number of output arguments try % the nargout function in Matlab 6.5 and older does not work on function handles num = nargout(statmethod); catch num = 1; end design=cfg.design; cfg=rmfield(cfg,'design'); % to not confuse lower level functions with both cfg.design and design input % perform the statistical test if strcmp(func2str(statmethod),'ft_statistics_montecarlo') % because ft_statistics_montecarlo (or to be precise, clusterstat) requires to know whether it is getting source data, % the following (ugly) work around is necessary if num>1 [stat, cfg] = statmethod(cfg, dat, design, 'issource',issource); else [stat] = statmethod(cfg, dat, design, 'issource', issource); end else if num>1 [stat, cfg] = statmethod(cfg, dat, design); else [stat] = statmethod(cfg, dat, design); end end if isstruct(stat) % the statistical output contains multiple elements, e.g. F-value, beta-weights and probability statfield = fieldnames(stat); else % only the probability was returned as a single matrix, reformat into a structure dum = stat; stat = []; % this prevents a Matlab warning that appears from release 7.0.4 onwards stat.prob = dum; statfield = fieldnames(stat); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % add descriptive information to the output and rehape into the input format %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if issource if ~isfield(varargin{1},'dim') % FIX ME; this is added temporarily (20110427) to cope with ft_sourceanalysis output not having a dim field since r3273 varargin{1}.dim = [Nvoxel 1]; end if isempty(cfg.roi) || strcmp(cfg.avgoverroi, 'no') % remember the definition of the volume, assume that they are identical for all input arguments try stat.dim = varargin{1}.dim; end try stat.xgrid = varargin{1}.xgrid; end try stat.ygrid = varargin{1}.ygrid; end try stat.zgrid = varargin{1}.zgrid; end try stat.inside = varargin{1}.inside; end try stat.outside = varargin{1}.outside; end try stat.pos = varargin{1}.pos; end try stat.transform = varargin{1}.transform; end try stat.freq = varargin{1}.freq; end try stat.time = varargin{1}.time; end else stat.inside = 1:length(roilabel); stat.outside = []; stat.label = roilabel(:); end for i=1:length(statfield) tmp = getsubfield(stat, statfield{i}); if isfield(varargin{1}, 'inside') && numel(tmp)==length(varargin{1}.inside) % the statistic was only computed on voxels that are inside the brain % sort the inside and outside voxels back into their original place if islogical(tmp) tmp(varargin{1}.inside) = tmp; tmp(varargin{1}.outside) = false; else tmp(varargin{1}.inside) = tmp; tmp(varargin{1}.outside) = nan; end extradim = 1; elseif isfield(varargin{1}, 'inside') && isfield(varargin{1}, 'freq') && isfield(varargin{1}, 'time') && numel(tmp)==length(varargin{1}.inside)*length(varargin{1}.freq)*length(varargin{1}.time) % the statistic is a higher dimensional matrix (here as a function of freq) computed only on the % inside voxels newtmp = zeros(length(varargin{1}.inside)+length(varargin{1}.outside), length(varargin{1}.freq), length(varargin{1}.time)); if islogical(tmp) newtmp(varargin{1}.inside, :, :) = reshape(tmp, length(varargin{1}.inside), length(varargin{1}.freq), []); newtmp(varargin{1}.outside, :, :) = false; else newtmp(varargin{1}.inside, :, :) = reshape(tmp, length(varargin{1}.inside), length(varargin{1}.freq), []); newtmp(varargin{1}.outside, :, :) = nan; end tmp = newtmp; clear newtmp; extradim = length(varargin{1}.freq); elseif isfield(varargin{1}, 'inside') && isfield(varargin{1}, 'freq') && numel(tmp)==length(varargin{1}.inside)*length(varargin{1}.freq) % the statistic is a higher dimensional matrix (here as a function of freq) computed only on the % inside voxels newtmp = zeros(length(varargin{1}.inside)+length(varargin{1}.outside), length(varargin{1}.freq)); if islogical(tmp) newtmp(varargin{1}.inside, :) = reshape(tmp, length(varargin{1}.inside), []); newtmp(varargin{1}.outside, :) = false; else newtmp(varargin{1}.inside, :) = reshape(tmp, length(varargin{1}.inside), []); newtmp(varargin{1}.outside, :) = nan; end tmp = newtmp; clear newtmp; extradim = length(varargin{1}.freq); elseif isfield(varargin{1}, 'inside') && isfield(varargin{1}, 'time') && numel(tmp)==length(varargin{1}.inside)*length(varargin{1}.time) % the statistic is a higher dimensional matrix (here as a function of time) computed only on the % inside voxels newtmp = zeros(length(varargin{1}.inside)+length(varargin{1}.outside), length(varargin{1}.time)); if islogical(tmp) newtmp(varargin{1}.inside, :) = reshape(tmp, length(varargin{1}.inside), []); newtmp(varargin{1}.outside, :) = false; else newtmp(varargin{1}.inside, :) = reshape(tmp, length(varargin{1}.inside), []); newtmp(varargin{1}.outside, :) = nan; end tmp = newtmp; clear newtmp; extradim = length(varargin{1}.time); else extradim = 1; end if numel(tmp)==prod(varargin{1}.dim) % reshape the statistical volumes into the original format stat = setsubfield(stat, statfield{i}, reshape(tmp, varargin{1}.dim)); else stat = setsubfield(stat, statfield{i}, tmp); end end else haschan = isfield(data, 'label'); % this one remains relevant, even after averaging over channels haschancmb = isfield(data, 'labelcmb'); % this one remains relevant, even after averaging over channels hasfreq = strcmp(cfg.avgoverfreq, 'no') && ~any(isnan(data.freq)); hastime = strcmp(cfg.avgovertime, 'no') && ~any(isnan(data.time)); stat.dimord = ''; if haschan stat.dimord = [stat.dimord 'chan_']; stat.label = data.label; chandim = dim(2); elseif haschancmb stat.dimord = [stat.dimord 'chancmb_']; stat.labelcmb = data.labelcmb; chandim = dim(2); end if hasfreq stat.dimord = [stat.dimord 'freq_']; stat.freq = data.freq; freqdim = dim(3); end if hastime stat.dimord = [stat.dimord 'time_']; stat.time = data.time; timedim = dim(4); end if ~isempty(stat.dimord) % remove the last '_' stat.dimord = stat.dimord(1:(end-1)); end for i=1:length(statfield) try % reshape the fields that have the same dimension as the input data if strcmp(stat.dimord, 'chan') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim 1])); elseif strcmp(stat.dimord, 'chan_time') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim timedim])); elseif strcmp(stat.dimord, 'chan_freq') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim freqdim])); elseif strcmp(stat.dimord, 'chan_freq_time') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim freqdim timedim])); elseif strcmp(stat.dimord, 'chancmb_time') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim timedim])); elseif strcmp(stat.dimord, 'chancmb_freq') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim freqdim])); elseif strcmp(stat.dimord, 'chancmb_freq_time') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [chandim freqdim timedim])); elseif strcmp(stat.dimord, 'time') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [1 timedim])); elseif strcmp(stat.dimord, 'freq') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [1 freqdim])); elseif strcmp(stat.dimord, 'freq_time') stat = setfield(stat, statfield{i}, reshape(getfield(stat, statfield{i}), [freqdim timedim])); end end end end return % statistics_wrapper main() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for extracting the data of interest % data resemples PCC beamed source reconstruction, multiple trials are coded in mom %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dat, cfg] = get_source_pcc_mom(cfg, varargin) Nsource = length(varargin); Nvoxel = length(varargin{1}.inside) + length(varargin{1}.outside); Ninside = length(varargin{1}.inside); dim = varargin{1}.dim; for i=1:Nsource dipsel = find(strcmp(varargin{i}.avg.csdlabel, 'scandip')); ntrltap = sum(varargin{i}.cumtapcnt); dat{i} = zeros(Ninside, ntrltap); for j=1:Ninside k = varargin{1}.inside(j); dat{i}(j,:) = reshape(varargin{i}.avg.mom{k}(dipsel,:), 1, ntrltap); end end % concatenate the data matrices of the individual input arguments dat = cat(2, dat{:}); % remember the dimension of the source data cfg.dim = dim; % remember which voxels are inside the brain cfg.inside = varargin{1}.inside; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for extracting the data of interest % data resemples LCMV beamed source reconstruction, mom contains timecourse %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dat, cfg] = get_source_lcmv_mom(cfg, varargin) Nsource = length(varargin); Nvoxel = length(varargin{1}.inside) + length(varargin{1}.outside); Ntime = length(varargin{1}.avg.mom{varargin{1}.inside(1)}); Ninside = length(varargin{1}.inside); dim = [varargin{1}.dim Ntime]; dat = zeros(Ninside*Ntime, Nsource); for i=1:Nsource % collect the 4D data of this input argument tmp = nan(Ninside, Ntime); for j=1:Ninside k = varargin{1}.inside(j); tmp(j,:) = reshape(varargin{i}.avg.mom{k}, 1, dim(4)); end dat(:,i) = tmp(:); end % remember the dimension of the source data cfg.dim = dim; % remember which voxels are inside the brain cfg.inside = varargin{1}.inside; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for extracting the data of interest % data contains single-trial or single-subject source reconstructions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dat, cfg] = get_source_trial(cfg, varargin) Nsource = length(varargin); Nvoxel = length(varargin{1}.inside) + length(varargin{1}.outside); for i=1:Nsource Ntrial(i) = length(varargin{i}.trial); end k = 1; for i=1:Nsource for j=1:Ntrial(i) tmp = getsubfield(varargin{i}.trial(j), cfg.parameter); if ~iscell(tmp), %dim = size(tmp); dim = [Nvoxel 1]; else dim = [Nvoxel size(tmp{varargin{i}.inside(1)})]; end if i==1 && j==1 && numel(tmp)~=Nvoxel, warning('the input-data contains more entries than the number of voxels in the volume, the data will be concatenated'); dat = zeros(prod(dim), sum(Ntrial)); %FIXME this is old code should be removed elseif i==1 && j==1 && iscell(tmp), warning('the input-data contains more entries than the number of voxels in the volume, the data will be concatenated'); dat = zeros(Nvoxel*numel(tmp{varargin{i}.inside(1)}), sum(Ntrial)); elseif i==1 && j==1, dat = zeros(Nvoxel, sum(Ntrial)); end if ~iscell(tmp), dat(:,k) = tmp(:); else Ninside = length(varargin{i}.inside); %tmpvec = (varargin{i}.inside-1)*prod(size(tmp{varargin{i}.inside(1)})); tmpvec = varargin{i}.inside; insidevec = []; for m = 1:numel(tmp{varargin{i}.inside(1)}) insidevec = [insidevec; tmpvec(:)+(m-1)*Nvoxel]; end insidevec = insidevec(:)'; tmpdat = reshape(permute(cat(3,tmp{varargin{1}.inside}), [3 1 2]), [Ninside numel(tmp{varargin{1}.inside(1)})]); dat(insidevec, k) = tmpdat(:); end % add original dimensionality of the data to the configuration, is required for clustering %FIXME: this was obviously wrong, because often trial-data is one-dimensional, so no dimensional information is present %cfg.dim = dim(2:end); k = k+1; end end if isfield(varargin{1}, 'inside') fprintf('only selecting voxels inside the brain for statistics (%.1f%%)\n', 100*length(varargin{1}.inside)/prod(dim)); for j=prod(dim(2:end)):-1:1 dat((j-1).*dim(1) + varargin{1}.outside, :) = []; end end % remember the dimension of the source data if ~isfield(cfg, 'dim') warning('for clustering on trial-based data you explicitly have to specify cfg.dim'); end % remember which voxels are inside the brain cfg.inside = varargin{1}.inside; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for extracting the data of interest % get the average source reconstructions, the repetitions are in multiple input arguments %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dat, cfg] = get_source_avg(cfg, varargin) Nsource = length(varargin); Nvoxel = length(varargin{1}.inside) + length(varargin{1}.outside); dim = varargin{1}.dim; inside = false(prod(dim),1); inside(varargin{1}.inside) = true; tmp = getsubfield(varargin{1}, cfg.parameter); if size(tmp,2)>1 if isfield(varargin{1}, 'freq') Nvoxel = Nvoxel*numel(varargin{1}.freq); dim = [dim numel(varargin{1}.freq)]; inside = repmat(inside, [1 numel(varargin{1}.freq)]); end if isfield(varargin{1}, 'time') Nvoxel = Nvoxel*numel(varargin{1}.time); dim = [dim numel(varargin{1}.time)]; if isfield(varargin{1},'freq') inside = repmat(inside, [1 1 numel(varargin{1}.time)]); else inside = repmat(inside, [1 numel(varargin{1}.time)]); end end end dat = zeros(Nvoxel, Nsource); for i=1:Nsource tmp = getsubfield(varargin{i}, cfg.parameter); dat(:,i) = tmp(:); end inside = find(inside(:)); if isfield(varargin{1}, 'inside') fprintf('only selecting voxels inside the brain for statistics (%.1f%%)\n', 100*length(varargin{1}.inside)/prod(varargin{1}.dim)); dat = dat(inside,:); end % remember the dimension of the source data cfg.dim = dim; % remember which voxels are inside the brain cfg.inside = inside(:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for creating a design matrix % should be called in the code above, or in prepare_design %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [cfg] = get_source_design_pcc_mom(cfg, varargin) % should be implemented function [cfg] = get_source_design_lcmv_mom(cfg, varargin) % should be implemented function [cfg] = get_source_design_trial(cfg, varargin) % should be implemented function [cfg] = get_source_design_avg(cfg, varargin) % should be implemented
github
philippboehmsturm/antx-master
arrow.m
.m
antx-master/xspm8/external/fieldtrip/private/arrow.m
58,174
utf_8
975de6e9378e741d3d2c993ad5c36e21
function [h,yy,zz] = arrow(varargin) % ARROW Draw a line with an arrowhead. % % ARROW(Start,Stop) draws a line with an arrow from Start to Stop (points % should be vectors of length 2 or 3, or matrices with 2 or 3 % columns), and returns the graphics handle of the arrow(s). % % ARROW uses the mouse (click-drag) to create an arrow. % % ARROW DEMO & ARROW DEMO2 show 3-D & 2-D demos of the capabilities of ARROW. % % ARROW may be called with a normal argument list or a property-based list. % ARROW(Start,Stop,Length,BaseAngle,TipAngle,Width,Page,CrossDir) is % the full normal argument list, where all but the Start and Stop % points are optional. If you need to specify a later argument (e.g., % Page) but want default values of earlier ones (e.g., TipAngle), % pass an empty matrix for the earlier ones (e.g., TipAngle=[]). % % ARROW('Property1',PropVal1,'Property2',PropVal2,...) creates arrows with the % given properties, using default values for any unspecified or given as % 'default' or NaN. Some properties used for line and patch objects are % used in a modified fashion, others are passed directly to LINE, PATCH, % or SET. For a detailed properties explanation, call ARROW PROPERTIES. % % Start The starting points. B % Stop The end points. /|\ ^ % Length Length of the arrowhead in pixels. /|||\ | % BaseAngle Base angle in degrees (ADE). //|||\\ L| % TipAngle Tip angle in degrees (ABC). ///|||\\\ e| % Width Width of the base in pixels. ////|||\\\\ n| % Page Use hardcopy proportions. /////|D|\\\\\ g| % CrossDir Vector || to arrowhead plane. //// ||| \\\\ t| % NormalDir Vector out of arrowhead plane. /// ||| \\\ h| % Ends Which end has an arrowhead. //<----->|| \\ | % ObjectHandles Vector of handles to update. / base ||| \ V % E angle||<-------->C % ARROW(H,'Prop1',PropVal1,...), where H is a |||tipangle % vector of handles to previously-created arrows ||| % and/or line objects, will update the previously- ||| % created arrows according to the current view -->|A|<-- width % and any specified properties, and will convert % two-point line objects to corresponding arrows. ARROW(H) will update % the arrows if the current view has changed. Root, figure, or axes % handles included in H are replaced by all descendant Arrow objects. % % A property list can follow any specified normal argument list, e.g., % ARROW([1 2 3],[0 0 0],36,'BaseAngle',60) creates an arrow from (1,2,3) to % the origin, with an arrowhead of length 36 pixels and 60-degree base angle. % % The basic arguments or properties can generally be vectorized to create % multiple arrows with the same call. This is done by passing a property % with one row per arrow, or, if all arrows are to have the same property % value, just one row may be specified. % % You may want to execute AXIS(AXIS) before calling ARROW so it doesn't change % the axes on you; ARROW determines the sizes of arrow components BEFORE the % arrow is plotted, so if ARROW changes axis limits, arrows may be malformed. % % This version of ARROW uses features of MATLAB 5 and is incompatible with % earlier MATLAB versions (ARROW for MATLAB 4.2c is available separately); % some problems with perspective plots still exist. % Copyright (c)1995-2002, Dr. Erik A. Johnson <[email protected]>, 11/15/02 % Revision history: % 11/15/02 EAJ Accomodate how MATLAB 6.5 handles NaN and logicals % 7/28/02 EAJ Tried (but failed) work-around for MATLAB 6.x / OpenGL bug % if zero 'Width' or not double-ended % 11/10/99 EAJ Add logical() to eliminate zero index problem in MATLAB 5.3. % 11/10/99 EAJ Corrected warning if axis limits changed on multiple axes. % 11/10/99 EAJ Update e-mail address. % 2/10/99 EAJ Some documentation updating. % 2/24/98 EAJ Fixed bug if Start~=Stop but both colinear with viewpoint. % 8/14/97 EAJ Added workaround for MATLAB 5.1 scalar logical transpose bug. % 7/21/97 EAJ Fixed a few misc bugs. % 7/14/97 EAJ Make arrow([],'Prop',...) do nothing (no old handles) % 6/23/97 EAJ MATLAB 5 compatible version, release. % 5/27/97 EAJ Added Line Arrows back in. Corrected a few bugs. % 5/26/97 EAJ Changed missing Start/Stop to mouse-selected arrows. % 5/19/97 EAJ MATLAB 5 compatible version, beta. % 4/13/97 EAJ MATLAB 5 compatible version, alpha. % 1/31/97 EAJ Fixed bug with multiple arrows and unspecified Z coords. % 12/05/96 EAJ Fixed one more bug with log plots and NormalDir specified % 10/24/96 EAJ Fixed bug with log plots and NormalDir specified % 11/13/95 EAJ Corrected handling for 'reverse' axis directions % 10/06/95 EAJ Corrected occasional conflict with SUBPLOT % 4/24/95 EAJ A major rewrite. % Fall 94 EAJ Original code. % Things to be done: % - segment parsing, computing, and plotting into separate subfunctions % - change computing from Xform to Camera paradigms % + this will help especially with 3-D perspective plots % + if the WarpToFill section works right, remove warning code % + when perpsective works properly, remove perspective warning code % - add cell property values and struct property name/values (like get/set) % - get rid of NaN as the "default" data label % + perhaps change userdata to a struct and don't include (or leave % empty) the values specified as default; or use a cell containing % an empty matrix for a default value % - add functionality of GET to retrieve current values of ARROW properties % Many thanks to Keith Rogers <[email protected]> for his many excellent % suggestions and beta testing. Check out his shareware package MATDRAW % (at ftp://ftp.mathworks.com/pub/contrib/v5/graphics/matdraw/) -- he has % permission to distribute ARROW with MATDRAW. % Permission is granted to distribute ARROW with the toolboxes for the book % "Solving Solid Mechanics Problems with MATLAB 5", by F. Golnaraghi et al. % (Prentice Hall, 1999). % global variable initialization global ARROW_PERSP_WARN ARROW_STRETCH_WARN ARROW_AXLIMITS if isempty(ARROW_PERSP_WARN ), ARROW_PERSP_WARN =1; end; if isempty(ARROW_STRETCH_WARN), ARROW_STRETCH_WARN=1; end; % Handle callbacks if (nargin>0 & ischar(varargin{1}) & strcmp(lower(varargin{1}),'callback')), arrow_callback(varargin{2:end}); return; end; % Are we doing the demo? c = sprintf('\n'); if (nargin==1 & ischar(varargin{1})), arg1 = lower(varargin{1}); if strncmp(arg1,'prop',4), arrow_props; elseif strncmp(arg1,'demo',4) clf reset demo_info = arrow_demo; if ~strncmp(arg1,'demo2',5), hh=arrow_demo3(demo_info); else, hh=arrow_demo2(demo_info); end; if (nargout>=1), h=hh; end; elseif strncmp(arg1,'fixlimits',3), arrow_fixlimits(ARROW_AXLIMITS); ARROW_AXLIMITS=[]; elseif strncmp(arg1,'help',4), disp(help(mfilename)); else, error([upper(mfilename) ' got an unknown single-argument string ''' deblank(arg1) '''.']); end; return; end; % Check # of arguments if (nargout>3), error([upper(mfilename) ' produces at most 3 output arguments.']); end; % find first property number firstprop = nargin+1; for k=1:length(varargin), if ~isnumeric(varargin{k}), firstprop=k; break; end; end; lastnumeric = firstprop-1; % check property list if (firstprop<=nargin), for k=firstprop:2:nargin, curarg = varargin{k}; if ~ischar(curarg) | sum(size(curarg)>1)>1, error([upper(mfilename) ' requires that a property name be a single string.']); end; end; if (rem(nargin-firstprop,2)~=1), error([upper(mfilename) ' requires that the property ''' ... varargin{nargin} ''' be paired with a property value.']); end; end; % default output if (nargout>0), h=[]; end; if (nargout>1), yy=[]; end; if (nargout>2), zz=[]; end; % set values to empty matrices start = []; stop = []; len = []; baseangle = []; tipangle = []; wid = []; page = []; crossdir = []; ends = []; ax = []; oldh = []; ispatch = []; defstart = [NaN NaN NaN]; defstop = [NaN NaN NaN]; deflen = 16; defbaseangle = 90; deftipangle = 16; defwid = 0; defpage = 0; defcrossdir = [NaN NaN NaN]; defends = 1; defoldh = []; defispatch = 1; % The 'Tag' we'll put on our arrows ArrowTag = 'Arrow'; % check for oldstyle arguments if (firstprop==2), % assume arg1 is a set of handles oldh = varargin{1}(:); if isempty(oldh), return; end; elseif (firstprop>9), error([upper(mfilename) ' takes at most 8 non-property arguments.']); elseif (firstprop>2), s = str2mat('start','stop','len','baseangle','tipangle','wid','page','crossdir'); for k=1:firstprop-1, eval([deblank(s(k,:)) '=varargin{k};']); end; end; % parse property pairs extraprops={}; for k=firstprop:2:nargin, prop = varargin{k}; val = varargin{k+1}; prop = [lower(prop(:)') ' ']; if strncmp(prop,'start' ,5), start = val; elseif strncmp(prop,'stop' ,4), stop = val; elseif strncmp(prop,'len' ,3), len = val(:); elseif strncmp(prop,'base' ,4), baseangle = val(:); elseif strncmp(prop,'tip' ,3), tipangle = val(:); elseif strncmp(prop,'wid' ,3), wid = val(:); elseif strncmp(prop,'page' ,4), page = val; elseif strncmp(prop,'cross' ,5), crossdir = val; elseif strncmp(prop,'norm' ,4), if (ischar(val)), crossdir=val; else, crossdir=val*sqrt(-1); end; elseif strncmp(prop,'end' ,3), ends = val; elseif strncmp(prop,'object',6), oldh = val(:); elseif strncmp(prop,'handle',6), oldh = val(:); elseif strncmp(prop,'type' ,4), ispatch = val; elseif strncmp(prop,'userd' ,5), %ignore it else, % make sure it is a valid patch or line property eval('get(0,[''DefaultPatch'' varargin{k}]);err=0;','err=1;'); errstr=lasterr; if (err), eval('get(0,[''DefaultLine'' varargin{k}]);err=0;','err=1;'); end; if (err), errstr(1:max(find(errstr==setstr(13)|errstr==setstr(10)))) = ''; error([upper(mfilename) ' got ' errstr]); end; extraprops={extraprops{:},varargin{k},val}; end; end; % Check if we got 'default' values start = arrow_defcheck(start ,defstart ,'Start' ); stop = arrow_defcheck(stop ,defstop ,'Stop' ); len = arrow_defcheck(len ,deflen ,'Length' ); baseangle = arrow_defcheck(baseangle,defbaseangle,'BaseAngle' ); tipangle = arrow_defcheck(tipangle ,deftipangle ,'TipAngle' ); wid = arrow_defcheck(wid ,defwid ,'Width' ); crossdir = arrow_defcheck(crossdir ,defcrossdir ,'CrossDir' ); page = arrow_defcheck(page ,defpage ,'Page' ); ends = arrow_defcheck(ends ,defends ,'' ); oldh = arrow_defcheck(oldh ,[] ,'ObjectHandles'); ispatch = arrow_defcheck(ispatch ,defispatch ,'' ); % check transpose on arguments [m,n]=size(start ); if any(m==[2 3])&(n==1|n>3), start = start'; end; [m,n]=size(stop ); if any(m==[2 3])&(n==1|n>3), stop = stop'; end; [m,n]=size(crossdir); if any(m==[2 3])&(n==1|n>3), crossdir = crossdir'; end; % convert strings to numbers if ~isempty(ends) & ischar(ends), endsorig = ends; [m,n] = size(ends); col = lower([ends(:,1:min(3,n)) ones(m,max(0,3-n))*' ']); ends = nan(m,1); oo = ones(1,m); ii=find(all(col'==['non']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*0; end; ii=find(all(col'==['sto']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*1; end; ii=find(all(col'==['sta']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*2; end; ii=find(all(col'==['bot']'*oo)'); if ~isempty(ii), ends(ii)=ones(length(ii),1)*3; end; if any(isnan(ends)), ii = min(find(isnan(ends))); error([upper(mfilename) ' does not recognize ''' deblank(endsorig(ii,:)) ''' as a valid ''Ends'' value.']); end; else, ends = ends(:); end; if ~isempty(ispatch) & ischar(ispatch), col = lower(ispatch(:,1)); patchchar='p'; linechar='l'; defchar=' '; mask = col~=patchchar & col~=linechar & col~=defchar; if any(mask), error([upper(mfilename) ' does not recognize ''' deblank(ispatch(min(find(mask)),:)) ''' as a valid ''Type'' value.']); end; ispatch = (col==patchchar)*1 + (col==linechar)*0 + (col==defchar)*defispatch; else, ispatch = ispatch(:); end; oldh = oldh(:); % check object handles if ~all(ishandle(oldh)), error([upper(mfilename) ' got invalid object handles.']); end; % expand root, figure, and axes handles if ~isempty(oldh), ohtype = get(oldh,'Type'); mask = strcmp(ohtype,'root') | strcmp(ohtype,'figure') | strcmp(ohtype,'axes'); if any(mask), oldh = num2cell(oldh); for ii=find(mask)', oldh(ii) = {findobj(oldh{ii},'Tag',ArrowTag)}; end; oldh = cat(1,oldh{:}); if isempty(oldh), return; end; % no arrows to modify, so just leave end; end; % largest argument length [mstart,junk]=size(start); [mstop,junk]=size(stop); [mcrossdir,junk]=size(crossdir); argsizes = [length(oldh) mstart mstop ... length(len) length(baseangle) length(tipangle) ... length(wid) length(page) mcrossdir length(ends) ]; args=['length(ObjectHandle) '; ... '#rows(Start) '; ... '#rows(Stop) '; ... 'length(Length) '; ... 'length(BaseAngle) '; ... 'length(TipAngle) '; ... 'length(Width) '; ... 'length(Page) '; ... '#rows(CrossDir) '; ... '#rows(Ends) ']; if (any(imag(crossdir(:))~=0)), args(9,:) = '#rows(NormalDir) '; end; if isempty(oldh), narrows = max(argsizes); else, narrows = length(oldh); end; if (narrows<=0), narrows=1; end; % Check size of arguments ii = find((argsizes~=0)&(argsizes~=1)&(argsizes~=narrows)); if ~isempty(ii), s = args(ii',:); while ((size(s,2)>1)&((abs(s(:,size(s,2)))==0)|(abs(s(:,size(s,2)))==abs(' ')))), s = s(:,1:size(s,2)-1); end; s = [ones(length(ii),1)*[upper(mfilename) ' requires that '] s ... ones(length(ii),1)*[' equal the # of arrows (' num2str(narrows) ').' c]]; s = s'; s = s(:)'; s = s(1:length(s)-1); error(setstr(s)); end; % check element length in Start, Stop, and CrossDir if ~isempty(start), [m,n] = size(start); if (n==2), start = [start nan(m,1)]; elseif (n~=3), error([upper(mfilename) ' requires 2- or 3-element Start points.']); end; end; if ~isempty(stop), [m,n] = size(stop); if (n==2), stop = [stop nan(m,1)]; elseif (n~=3), error([upper(mfilename) ' requires 2- or 3-element Stop points.']); end; end; if ~isempty(crossdir), [m,n] = size(crossdir); if (n<3), crossdir = [crossdir nan(m,3-n)]; elseif (n~=3), if (all(imag(crossdir(:))==0)), error([upper(mfilename) ' requires 2- or 3-element CrossDir vectors.']); else, error([upper(mfilename) ' requires 2- or 3-element NormalDir vectors.']); end; end; end; % fill empty arguments if isempty(start ), start = [Inf Inf Inf]; end; if isempty(stop ), stop = [Inf Inf Inf]; end; if isempty(len ), len = Inf; end; if isempty(baseangle ), baseangle = Inf; end; if isempty(tipangle ), tipangle = Inf; end; if isempty(wid ), wid = Inf; end; if isempty(page ), page = Inf; end; if isempty(crossdir ), crossdir = [Inf Inf Inf]; end; if isempty(ends ), ends = Inf; end; if isempty(ispatch ), ispatch = Inf; end; % expand single-column arguments o = ones(narrows,1); if (size(start ,1)==1), start = o * start ; end; if (size(stop ,1)==1), stop = o * stop ; end; if (length(len )==1), len = o * len ; end; if (length(baseangle )==1), baseangle = o * baseangle ; end; if (length(tipangle )==1), tipangle = o * tipangle ; end; if (length(wid )==1), wid = o * wid ; end; if (length(page )==1), page = o * page ; end; if (size(crossdir ,1)==1), crossdir = o * crossdir ; end; if (length(ends )==1), ends = o * ends ; end; if (length(ispatch )==1), ispatch = o * ispatch ; end; ax = o * gca; % if we've got handles, get the defaults from the handles if ~isempty(oldh), for k=1:narrows, oh = oldh(k); ud = get(oh,'UserData'); ax(k) = get(oh,'Parent'); ohtype = get(oh,'Type'); if strcmp(get(oh,'Tag'),ArrowTag), % if it's an arrow already if isinf(ispatch(k)), ispatch(k)=strcmp(ohtype,'patch'); end; % arrow UserData format: [start' stop' len base tip wid page crossdir' ends] start0 = ud(1:3); stop0 = ud(4:6); if (isinf(len(k))), len(k) = ud( 7); end; if (isinf(baseangle(k))), baseangle(k) = ud( 8); end; if (isinf(tipangle(k))), tipangle(k) = ud( 9); end; if (isinf(wid(k))), wid(k) = ud(10); end; if (isinf(page(k))), page(k) = ud(11); end; if (isinf(crossdir(k,1))), crossdir(k,1) = ud(12); end; if (isinf(crossdir(k,2))), crossdir(k,2) = ud(13); end; if (isinf(crossdir(k,3))), crossdir(k,3) = ud(14); end; if (isinf(ends(k))), ends(k) = ud(15); end; elseif strcmp(ohtype,'line')|strcmp(ohtype,'patch'), % it's a non-arrow line or patch convLineToPatch = 1; %set to make arrow patches when converting from lines. if isinf(ispatch(k)), ispatch(k)=convLineToPatch|strcmp(ohtype,'patch'); end; x=get(oh,'XData'); x=x(~isnan(x(:))); if isempty(x), x=NaN; end; y=get(oh,'YData'); y=y(~isnan(y(:))); if isempty(y), y=NaN; end; z=get(oh,'ZData'); z=z(~isnan(z(:))); if isempty(z), z=NaN; end; start0 = [x(1) y(1) z(1) ]; stop0 = [x(end) y(end) z(end)]; else, error([upper(mfilename) ' cannot convert ' ohtype ' objects.']); end; ii=find(isinf(start(k,:))); if ~isempty(ii), start(k,ii)=start0(ii); end; ii=find(isinf(stop( k,:))); if ~isempty(ii), stop( k,ii)=stop0( ii); end; end; end; % convert Inf's to NaN's start( isinf(start )) = NaN; stop( isinf(stop )) = NaN; len( isinf(len )) = NaN; baseangle( isinf(baseangle)) = NaN; tipangle( isinf(tipangle )) = NaN; wid( isinf(wid )) = NaN; page( isinf(page )) = NaN; crossdir( isinf(crossdir )) = NaN; ends( isinf(ends )) = NaN; ispatch( isinf(ispatch )) = NaN; % set up the UserData data (here so not corrupted by log10's and such) ud = [start stop len baseangle tipangle wid page crossdir ends]; % Set Page defaults page = ~isnan(page) & trueornan(page); % Get axes limits, range, min; correct for aspect ratio and log scale axm = zeros(3,narrows); axr = zeros(3,narrows); axrev = zeros(3,narrows); ap = zeros(2,narrows); xyzlog = zeros(3,narrows); limmin = zeros(2,narrows); limrange = zeros(2,narrows); oldaxlims = zeros(narrows,7); oneax = all(ax==ax(1)); if (oneax), T = zeros(4,4); invT = zeros(4,4); else, T = zeros(16,narrows); invT = zeros(16,narrows); end; axnotdone = logical(ones(size(ax))); while (any(axnotdone)), ii = min(find(axnotdone)); curax = ax(ii); curpage = page(ii); % get axes limits and aspect ratio axl = [get(curax,'XLim'); get(curax,'YLim'); get(curax,'ZLim')]; oldaxlims(min(find(oldaxlims(:,1)==0)),:) = [curax reshape(axl',1,6)]; % get axes size in pixels (points) u = get(curax,'Units'); axposoldunits = get(curax,'Position'); really_curpage = curpage & strcmp(u,'normalized'); if (really_curpage), curfig = get(curax,'Parent'); pu = get(curfig,'PaperUnits'); set(curfig,'PaperUnits','points'); pp = get(curfig,'PaperPosition'); set(curfig,'PaperUnits',pu); set(curax,'Units','pixels'); curapscreen = get(curax,'Position'); set(curax,'Units','normalized'); curap = pp.*get(curax,'Position'); else, set(curax,'Units','pixels'); curapscreen = get(curax,'Position'); curap = curapscreen; end; set(curax,'Units',u); set(curax,'Position',axposoldunits); % handle non-stretched axes position str_stretch = { 'DataAspectRatioMode' ; ... 'PlotBoxAspectRatioMode' ; ... 'CameraViewAngleMode' }; str_camera = { 'CameraPositionMode' ; ... 'CameraTargetMode' ; ... 'CameraViewAngleMode' ; ... 'CameraUpVectorMode' }; notstretched = strcmp(get(curax,str_stretch),'manual'); manualcamera = strcmp(get(curax,str_camera),'manual'); if ~arrow_WarpToFill(notstretched,manualcamera,curax), % give a warning that this has not been thoroughly tested if 0 & ARROW_STRETCH_WARN, ARROW_STRETCH_WARN = 0; strs = {str_stretch{1:2},str_camera{:}}; strs = [char(ones(length(strs),1)*sprintf('\n ')) char(strs)]'; warning([upper(mfilename) ' may not yet work quite right ' ... 'if any of the following are ''manual'':' strs(:).']); end; % find the true pixel size of the actual axes texttmp = text(axl(1,[1 2 2 1 1 2 2 1]), ... axl(2,[1 1 2 2 1 1 2 2]), ... axl(3,[1 1 1 1 2 2 2 2]),''); set(texttmp,'Units','points'); textpos = get(texttmp,'Position'); delete(texttmp); textpos = cat(1,textpos{:}); textpos = max(textpos(:,1:2)) - min(textpos(:,1:2)); % adjust the axes position if (really_curpage), % adjust to printed size textpos = textpos * min(curap(3:4)./textpos); curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos]; else, % adjust for pixel roundoff textpos = textpos * min(curapscreen(3:4)./textpos); curap = [curap(1:2)+(curap(3:4)-textpos)/2 textpos]; end; end; if ARROW_PERSP_WARN & ~strcmp(get(curax,'Projection'),'orthographic'), ARROW_PERSP_WARN = 0; warning([upper(mfilename) ' does not yet work right for 3-D perspective projection.']); end; % adjust limits for log scale on axes curxyzlog = [strcmp(get(curax,'XScale'),'log'); ... strcmp(get(curax,'YScale'),'log'); ... strcmp(get(curax,'ZScale'),'log')]; if (any(curxyzlog)), ii = find([curxyzlog;curxyzlog]); if (any(axl(ii)<=0)), error([upper(mfilename) ' does not support non-positive limits on log-scaled axes.']); else, axl(ii) = log10(axl(ii)); end; end; % correct for 'reverse' direction on axes; curreverse = [strcmp(get(curax,'XDir'),'reverse'); ... strcmp(get(curax,'YDir'),'reverse'); ... strcmp(get(curax,'ZDir'),'reverse')]; ii = find(curreverse); if ~isempty(ii), axl(ii,[1 2])=-axl(ii,[2 1]); end; % compute the range of 2-D values curT = get(curax,'Xform'); lim = curT*[0 1 0 1 0 1 0 1;0 0 1 1 0 0 1 1;0 0 0 0 1 1 1 1;1 1 1 1 1 1 1 1]; lim = lim(1:2,:)./([1;1]*lim(4,:)); curlimmin = min(lim')'; curlimrange = max(lim')' - curlimmin; curinvT = inv(curT); if (~oneax), curT = curT.'; curinvT = curinvT.'; curT = curT(:); curinvT = curinvT(:); end; % check which arrows to which cur corresponds ii = find((ax==curax)&(page==curpage)); oo = ones(1,length(ii)); axr(:,ii) = diff(axl')' * oo; axm(:,ii) = axl(:,1) * oo; axrev(:,ii) = curreverse * oo; ap(:,ii) = curap(3:4)' * oo; xyzlog(:,ii) = curxyzlog * oo; limmin(:,ii) = curlimmin * oo; limrange(:,ii) = curlimrange * oo; if (oneax), T = curT; invT = curinvT; else, T(:,ii) = curT * oo; invT(:,ii) = curinvT * oo; end; axnotdone(ii) = zeros(1,length(ii)); end; oldaxlims(oldaxlims(:,1)==0,:)=[]; % correct for log scales curxyzlog = xyzlog.'; ii = find(curxyzlog(:)); if ~isempty(ii), start( ii) = real(log10(start( ii))); stop( ii) = real(log10(stop( ii))); if (all(imag(crossdir)==0)), % pulled (ii) subscript on crossdir, 12/5/96 eaj crossdir(ii) = real(log10(crossdir(ii))); end; end; % correct for reverse directions ii = find(axrev.'); if ~isempty(ii), start( ii) = -start( ii); stop( ii) = -stop( ii); crossdir(ii) = -crossdir(ii); end; % transpose start/stop values start = start.'; stop = stop.'; % take care of defaults, page was done above ii=find(isnan(start(:) )); if ~isempty(ii), start(ii) = axm(ii)+axr(ii)/2; end; ii=find(isnan(stop(:) )); if ~isempty(ii), stop(ii) = axm(ii)+axr(ii)/2; end; ii=find(isnan(crossdir(:) )); if ~isempty(ii), crossdir(ii) = zeros(length(ii),1); end; ii=find(isnan(len )); if ~isempty(ii), len(ii) = ones(length(ii),1)*deflen; end; ii=find(isnan(baseangle )); if ~isempty(ii), baseangle(ii) = ones(length(ii),1)*defbaseangle; end; ii=find(isnan(tipangle )); if ~isempty(ii), tipangle(ii) = ones(length(ii),1)*deftipangle; end; ii=find(isnan(wid )); if ~isempty(ii), wid(ii) = ones(length(ii),1)*defwid; end; ii=find(isnan(ends )); if ~isempty(ii), ends(ii) = ones(length(ii),1)*defends; end; % transpose rest of values len = len.'; baseangle = baseangle.'; tipangle = tipangle.'; wid = wid.'; page = page.'; crossdir = crossdir.'; ends = ends.'; ax = ax.'; % given x, a 3xN matrix of points in 3-space; % want to convert to X, the corresponding 4xN 2-space matrix % % tmp1=[(x-axm)./axr; ones(1,size(x,1))]; % if (oneax), X=T*tmp1; % else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; % tmp2=zeros(4,4*N); tmp2(:)=tmp1(:); % X=zeros(4,N); X(:)=sum(tmp2)'; end; % X = X ./ (ones(4,1)*X(4,:)); % for all points with start==stop, start=stop-(verysmallvalue)*(up-direction); ii = find(all(start==stop)); if ~isempty(ii), % find an arrowdir vertical on screen and perpendicular to viewer % transform to 2-D tmp1 = [(stop(:,ii)-axm(:,ii))./axr(:,ii);ones(1,length(ii))]; if (oneax), twoD=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,ii).*tmp1; tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:); twoD=zeros(4,length(ii)); twoD(:)=sum(tmp2)'; end; twoD=twoD./(ones(4,1)*twoD(4,:)); % move the start point down just slightly tmp1 = twoD + [0;-1/1000;0;0]*(limrange(2,ii)./ap(2,ii)); % transform back to 3-D if (oneax), threeD=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT(:,ii).*tmp1; tmp2=zeros(4,4*length(ii)); tmp2(:)=tmp1(:); threeD=zeros(4,length(ii)); threeD(:)=sum(tmp2)'; end; start(:,ii) = (threeD(1:3,:)./(ones(3,1)*threeD(4,:))).*axr(:,ii)+axm(:,ii); end; % compute along-arrow points % transform Start points tmp1=[(start-axm)./axr;ones(1,narrows)]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); X0=zeros(4,narrows); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % transform Stop points tmp1=[(stop-axm)./axr;ones(1,narrows)]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); Xf=zeros(4,narrows); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute pixel distance between points D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*(ap./limrange)).^2)); D = D + (D==0); %eaj new 2/24/98 % compute and modify along-arrow distances len1 = len; len2 = len - (len.*tan(tipangle/180*pi)-wid/2).*tan((90-baseangle)/180*pi); slen0 = zeros(1,narrows); slen1 = len1 .* ((ends==2)|(ends==3)); slen2 = len2 .* ((ends==2)|(ends==3)); len0 = zeros(1,narrows); len1 = len1 .* ((ends==1)|(ends==3)); len2 = len2 .* ((ends==1)|(ends==3)); % for no start arrowhead ii=find((ends==1)&(D<len2)); if ~isempty(ii), slen0(ii) = D(ii)-len2(ii); end; % for no end arrowhead ii=find((ends==2)&(D<slen2)); if ~isempty(ii), len0(ii) = D(ii)-slen2(ii); end; len1 = len1 + len0; len2 = len2 + len0; slen1 = slen1 + slen0; slen2 = slen2 + slen0; % note: the division by D below will probably not be accurate if both % of the following are true: % 1. the ratio of the line length to the arrowhead % length is large % 2. the view is highly perspective. % compute stoppoints tmp1=X0.*(ones(4,1)*(len0./D))+Xf.*(ones(4,1)*(1-len0./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; stoppoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute tippoints tmp1=X0.*(ones(4,1)*(len1./D))+Xf.*(ones(4,1)*(1-len1./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; tippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute basepoints tmp1=X0.*(ones(4,1)*(len2./D))+Xf.*(ones(4,1)*(1-len2./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; basepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute startpoints tmp1=X0.*(ones(4,1)*(1-slen0./D))+Xf.*(ones(4,1)*(slen0./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; startpoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute stippoints tmp1=X0.*(ones(4,1)*(1-slen1./D))+Xf.*(ones(4,1)*(slen1./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; stippoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute sbasepoints tmp1=X0.*(ones(4,1)*(1-slen2./D))+Xf.*(ones(4,1)*(slen2./D)); if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=invT.*tmp1; tmp2=zeros(4,4*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,narrows); tmp3(:)=sum(tmp2)'; end; sbasepoint = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)).*axr+axm; % compute cross-arrow directions for arrows with NormalDir specified if (any(imag(crossdir(:))~=0)), ii = find(any(imag(crossdir)~=0)); crossdir(:,ii) = cross((stop(:,ii)-start(:,ii))./axr(:,ii), ... imag(crossdir(:,ii))).*axr(:,ii); end; % compute cross-arrow directions basecross = crossdir + basepoint; tipcross = crossdir + tippoint; sbasecross = crossdir + sbasepoint; stipcross = crossdir + stippoint; ii = find(all(crossdir==0)|any(isnan(crossdir))); if ~isempty(ii), numii = length(ii); % transform start points tmp1 = [basepoint(:,ii) tippoint(:,ii) sbasepoint(:,ii) stippoint(:,ii)]; tmp1 = (tmp1-axm(:,[ii ii ii ii])) ./ axr(:,[ii ii ii ii]); tmp1 = [tmp1; ones(1,4*numii)]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); X0=zeros(4,4*numii); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % transform stop points tmp1 = [(2*stop(:,ii)-start(:,ii)-axm(:,ii))./axr(:,ii);ones(1,numii)]; tmp1 = [tmp1 tmp1 tmp1 tmp1]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=T(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); Xf=zeros(4,4*numii); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute perpendicular directions pixfact = ((limrange(1,ii)./limrange(2,ii)).*(ap(2,ii)./ap(1,ii))).^2; pixfact = [pixfact pixfact pixfact pixfact]; pixfact = [pixfact;1./pixfact]; [dummyval,jj] = max(abs(Xf(1:2,:)-X0(1:2,:))); jj1 = ((1:4)'*ones(1,length(jj))==ones(4,1)*jj); jj2 = ((1:4)'*ones(1,length(jj))==ones(4,1)*(3-jj)); jj3 = jj1(1:2,:); Xf(jj1)=Xf(jj1)+(Xf(jj1)-X0(jj1)==0); %eaj new 2/24/98 Xp = X0; Xp(jj2) = X0(jj2) + ones(sum(jj2(:)),1); Xp(jj1) = X0(jj1) - (Xf(jj2)-X0(jj2))./(Xf(jj1)-X0(jj1)) .* pixfact(jj3); % inverse transform the cross points if (oneax), Xp=invT*Xp; else, tmp1=[Xp;Xp;Xp;Xp]; tmp1=invT(:,[ii ii ii ii]).*tmp1; tmp2=zeros(4,16*numii); tmp2(:)=tmp1(:); Xp=zeros(4,4*numii); Xp(:)=sum(tmp2)'; end; Xp=(Xp(1:3,:)./(ones(3,1)*Xp(4,:))).*axr(:,[ii ii ii ii])+axm(:,[ii ii ii ii]); basecross(:,ii) = Xp(:,0*numii+(1:numii)); tipcross(:,ii) = Xp(:,1*numii+(1:numii)); sbasecross(:,ii) = Xp(:,2*numii+(1:numii)); stipcross(:,ii) = Xp(:,3*numii+(1:numii)); end; % compute all points % compute start points axm11 = [axm axm axm axm axm axm axm axm axm axm axm]; axr11 = [axr axr axr axr axr axr axr axr axr axr axr]; st = [stoppoint tippoint basepoint sbasepoint stippoint startpoint stippoint sbasepoint basepoint tippoint stoppoint]; tmp1 = (st - axm11) ./ axr11; tmp1 = [tmp1; ones(1,size(tmp1,2))]; if (oneax), X0=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); X0=zeros(4,11*narrows); X0(:)=sum(tmp2)'; end; X0=X0./(ones(4,1)*X0(4,:)); % compute stop points tmp1 = ([start tipcross basecross sbasecross stipcross stop stipcross sbasecross basecross tipcross start] ... - axm11) ./ axr11; tmp1 = [tmp1; ones(1,size(tmp1,2))]; if (oneax), Xf=T*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[T T T T T T T T T T T].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); Xf=zeros(4,11*narrows); Xf(:)=sum(tmp2)'; end; Xf=Xf./(ones(4,1)*Xf(4,:)); % compute lengths len0 = len.*((ends==1)|(ends==3)).*tan(tipangle/180*pi); slen0 = len.*((ends==2)|(ends==3)).*tan(tipangle/180*pi); le = [zeros(1,narrows) len0 wid/2 wid/2 slen0 zeros(1,narrows) -slen0 -wid/2 -wid/2 -len0 zeros(1,narrows)]; aprange = ap./limrange; aprange = [aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange aprange]; D = sqrt(sum(((Xf(1:2,:)-X0(1:2,:)).*aprange).^2)); Dii=find(D==0); if ~isempty(Dii), D=D+(D==0); le(Dii)=zeros(1,length(Dii)); end; %should fix DivideByZero warnings tmp1 = X0.*(ones(4,1)*(1-le./D)) + Xf.*(ones(4,1)*(le./D)); % inverse transform if (oneax), tmp3=invT*tmp1; else, tmp1=[tmp1;tmp1;tmp1;tmp1]; tmp1=[invT invT invT invT invT invT invT invT invT invT invT].*tmp1; tmp2=zeros(4,44*narrows); tmp2(:)=tmp1(:); tmp3=zeros(4,11*narrows); tmp3(:)=sum(tmp2)'; end; pts = tmp3(1:3,:)./(ones(3,1)*tmp3(4,:)) .* axr11 + axm11; % correct for ones where the crossdir was specified ii = find(~(all(crossdir==0)|any(isnan(crossdir)))); if ~isempty(ii), D1 = [pts(:,1*narrows+ii)-pts(:,9*narrows+ii) ... pts(:,2*narrows+ii)-pts(:,8*narrows+ii) ... pts(:,3*narrows+ii)-pts(:,7*narrows+ii) ... pts(:,4*narrows+ii)-pts(:,6*narrows+ii) ... pts(:,6*narrows+ii)-pts(:,4*narrows+ii) ... pts(:,7*narrows+ii)-pts(:,3*narrows+ii) ... pts(:,8*narrows+ii)-pts(:,2*narrows+ii) ... pts(:,9*narrows+ii)-pts(:,1*narrows+ii)]/2; ii = ii'*ones(1,8) + ones(length(ii),1)*[1:4 6:9]*narrows; ii = ii(:)'; pts(:,ii) = st(:,ii) + D1; end; % readjust for reverse directions iicols=(1:narrows)'; iicols=iicols(:,ones(1,11)); iicols=iicols(:).'; tmp1=axrev(:,iicols); ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=-pts(ii); end; % readjust for log scale on axes tmp1=xyzlog(:,iicols); ii = find(tmp1(:)); if ~isempty(ii), pts(ii)=10.^pts(ii); end; % compute the x,y,z coordinates of the patches; ii = narrows*(0:10)'*ones(1,narrows) + ones(11,1)*(1:narrows); ii = ii(:)'; x = zeros(11,narrows); y = zeros(11,narrows); z = zeros(11,narrows); x(:) = pts(1,ii)'; y(:) = pts(2,ii)'; z(:) = pts(3,ii)'; % do the output if (nargout<=1), % % create or modify the patches newpatch = trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'patch')); newline = ~trueornan(ispatch) & (isempty(oldh)|~strcmp(get(oldh,'Type'),'line')); if isempty(oldh), H=zeros(narrows,1); else, H=oldh; end; % % make or modify the arrows for k=1:narrows, if all(isnan(ud(k,[3 6])))&arrow_is2DXY(ax(k)), zz=[]; else, zz=z(:,k); end; % work around a MATLAB 6.x OpenGL bug -- 7/28/02 xx=x(:,k); yy=y(:,k); mask=any([ones(1,2+size(zz,2));diff([xx yy zz],[],1)],2); xx=xx(mask); yy=yy(mask); if ~isempty(zz), zz=zz(mask); end; % plot the patch or line xyz = {'XData',xx,'YData',yy,'ZData',zz,'Tag',ArrowTag}; if newpatch(k)|newline(k), if newpatch(k), H(k) = patch(xyz{:}); else, H(k) = line(xyz{:}); end; if ~isempty(oldh), arrow_copyprops(oldh(k),H(k)); end; else, if ispatch(k), xyz={xyz{:},'CData',[]}; end; set(H(k),xyz{:}); end; end; if ~isempty(oldh), delete(oldh(oldh~=H)); end; % % additional properties set(H,'Clipping','off'); set(H,{'UserData'},num2cell(ud,2)); if (length(extraprops)>0), set(H,extraprops{:}); end; % handle choosing arrow Start and/or Stop locations if unspecified [H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims); if ~isempty(errstr), error([upper(mfilename) ' got ' errstr]); end; % set the output if (nargout>0), h=H; end; % make sure the axis limits did not change if isempty(oldaxlims), ARROW_AXLIMITS = []; else, lims = get(oldaxlims(:,1),{'XLim','YLim','ZLim'})'; lims = reshape(cat(2,lims{:}),6,size(lims,2)); mask = arrow_is2DXY(oldaxlims(:,1)); oldaxlims(mask,6:7) = lims(5:6,mask)'; ARROW_AXLIMITS = oldaxlims(find(any(oldaxlims(:,2:7)'~=lims)),:); if ~isempty(ARROW_AXLIMITS), warning(arrow_warnlimits(ARROW_AXLIMITS,narrows)); end; end; else, % don't create the patch, just return the data h=x; yy=y; zz=z; end; function out = arrow_defcheck(in,def,prop) % check if we got 'default' values out = in; if ~ischar(in), return; end; if size(in,1)==1 & strncmp(lower(in),'def',3), out = def; elseif ~isempty(prop), error([upper(mfilename) ' does not recognize ''' in(:)' ''' as a valid ''' prop ''' string.']); end; function [H,oldaxlims,errstr] = arrow_clicks(H,ud,x,y,z,ax,oldaxlims) % handle choosing arrow Start and/or Stop locations if necessary errstr = ''; if isempty(H)|isempty(ud)|isempty(x), return; end; % determine which (if any) need Start and/or Stop needStart = all(isnan(ud(:,1:3)'))'; needStop = all(isnan(ud(:,4:6)'))'; mask = any(needStart|needStop); if ~any(mask), return; end; ud(~mask,:)=[]; ax(:,~mask)=[]; x(:,~mask)=[]; y(:,~mask)=[]; z(:,~mask)=[]; % make them invisible for the time being set(H,'Visible','off'); % save the current axes and limits modes; set to manual for the time being oldAx = gca; limModes=get(ax(:),{'XLimMode','YLimMode','ZLimMode'}); set(ax(:),{'XLimMode','YLimMode','ZLimMode'},{'manual','manual','manual'}); % loop over each arrow that requires attention jj = find(mask); for ii=1:length(jj), h = H(jj(ii)); axes(ax(ii)); % figure out correct call if needStart(ii), prop='Start'; else, prop='Stop'; end; [wasInterrupted,errstr] = arrow_click(needStart(ii)&needStop(ii),h,prop,ax(ii)); % handle errors and control-C if wasInterrupted, delete(H(jj(ii:end))); H(jj(ii:end))=[]; oldaxlims(jj(ii:end),:)=[]; break; end; end; % restore the axes and limit modes axes(oldAx); set(ax(:),{'XLimMode','YLimMode','ZLimMode'},limModes); function [wasInterrupted,errstr] = arrow_click(lockStart,H,prop,ax) % handle the clicks for one arrow fig = get(ax,'Parent'); % save some things oldFigProps = {'Pointer','WindowButtonMotionFcn','WindowButtonUpFcn'}; oldFigValue = get(fig,oldFigProps); oldArrowProps = {'EraseMode'}; oldArrowValue = get(H,oldArrowProps); set(H,'EraseMode','background'); %because 'xor' makes shaft invisible unless Width>1 global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z ARROW_CLICK_H=H; ARROW_CLICK_PROP=prop; ARROW_CLICK_AX=ax; ARROW_CLICK_USE_Z=~arrow_is2DXY(ax)|~arrow_planarkids(ax); set(fig,'Pointer','crosshair'); % set up the WindowButtonMotion so we can see the arrow while moving around set(fig,'WindowButtonUpFcn','set(gcf,''WindowButtonUpFcn'','''')', ... 'WindowButtonMotionFcn',''); if ~lockStart, set(H,'Visible','on'); set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']); end; % wait for the button to be pressed [wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig); % if we wanted to click-drag, set the Start point if lockStart & ~wasInterrupted, pt = arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z); feval(mfilename,H,'Start',pt,'Stop',pt); set(H,'Visible','on'); ARROW_CLICK_PROP='Stop'; set(fig,'WindowButtonMotionFcn',[mfilename '(''callback'',''motion'');']); % wait for the mouse button to be released eval('waitfor(fig,''WindowButtonUpFcn'','''');','wasInterrupted=1;'); if wasInterrupted, errstr=lasterr; end; end; if ~wasInterrupted, feval(mfilename,'callback','motion'); end; % restore some things set(gcf,oldFigProps,oldFigValue); set(H,oldArrowProps,oldArrowValue); function arrow_callback(varargin) % handle redrawing callbacks if nargin==0, return; end; str = varargin{1}; if ~ischar(str), error([upper(mfilename) ' got an invalid Callback command.']); end; s = lower(str); if strcmp(s,'motion'), % motion callback global ARROW_CLICK_H ARROW_CLICK_PROP ARROW_CLICK_AX ARROW_CLICK_USE_Z feval(mfilename,ARROW_CLICK_H,ARROW_CLICK_PROP,arrow_point(ARROW_CLICK_AX,ARROW_CLICK_USE_Z)); drawnow; else, error([upper(mfilename) ' does not recognize ''' str(:).' ''' as a valid Callback option.']); end; function out = arrow_point(ax,use_z) % return the point on the given axes if nargin==0, ax=gca; end; if nargin<2, use_z=~arrow_is2DXY(ax)|~arrow_planarkids(ax); end; out = get(ax,'CurrentPoint'); out = out(1,:); if ~use_z, out=out(1:2); end; function [wasKeyPress,wasInterrupted,errstr] = arrow_wfbdown(fig) % wait for button down ignoring object ButtonDownFcn's if nargin==0, fig=gcf; end; errstr = ''; % save ButtonDownFcn values objs = findobj(fig); buttonDownFcns = get(objs,'ButtonDownFcn'); mask=~strcmp(buttonDownFcns,''); objs=objs(mask); buttonDownFcns=buttonDownFcns(mask); set(objs,'ButtonDownFcn',''); % save other figure values figProps = {'KeyPressFcn','WindowButtonDownFcn'}; figValue = get(fig,figProps); % do the real work set(fig,'KeyPressFcn','set(gcf,''KeyPressFcn'','''',''WindowButtonDownFcn'','''');', ... 'WindowButtonDownFcn','set(gcf,''WindowButtonDownFcn'','''')'); lasterr(''); wasInterrupted=0; eval('waitfor(fig,''WindowButtonDownFcn'','''');','wasInterrupted=1;'); wasKeyPress = ~wasInterrupted & strcmp(get(fig,'KeyPressFcn'),''); if wasInterrupted, errstr=lasterr; end; % restore ButtonDownFcn and other figure values set(objs,'ButtonDownFcn',buttonDownFcns); set(fig,figProps,figValue); function [out,is2D] = arrow_is2DXY(ax) % check if axes are 2-D X-Y plots % may not work for modified camera angles, etc. out = logical(zeros(size(ax))); % 2-D X-Y plots is2D = out; % any 2-D plots views = get(ax(:),{'View'}); views = cat(1,views{:}); out(:) = abs(views(:,2))==90; is2D(:) = out(:) | all(rem(views',90)==0)'; function out = arrow_planarkids(ax) % check if axes descendents all have empty ZData (lines,patches,surfaces) out = logical(ones(size(ax))); allkids = get(ax(:),{'Children'}); for k=1:length(allkids), kids = get([findobj(allkids{k},'flat','Type','line') findobj(allkids{k},'flat','Type','patch') findobj(allkids{k},'flat','Type','surface')],{'ZData'}); for j=1:length(kids), if ~isempty(kids{j}), out(k)=logical(0); break; end; end; end; function arrow_fixlimits(axlimits) % reset the axis limits as necessary if isempty(axlimits), disp([upper(mfilename) ' does not remember any axis limits to reset.']); end; for k=1:size(axlimits,1), if any(get(axlimits(k,1),'XLim')~=axlimits(k,2:3)), set(axlimits(k,1),'XLim',axlimits(k,2:3)); end; if any(get(axlimits(k,1),'YLim')~=axlimits(k,4:5)), set(axlimits(k,1),'YLim',axlimits(k,4:5)); end; if any(get(axlimits(k,1),'ZLim')~=axlimits(k,6:7)), set(axlimits(k,1),'ZLim',axlimits(k,6:7)); end; end; function out = arrow_WarpToFill(notstretched,manualcamera,curax) % check if we are in "WarpToFill" mode. out = strcmp(get(curax,'WarpToFill'),'on'); % 'WarpToFill' is undocumented, so may need to replace this by % out = ~( any(notstretched) & any(manualcamera) ); function out = arrow_warnlimits(axlimits,narrows) % create a warning message if we've changed the axis limits msg = ''; switch (size(axlimits,1)) case 1, msg=''; case 2, msg='on two axes '; otherwise, msg='on several axes '; end; msg = [upper(mfilename) ' changed the axis limits ' msg ... 'when adding the arrow']; if (narrows>1), msg=[msg 's']; end; out = [msg '.' sprintf('\n') ' Call ' upper(mfilename) ... ' FIXLIMITS to reset them now.']; function arrow_copyprops(fm,to) % copy line properties to patches props = {'EraseMode','LineStyle','LineWidth','Marker','MarkerSize',... 'MarkerEdgeColor','MarkerFaceColor','ButtonDownFcn', ... 'Clipping','DeleteFcn','BusyAction','HandleVisibility', ... 'Selected','SelectionHighlight','Visible'}; lineprops = {'Color', props{:}}; patchprops = {'EdgeColor',props{:}}; patch2props = {'FaceColor',patchprops{:}}; fmpatch = strcmp(get(fm,'Type'),'patch'); topatch = strcmp(get(to,'Type'),'patch'); set(to( fmpatch& topatch),patch2props,get(fm( fmpatch& topatch),patch2props)); %p->p set(to(~fmpatch&~topatch),lineprops, get(fm(~fmpatch&~topatch),lineprops )); %l->l set(to( fmpatch&~topatch),lineprops, get(fm( fmpatch&~topatch),patchprops )); %p->l set(to(~fmpatch& topatch),patchprops, get(fm(~fmpatch& topatch),lineprops) ,'FaceColor','none'); %l->p function arrow_props % display further help info about ARROW properties c = sprintf('\n'); disp([c ... 'ARROW Properties: Default values are given in [square brackets], and other' c ... ' acceptable equivalent property names are in (parenthesis).' c c ... ' Start The starting points. For N arrows, B' c ... ' this should be a Nx2 or Nx3 matrix. /|\ ^' c ... ' Stop The end points. For N arrows, this /|||\ |' c ... ' should be a Nx2 or Nx3 matrix. //|||\\ L|' c ... ' Length Length of the arrowhead (in pixels on ///|||\\\ e|' c ... ' screen, points on a page). [16] (Len) ////|||\\\\ n|' c ... ' BaseAngle Angle (degrees) of the base angle /////|D|\\\\\ g|' c ... ' ADE. For a simple stick arrow, use //// ||| \\\\ t|' c ... ' BaseAngle=TipAngle. [90] (Base) /// ||| \\\ h|' c ... ' TipAngle Angle (degrees) of tip angle ABC. //<----->|| \\ |' c ... ' [16] (Tip) / base ||| \ V' c ... ' Width Width of the base in pixels. Not E angle ||<-------->C' c ... ' the ''LineWidth'' prop. [0] (Wid) |||tipangle' c ... ' Page If provided, non-empty, and not NaN, |||' c ... ' this causes ARROW to use hardcopy |||' c ... ' rather than onscreen proportions. A' c ... ' This is important if screen aspect --> <-- width' c ... ' ratio and hardcopy aspect ratio are ----CrossDir---->' c ... ' vastly different. []' c... ' CrossDir A vector giving the direction towards which the fletches' c ... ' on the arrow should go. [computed such that it is perpen-' c ... ' dicular to both the arrow direction and the view direction' c ... ' (i.e., as if it was pasted on a normal 2-D graph)] (Note' c ... ' that CrossDir is a vector. Also note that if an axis is' c ... ' plotted on a log scale, then the corresponding component' c ... ' of CrossDir must also be set appropriately, i.e., to 1 for' c ... ' no change in that direction, >1 for a positive change, >0' c ... ' and <1 for negative change.)' c ... ' NormalDir A vector normal to the fletch direction (CrossDir is then' c ... ' computed by the vector cross product [Line]x[NormalDir]). []' c ... ' (Note that NormalDir is a vector. Unlike CrossDir,' c ... ' NormalDir is used as is regardless of log-scaled axes.)' c ... ' Ends Set which end has an arrowhead. Valid values are ''none'',' c ... ' ''stop'', ''start'', and ''both''. [''stop''] (End)' c... ' ObjectHandles Vector of handles to previously-created arrows to be' c ... ' updated or line objects to be converted to arrows.' c ... ' [] (Object,Handle)' c ]); function out = arrow_demo % demo % create the data [x,y,z] = peaks; [ddd,out.iii]=max(z(:)); out.axlim = [min(x(:)) max(x(:)) min(y(:)) max(y(:)) min(z(:)) max(z(:))]; % modify it by inserting some NaN's [m,n] = size(z); m = floor(m/2); n = floor(n/2); z(1:m,1:n) = nan(m,n); % graph it clf('reset'); out.hs=surf(x,y,z); out.x=x; out.y=y; out.z=z; xlabel('x'); ylabel('y'); function h = arrow_demo3(in) % set the view axlim = in.axlim; axis(axlim); zlabel('z'); %set(in.hs,'FaceColor','interp'); view(viewmtx(-37.5,30,20)); title(['Demo of the capabilities of the ARROW function in 3-D']); % Normal blue arrow h1 = feval(mfilename,[axlim(1) axlim(4) 4],[-.8 1.2 4], ... 'EdgeColor','b','FaceColor','b'); % Normal white arrow, clipped by the surface h2 = feval(mfilename,axlim([1 4 6]),[0 2 4]); t=text(-2.4,2.7,7.7,'arrow clipped by surf'); % Baseangle<90 h3 = feval(mfilename,[3 .125 3.5],[1.375 0.125 3.5],30,50); t2=text(3.1,.125,3.5,'local maximum'); % Baseangle<90, fill and edge colors different h4 = feval(mfilename,axlim(1:2:5)*.5,[0 0 0],36,60,25, ... 'EdgeColor','b','FaceColor','c'); t3=text(axlim(1)*.5,axlim(3)*.5,axlim(5)*.5-.75,'origin'); set(t3,'HorizontalAlignment','center'); % Baseangle>90, black fill h5 = feval(mfilename,[-2.9 2.9 3],[-1.3 .4 3.2],30,120,[],6, ... 'EdgeColor','r','FaceColor','k','LineWidth',2); % Baseangle>90, no fill h6 = feval(mfilename,[-2.9 2.9 1.3],[-1.3 .4 1.5],30,120,[],6, ... 'EdgeColor','r','FaceColor','none','LineWidth',2); % Stick arrow h7 = feval(mfilename,[-1.6 -1.65 -6.5],[0 -1.65 -6.5],[],16,16); t4=text(-1.5,-1.65,-7.25,'global mininum'); set(t4,'HorizontalAlignment','center'); % Normal, black fill h8 = feval(mfilename,[-1.4 0 -7.2],[-1.4 0 -3],'FaceColor','k'); t5=text(-1.5,0,-7.75,'local minimum'); set(t5,'HorizontalAlignment','center'); % Gray fill, crossdir specified, 'LineStyle' -- h9 = feval(mfilename,[-3 2.2 -6],[-3 2.2 -.05],36,[],27,6,[],[0 -1 0], ... 'EdgeColor','k','FaceColor',.75*[1 1 1],'LineStyle','--'); % a series of normal arrows, linearly spaced, crossdir specified h10y=(0:4)'/3; h10 = feval(mfilename,[-3*ones(size(h10y)) h10y -6.5*ones(size(h10y))], ... [-3*ones(size(h10y)) h10y -.05*ones(size(h10y))], ... 12,[],[],[],[],[0 -1 0]); % a series of normal arrows, linearly spaced h11x=(1:.33:2.8)'; h11 = feval(mfilename,[h11x -3*ones(size(h11x)) 6.5*ones(size(h11x))], ... [h11x -3*ones(size(h11x)) -.05*ones(size(h11x))]); % series of magenta arrows, radially oriented, crossdir specified h12x=2; h12y=-3; h12z=axlim(5)/2; h12xr=1; h12zr=h12z; ir=.15;or=.81; h12t=(0:11)'/6*pi; h12 = feval(mfilename, ... [h12x+h12xr*cos(h12t)*ir h12y*ones(size(h12t)) ... h12z+h12zr*sin(h12t)*ir],[h12x+h12xr*cos(h12t)*or ... h12y*ones(size(h12t)) h12z+h12zr*sin(h12t)*or], ... 10,[],[],[],[], ... [-h12xr*sin(h12t) zeros(size(h12t)) h12zr*cos(h12t)],... 'FaceColor','none','EdgeColor','m'); % series of normal arrows, tangentially oriented, crossdir specified or13=.91; h13t=(0:.5:12)'/6*pi; locs = [h12x+h12xr*cos(h13t)*or13 h12y*ones(size(h13t)) h12z+h12zr*sin(h13t)*or13]; h13 = feval(mfilename,locs(1:end-1,:),locs(2:end,:),6); % arrow with no line ==> oriented downwards h14 = feval(mfilename,[3 3 .100001],[3 3 .1],30); t6=text(3,3,3.6,'no line'); set(t6,'HorizontalAlignment','center'); % arrow with arrowheads at both ends h15 = feval(mfilename,[-.5 -3 -3],[1 -3 -3],'Ends','both','FaceColor','g', ... 'Length',20,'Width',3,'CrossDir',[0 0 1],'TipAngle',25); h=[h1;h2;h3;h4;h5;h6;h7;h8;h9;h10;h11;h12;h13;h14;h15]; function h = arrow_demo2(in) axlim = in.axlim; dolog = 1; if (dolog), set(in.hs,'YData',10.^get(in.hs,'YData')); end; shading('interp'); view(2); title(['Demo of the capabilities of the ARROW function in 2-D']); hold on; [C,H]=contour(in.x,in.y,in.z,20,'-'); hold off; for k=H', set(k,'ZData',(axlim(6)+1)*ones(size(get(k,'XData'))),'Color','k'); if (dolog), set(k,'YData',10.^get(k,'YData')); end; end; if (dolog), axis([axlim(1:2) 10.^axlim(3:4)]); set(gca,'YScale','log'); else, axis(axlim(1:4)); end; % Normal blue arrow start = [axlim(1) axlim(4) axlim(6)+2]; stop = [in.x(in.iii) in.y(in.iii) axlim(6)+2]; if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end; h1 = feval(mfilename,start,stop,'EdgeColor','b','FaceColor','b'); % three arrows with varying fill, width, and baseangle start = [-3 -3 10; -3 -1.5 10; -1.5 -3 10]; stop = [-.03 -.03 10; -.03 -1.5 10; -1.5 -.03 10]; if (dolog), start(:,2)=10.^start(:,2); stop(:,2)=10.^stop(:,2); end; h2 = feval(mfilename,start,stop,24,[90;60;120],[],[0;0;4],'Ends',str2mat('both','stop','stop')); set(h2(2),'EdgeColor',[0 .35 0],'FaceColor',[0 .85 .85]); set(h2(3),'EdgeColor','r','FaceColor',[1 .5 1]); h=[h1;h2]; function out = trueornan(x) if isempty(x), out=x; else, out = isnan(x); out(~out) = x(~out); end;
github
philippboehmsturm/antx-master
csp.m
.m
antx-master/xspm8/external/fieldtrip/private/csp.m
1,702
utf_8
3eb6c73192bc8163344c9b5e70a04877
function [W] = csp(C1, C2, m) % CSP calculates the common spatial pattern (CSP) projection. % % Use as: % [W] = csp(C1, C2, m) % % This function implements the intents of the CSP algorithm described in [1]. % Specifically, CSP finds m spatial projections that maximize the variance (or % band power) in one condition (described by the [p x p] channel-covariance % matrix C1), and simultaneously minimizes the variance in the other (C2): % % W C1 W' = D % % and % % W (C1 + C2) W' = I, % % Where D is a diagonal matrix with decreasing values on it's diagonal, and I % is the identity matrix of matching shape. % The resulting [m x p] matrix can be used to project a zero-centered [p x n] % trial matrix X: % % S = W X. % % % Although the CSP is the de facto standard method for feature extraction for % motor imagery induced event-related desynchronization, it is not strictly % necessary [2]. % % [1] Zoltan J. Koles. The quantitative extraction and topographic mapping of % the abnormal components in the clinical EEG. Electroencephalography and % Clinical Neurophysiology, 79(6):440--447, December 1991. % % [2] Jason Farquhar. A linear feature space for simultaneous learning of % spatio-spectral filters in BCI. Neural Networks, 22:1278--1285, 2009. % Copyright (c) 2012, Boris Reuderink P = whiten(C1 + C2, 1e-14); % decorrelate over conditions [B, Lamb, B2] = svd(P * C1 * P'); % rotation to decorrelate within condition. W = B' * P; % keep m projections at ends keep = circshift(1:size(W, 1) <= m, [0, -m/2]); W = W(keep,:); function P = whiten(C, rtol) [U, l, U2] = svd(C); l = diag(l); keep = l > max(l) * rtol; P = diag(l(keep).^(-.5)) * U(:,keep)';
github
philippboehmsturm/antx-master
read_besa_src.m
.m
antx-master/xspm8/external/fieldtrip/private/read_besa_src.m
2,719
utf_8
a2ac15bf2e94b068fdb5b6361310a7dd
function [src] = read_besa_src(filename); % READ_BESA_SRC reads a beamformer source reconstruction from a BESA file % % Use as % [src] = read_besa_src(filename) % % The output structure contains a minimal representation of the contents % of the file. % Copyright (C) 2005, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_besa_src.m 7123 2012-12-06 21:21:38Z roboos $ src = []; fid = fopen(filename, 'rt'); % read the header information line = fgetl(fid); while isempty(strmatch('BESA_SA_IMAGE', line)), line = fgetl(fid); check_feof(fid, filename); end % while isempty(strmatch('sd' , line)), line = fgetl(fid); check_feof(fid, filename); end % this line contains condition information while isempty(strmatch('Grid dimen' , line)), line = fgetl(fid); check_feof(fid, filename); end while isempty(strmatch('X:' , line)), line = fgetl(fid); check_feof(fid, filename); end; linex = line; while isempty(strmatch('Y:' , line)), line = fgetl(fid); check_feof(fid, filename); end; liney = line; while isempty(strmatch('Z:' , line)), line = fgetl(fid); check_feof(fid, filename); end; linez = line; tok = tokenize(linex, ' '); src.X = [str2num(tok{2}) str2num(tok{3}) str2num(tok{4})]; tok = tokenize(liney, ' '); src.Y = [str2num(tok{2}) str2num(tok{3}) str2num(tok{4})]; tok = tokenize(linez, ' '); src.Z = [str2num(tok{2}) str2num(tok{3}) str2num(tok{4})]; nx = src.X(3); ny = src.Y(3); nz = src.Z(3); src.vol = zeros(nx, ny, nz); for i=1:nz % search up to the next slice while isempty(strmatch(sprintf('Z: %d', i-1), line)), line = fgetl(fid); check_feof(fid, filename); end; % read all the values for this slice buf = fscanf(fid, '%f', [nx ny]); src.vol(:,:,i) = buf; end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function check_feof(fid, filename) if feof(fid) error(sprintf('could not read all information from file ''%s''', filename)); end
github
philippboehmsturm/antx-master
splint.m
.m
antx-master/xspm8/external/fieldtrip/private/splint.m
6,074
utf_8
ef61b12d46539bcc2f66afb96daba8f2
function [V2, L2, L1] = splint(elc1, V1, elc2) % SPLINT computes the spherical spline interpolation and the surface laplacian % of an EEG potential distribution % % Use as % [V2, L2, L1] = splint(elc1, V1, elc2) % where % elc1 electrode positions where potential is known % elc2 electrode positions where potential is not known % V1 known potential % and % V2 potential at electrode locations in elc2 % L2 laplacian of potential at electrode locations in elc2 % L1 laplacian of potential at electrode locations in elc1 % % See also LAPINT, LAPINTMAT, LAPCAL % This implements % F. Perrin, J. Pernier, O. Bertrand, and J. F. Echallier. % Spherical splines for scalp potential and curernt density mapping. % Electroencephalogr Clin Neurophysiol, 72:184-187, 1989. % including their corrections in % F. Perrin, J. Pernier, O. Bertrand, and J. F. Echallier. % Corrigenda: EEG 02274, Electroencephalography and Clinical % Neurophysiology 76:565. % Copyright (C) 2003, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: splint.m 7123 2012-12-06 21:21:38Z roboos $ N = size(elc1,1); % number of known electrodes M = size(elc2,1); % number of unknown electrodes T = size(V1,2); % number of timepoints in the potential Z = V1; % potential on known electrodes, can be matrix % remember the actual size of the sphere sphere1_scale = mean(sqrt(sum(elc1.^2,2))); sphere2_scale = mean(sqrt(sum(elc2.^2,2))); % scale all electrodes towards a unit sphere elc1 = elc1 ./ repmat(sqrt(sum(elc1.^2,2)), 1, 3); elc2 = elc2 ./ repmat(sqrt(sum(elc2.^2,2)), 1, 3); % compute cosine of angle between all known electrodes CosEii = zeros(N, N); for i=1:N for j=1:N CosEii(i,j) = 1 - sum((elc1(i,:) - elc1(j,:)).^2)/2; end end % compute matrix G of Perrin 1989 [gx, hx] = gh(CosEii); G = gx; % Note that the two simultaneous equations (2) of Perrin % G*C + T*c0 = Z % T'*C = 0 % with C = [c1 c2 c3 ...] can be rewritten into a single linear system % H * [c0 c1 c2 ... cN]' = [0 z1 z2 ... zN]' % with % H = [ 0 1 1 1 1 1 1 . ] % [ 1 g11 g12 . . . . . ] % [ 1 g21 g22 . . . . . ] % [ 1 g31 g32 . . . . . ] % [ 1 g41 g42 . . . . . ] % [ . . . . . . . . ] % that subsequently can be solved using a singular value decomposition % or another linear solver % rewrite the linear system according to the comment above and solve it for C % different from Perrin, this solution for C includes the c0 term H = ones(N+1,N+1); H(1,1) = 0; H(2:end,2:end) = G; % C = pinv(H)*[zeros(1,T); Z]; % solve with SVD C = H \ [zeros(1,T); Z]; % solve by Gaussian elimination % compute surface laplacian on all known electrodes by matrix multiplication L1 = hx * C(2:end, :); % undo the initial scaling of the sphere to get back to real units for the laplacian L1 = L1 / (sphere1_scale^2); if all(size(elc1)==size(elc2)) & all(elc1(:)==elc2(:)) warning('using shortcut for splint'); % do not recompute gx and hx else % compute cosine of angle between all known and unknown electrodes CosEji = zeros(M, N); for j=1:M for i=1:N CosEji(j,i) = 1 - sum((elc2(j,:) - elc1(i,:)).^2)/2; end end [gx, hx] = gh(CosEji); end % compute interpolated potential on all unknown electrodes by matrix multiplication V2 = [ones(M,1) gx] * C; % compute surface laplacian on all unknown electrodes by matrix multiplication L2 = hx * C(2:end, :); % undo the initial scaling of the sphere to get back to real units for the laplacian L2 = L2 / (sphere2_scale^2); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this subfunction implements equations (3) and (5b) of Perrin 1989 % for simultaneous computation of multiple values % also implemented as MEX file, but without the adaptive N %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [gx, hx] = gh(x) M = 4; % constant in denominator % N is the number of terms for series expansion % N=9 works fine for 32 electrodes, but for 128 electrodes it should be larger if max(size(x))<=32 N = 9; elseif max(size(x))<=64 N = 14; elseif max(size(x))<=128 N = 20; else N = 32; end p = zeros(1,N); gx = zeros(size(x)); hx = zeros(size(x)); x(find(x>1)) = 1; % to avoid rounding off errors x(find(x<-1)) = -1; % to avoid rounding off errors % using Matlab function to compute legendre polynomials % P = zeros(size(x,1), size(x,2), N); % for k=1:N % tmp = legendre(k,x); % P(:,:,k) = squeeze(tmp(1,:,:)); % end if (size(x,1)==size(x,2)) & all(all(x==x')) issymmetric = 1; else issymmetric = 0; end for i=1:size(x,1) if issymmetric jloop = i:size(x,2); else jloop = 1:size(x,2); end for j=jloop % using faster "Numerical Recipies in C" plgndr function (mex file) for k=1:N p(k) = plgndr(k,0,x(i,j)); end % p = squeeze(P(i, j ,:))'; gx(i,j) = sum((2*(1:N)+1) ./ ((1:N).*((1:N)+1)).^M .* p) / (4*pi); hx(i,j) = -sum((2*(1:N)+1) ./ ((1:N).*((1:N)+1)).^(M-1) .* p) / (4*pi); if issymmetric gx(j,i) = gx(i,j); hx(j,i) = hx(i,j); end % fprintf('computing laplacian %f%% done\n', 100*(((i-1)*size(x,2)+j) / prod(size(x)))); end end
github
philippboehmsturm/antx-master
find_nearest.m
.m
antx-master/xspm8/external/fieldtrip/private/find_nearest.m
6,055
utf_8
a825f646f8070b85d3838ae337adee3d
function [nearest, distance] = find_nearest(pnt1, pnt2, npart, gridflag) % FIND_NEAREST finds the nearest vertex in a cloud of points and % does this efficiently for many target vertices at once (by means % of partitioning). % % Use as % [nearest, distance] = find_nearest(pnt1, pnt2, npart) % Copyright (C) 2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: find_nearest.m 7123 2012-12-06 21:21:38Z roboos $ % this can be used for printing detailled user feedback fb = false; if nargin<4 gridflag = 0; end npnt1 = size(pnt1,1); npnt2 = size(pnt2,1); if ~gridflag % check whether pnt2 is gridded if all(pnt2(1,:)==1) % it might be gridded, test in more detail dim = max(pnt2, [], 1); [X, Y, Z] = ndgrid(1:dim(1), 1:dim(2), 1:dim(3)); gridflag = all(pnt2(:)==[X(:);Y(:);Z(:)]); end end if gridflag % it is gridded, that can be treated much faster if fb, fprintf('pnt2 is gridded\n'); end sub = round(pnt1); sub(sub(:)<1) = 1; sub(sub(:,1)>dim(1),1) = dim(1); sub(sub(:,2)>dim(2),2) = dim(2); sub(sub(:,3)>dim(3),3) = dim(3); ind = sub2ind(dim, sub(:,1), sub(:,2), sub(:,3)); nearest = ind(:); distance = sqrt(sum((pnt1-pnt2(ind,:)).^2, 2)); return end if npart<1 npart = 1; end nearest = ones(size(pnt1,1),1) * -1; distance = ones(size(pnt1,1),1) * inf; sel = find(nearest<0); while ~isempty(sel) if fb, fprintf('nsel = %d, npart = %d\n', length(sel), npart); end [pnear, pdist] = find_nearest_partition(pnt1(sel,:), pnt2, npart); better = pdist<=distance(sel); nearest(sel(better)) = pnear(better); distance(sel(better)) = distance(better); sel = find(nearest<0); npart = floor(npart/2); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nearest, distance] = find_nearest_partition(pnt1, pnt2, npart) % this can be used for printing detailled user feedback fb = false; if isempty(fb) fb = 0; end npnt1 = size(pnt1,1); npnt2 = size(pnt2,1); % this will contain the output nearest = zeros(npnt1, 1); distance = zeros(npnt1, 1); if npnt1==0 return end minpnt1 = min(pnt1,1); minpnt2 = min(pnt2,1); maxpnt1 = max(pnt1,1); maxpnt2 = max(pnt2,1); pmin = min([minpnt1; minpnt2]) - eps; pmax = max([maxpnt1; maxpnt2]) + eps; dx = (pmax(1)-pmin(1))/npart; dy = (pmax(2)-pmin(2))/npart; dz = (pmax(3)-pmin(3))/npart; % determine the lower boundaries of each partition along the x, y, and z-axis limx = pmin(1) + (0:(npart-1)) * dx; limy = pmin(2) + (0:(npart-1)) * dy; limz = pmin(3) + (0:(npart-1)) * dz; % determine the lower boundaries of each of the N^3 partitions [X, Y, Z] = ndgrid(limx, limy, limz); partlim = [X(:) Y(:) Z(:)]; % determine for each vertex to which partition it belongs binx = ceil((pnt1(:,1)- pmin(1))/dx); biny = ceil((pnt1(:,2)- pmin(2))/dy); binz = ceil((pnt1(:,3)- pmin(3))/dz); ind1 = (binx-1)*npart^0 + (biny-1)*npart^1 +(binz-1)*npart^2 + 1; binx = ceil((pnt2(:,1)- pmin(1))/dx); biny = ceil((pnt2(:,2)- pmin(2))/dy); binz = ceil((pnt2(:,3)- pmin(3))/dz); ind2 = (binx-1)*npart^0 + (biny-1)*npart^1 +(binz-1)*npart^2 + 1; % use the brute force approach within each partition for p=1:(npart^3) sel1 = (ind1==p); sel2 = (ind2==p); nsel1 = sum(sel1); nsel2 = sum(sel2); if nsel1==0 || nsel2==0 continue end pnt1s = pnt1(sel1, :); pnt2s = pnt2(sel2, :); [pnear, pdist] = find_nearest_brute_force(pnt1s, pnt2s); % determine the points that are sufficiently far from the partition edge seln = true(nsel1, 1); if npart>1 if partlim(p,1)>pmin(1), seln = seln & (pdist < (pnt1s(:,1) - partlim(p,1))); end if partlim(p,1)>pmin(2), seln = seln & (pdist < (pnt1s(:,2) - partlim(p,2))); end if partlim(p,1)>pmin(3), seln = seln & (pdist < (pnt1s(:,3) - partlim(p,3))); end if partlim(p,1)<pmin(1), seln = seln & (pdist < (partlim(p,1)) + dx - pnt1s(:,1)); end if partlim(p,2)<pmin(2), seln = seln & (pdist < (partlim(p,2)) + dx - pnt1s(:,2)); end if partlim(p,3)<pmin(3), seln = seln & (pdist < (partlim(p,3)) + dx - pnt1s(:,3)); end end % the results have to be re-indexed dum1 = find(sel1); dum2 = find(sel2); nearest(dum1( seln)) = dum2(pnear( seln)); nearest(dum1(~seln)) = -dum2(pnear(~seln)); % negative means that it is not certain distance(dum1) = pdist; end % handle the points that ly in empty target partitions sel = (nearest==0); if any(sel) if fb, fprintf('%d points in empty target partition\n', sum(sel)); end pnt1s = pnt1(sel, :); [pnear, pdist] = find_nearest_brute_force(pnt1s, pnt2); nearest(sel) = pnear; distance(sel) = pdist; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [nearest, distance] = find_nearest_brute_force(pnt1, pnt2) % implementation 1 -- brute force npnt1 = size(pnt1,1); npnt2 = size(pnt2,1); nearest = zeros(npnt1, 1); distance = zeros(npnt1, 1); if npnt1==0 || npnt2==0 return end for i=1:npnt1 % compute squared distance tmp = (pnt2(:,1) - pnt1(i,1)).^2 + (pnt2(:,2) - pnt1(i,2)).^2 + (pnt2(:,3) - pnt1(i,3)).^2; [distance(i), nearest(i)] = min(tmp); end distance = sqrt(distance); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plotpnt(pnt, varargin) x = pnt(:,1); y = pnt(:,2); z = pnt(:,3); plot3(x, y, z, varargin{:});
github
philippboehmsturm/antx-master
read_besa_avr.m
.m
antx-master/xspm8/external/fieldtrip/private/read_besa_avr.m
3,929
utf_8
91f2ee59d1af564811511e0e7f201ba4
function [avr] = read_besa_avr(filename) % READ_BESA_AVR reads average EEG data in BESA format % % Use as % [avr] = read_besa_avr(filename) % % This will return a structure with the header information in % avr.npnt % avr.tsb % avr.di % avr.sb % avr.sc % avr.Nchan (optional) % avr.label (optional) % and the ERP data is contained in the Nchan X Nsamples matrix % avr.data % Copyright (C) 2003-2006, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_besa_avr.m 7123 2012-12-06 21:21:38Z roboos $ fid = fopen(filename, 'rt'); % the first line contains header information headstr = fgetl(fid); ok = 0; if ~ok try buf = sscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f Nchan= %f SegmentName= %s\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); avr.Nchan = buf(6); avr.SegmentName = buf(7); ok = 1; catch ok = 0; end end if ~ok try buf = fscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f Nchan= %f\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); avr.Nchan = buf(6); ok = 1; catch ok = 0; end end if ~ok try buf = sscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); ok = 1; catch ok = 0; end end if ~ok error('Could not interpret the header information.'); end % rewind to the beginning of the file, skip the header line fseek(fid, 0, 'bof'); fgetl(fid); % the second line may contain channel names chanstr = fgetl(fid); chanstr = deblank(fliplr(deblank(fliplr(chanstr)))); if (chanstr(1)>='A' && chanstr(1)<='Z') || (chanstr(1)>='a' && chanstr(1)<='z') haschan = 1; avr.label = str2cell(strrep(deblank(chanstr), '''', ''))'; else [root, name] = fileparts(filename); haschan = 0; elpfile = fullfile(root, [name '.elp']); elafile = fullfile(root, [name '.ela']); if exist(elpfile, 'file') % read the channel names from the accompanying ELP file lbl = importdata(elpfile); avr.label = strrep(lbl.textdata(:,2) ,'''', ''); elseif exist(elafile, 'file') % read the channel names from the accompanying ELA file lbl = importdata(elafile); lbl = strrep(lbl ,'MEG ', ''); % remove the channel type lbl = strrep(lbl ,'EEG ', ''); % remove the channel type avr.label = lbl; else warning('Could not create channels labels.'); end end % seek to the beginning of the data fseek(fid, 0, 'bof'); fgetl(fid); % skip the header line if haschan fgetl(fid); % skip the channel name line end buf = fscanf(fid, '%f'); nchan = length(buf)/avr.npnt; avr.data = reshape(buf, avr.npnt, nchan)'; fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to cut a string into pieces at the spaces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function c = str2cell(s) c = {}; [t, r] = strtok(s, ' '); while ~isempty(t) c{end+1} = t; [t, r] = strtok(r, ' '); end
github
philippboehmsturm/antx-master
sftrans.m
.m
antx-master/xspm8/external/fieldtrip/private/sftrans.m
7,947
utf_8
f64cb2e7d19bcdc6232b39d8a6d70e7c
% Copyright (C) 1999 Paul Kienzle % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop) % % Transform band edges of a generic lowpass filter (cutoff at W=1) % represented in splane zero-pole-gain form. W is the edge of the % target filter (or edges if band pass or band stop). Stop is true for % high pass and band stop filters or false for low pass and band pass % filters. Filter edges are specified in radians, from 0 to pi (the % nyquist frequency). % % Theory: Given a low pass filter represented by poles and zeros in the % splane, you can convert it to a low pass, high pass, band pass or % band stop by transforming each of the poles and zeros individually. % The following table summarizes the transformation: % % Transform Zero at x Pole at x % ---------------- ------------------------- ------------------------ % Low Pass zero: Fc x/C pole: Fc x/C % S -> C S/Fc gain: C/Fc gain: Fc/C % ---------------- ------------------------- ------------------------ % High Pass zero: Fc C/x pole: Fc C/x % S -> C Fc/S pole: 0 zero: 0 % gain: -x gain: -1/x % ---------------- ------------------------- ------------------------ % Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S^2+FhFl pole: 0 zero: 0 % S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C % S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ % Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl) % S -> C -------- gain: -x gain: -1/x % S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ % Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT) % 2 z-1 pole: -1 zero: -1 % S -> - --- gain: (2-xT)/T gain: (2-xT)/T % T z+1 % ---------------- ------------------------- ------------------------ % % where C is the cutoff frequency of the initial lowpass filter, Fc is % the edge of the target low/high pass filter and [Fl,Fh] are the edges % of the target band pass/stop filter. With abundant tedious algebra, % you can derive the above formulae yourself by substituting the % transform for S into H(S)=S-x for a zero at x or H(S)=1/(S-x) for a % pole at x, and converting the result into the form: % % H(S)=g prod(S-Xi)/prod(S-Xj) % % The transforms are from the references. The actual pole-zero-gain % changes I derived myself. % % Please note that a pole and a zero at the same place exactly cancel. % This is significant for High Pass, Band Pass and Band Stop filters % which create numerous extra poles and zeros, most of which cancel. % Those which do not cancel have a 'fill-in' effect, extending the % shorter of the sets to have the same number of as the longer of the % sets of poles and zeros (or at least split the difference in the case % of the band pass filter). There may be other opportunistic % cancellations but I will not check for them. % % Also note that any pole on the unit circle or beyond will result in % an unstable filter. Because of cancellation, this will only happen % if the number of poles is smaller than the number of zeros and the % filter is high pass or band pass. The analytic design methods all % yield more poles than zeros, so this will not be a problem. % % References: % % Proakis & Manolakis (1992). Digital Signal Processing. New York: % Macmillan Publishing Company. % Author: Paul Kienzle <[email protected]> % 2000-03-01 [email protected] % leave transformed Sg as a complex value since cheby2 blows up % otherwise (but only for odd-order low-pass filters). bilinear % will return Zg as real, so there is no visible change to the % user of the IIR filter design functions. % 2001-03-09 [email protected] % return real Sg; don't know what to do for imaginary filters function [Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop) if (nargin ~= 5) usage('[Sz, Sp, Sg] = sftrans(Sz, Sp, Sg, W, stop)'); end; C = 1; p = length(Sp); z = length(Sz); if z > p || p == 0 error('sftrans: must have at least as many poles as zeros in s-plane'); end if length(W)==2 Fl = W(1); Fh = W(2); if stop % ---------------- ------------------------- ------------------------ % Band Stop zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S(Fh-Fl) pole: ?sqrt(-FhFl) zero: ?sqrt(-FhFl) % S -> C -------- gain: -x gain: -1/x % S^2+FhFl b=C/x (Fh-Fl)/2 b=C/x (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ if (isempty(Sz)) Sg = Sg * real (1./ prod(-Sp)); elseif (isempty(Sp)) Sg = Sg * real(prod(-Sz)); else Sg = Sg * real(prod(-Sz)/prod(-Sp)); end b = (C*(Fh-Fl)/2)./Sp; Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; extend = [sqrt(-Fh*Fl), -sqrt(-Fh*Fl)]; if isempty(Sz) Sz = [extend(1+rem([1:2*p],2))]; else b = (C*(Fh-Fl)/2)./Sz; Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; if (p > z) Sz = [Sz, extend(1+rem([1:2*(p-z)],2))]; end end else % ---------------- ------------------------- ------------------------ % Band Pass zero: b ? sqrt(b^2-FhFl) pole: b ? sqrt(b^2-FhFl) % S^2+FhFl pole: 0 zero: 0 % S -> C -------- gain: C/(Fh-Fl) gain: (Fh-Fl)/C % S(Fh-Fl) b=x/C (Fh-Fl)/2 b=x/C (Fh-Fl)/2 % ---------------- ------------------------- ------------------------ Sg = Sg * (C/(Fh-Fl))^(z-p); b = Sp*((Fh-Fl)/(2*C)); Sp = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; if isempty(Sz) Sz = zeros(1,p); else b = Sz*((Fh-Fl)/(2*C)); Sz = [b+sqrt(b.^2-Fh*Fl), b-sqrt(b.^2-Fh*Fl)]; if (p>z) Sz = [Sz, zeros(1, (p-z))]; end end end else Fc = W; if stop % ---------------- ------------------------- ------------------------ % High Pass zero: Fc C/x pole: Fc C/x % S -> C Fc/S pole: 0 zero: 0 % gain: -x gain: -1/x % ---------------- ------------------------- ------------------------ if (isempty(Sz)) Sg = Sg * real (1./ prod(-Sp)); elseif (isempty(Sp)) Sg = Sg * real(prod(-Sz)); else Sg = Sg * real(prod(-Sz)/prod(-Sp)); end Sp = C * Fc ./ Sp; if isempty(Sz) Sz = zeros(1,p); else Sz = [C * Fc ./ Sz]; if (p > z) Sz = [Sz, zeros(1,p-z)]; end end else % ---------------- ------------------------- ------------------------ % Low Pass zero: Fc x/C pole: Fc x/C % S -> C S/Fc gain: C/Fc gain: Fc/C % ---------------- ------------------------- ------------------------ Sg = Sg * (C/Fc)^(z-p); Sp = Fc * Sp / C; Sz = Fc * Sz / C; end end
github
philippboehmsturm/antx-master
filtfilt.m
.m
antx-master/xspm8/external/fieldtrip/private/filtfilt.m
3,297
iso_8859_1
d01a26a827bc3379f05bbc57f46ac0a9
% Copyright (C) 1999 Paul Kienzle % Copyright (C) 2007 Francesco Potortì % Copyright (C) 2008 Luca Citi % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: y = filtfilt(b, a, x) % % Forward and reverse filter the signal. This corrects for phase % distortion introduced by a one-pass filter, though it does square the % magnitude response in the process. That's the theory at least. In % practice the phase correction is not perfect, and magnitude response % is distorted, particularly in the stop band. %% % Example % [b, a]=butter(3, 0.1); % 10 Hz low-pass filter % t = 0:0.01:1.0; % 1 second sample % x=sin(2*pi*t*2.3)+0.25*randn(size(t)); % 2.3 Hz sinusoid+noise % y = filtfilt(b,a,x); z = filter(b,a,x); % apply filter % plot(t,x,';data;',t,y,';filtfilt;',t,z,';filter;') % Changelog: % 2000 02 [email protected] % - pad with zeros to load up the state vector on filter reverse. % - add example % 2007 12 [email protected] % - use filtic to compute initial and final states % - work for multiple columns as well % 2008 12 [email protected] % - fixed instability issues with IIR filters and noisy inputs % - initial states computed according to Likhterov & Kopeika, 2003 % - use of a "reflection method" to reduce end effects % - added some basic tests % TODO: (pkienzle) My version seems to have similar quality to matlab, % but both are pretty bad. They do remove gross lag errors, though. function y = filtfilt(b, a, x) if (nargin ~= 3) usage('y=filtfilt(b,a,x)'); end rotate = (size(x, 1)==1); if rotate % a row vector x = x(:); % make it a column vector end lx = size(x,1); a = a(:).'; b = b(:).'; lb = length(b); la = length(a); n = max(lb, la); lrefl = 3 * (n - 1); if la < n, a(n) = 0; end if lb < n, b(n) = 0; end % Compute a the initial state taking inspiration from % Likhterov & Kopeika, 2003. "Hardware-efficient technique for % minimizing startup transients in Direct Form II digital filters" kdc = sum(b) / sum(a); if (abs(kdc) < inf) % neither NaN nor +/- Inf si = fliplr(cumsum(fliplr(b - kdc * a))); else si = zeros(size(a)); % fall back to zero initialization end si(1) = []; y = zeros(size(x)); for c = 1:size(x, 2) % filter all columns, one by one v = [2*x(1,c)-x((lrefl+1):-1:2,c); x(:,c); 2*x(end,c)-x((end-1):-1:end-lrefl,c)]; % a column vector % Do forward and reverse filtering v = filter(b,a,v,si*v(1)); % forward filter v = flipud(filter(b,a,flipud(v),si*v(end))); % reverse filter y(:,c) = v((lrefl+1):(lx+lrefl)); end if (rotate) % x was a row vector y = rot90(y); % rotate it back end
github
philippboehmsturm/antx-master
nanstd.m
.m
antx-master/xspm8/external/fieldtrip/private/nanstd.m
231
utf_8
0ff62b1c345b5ad76a9af59cf07c2983
% NANSTD provides a replacement for MATLAB's nanstd that is almost % compatible. % % For usage see STD. Note that the three-argument call with FLAG is not % supported. function Y = nanstd(varargin) Y = sqrt(nanvar(varargin{:}));
github
philippboehmsturm/antx-master
avw_img_write.m
.m
antx-master/xspm8/external/fieldtrip/private/avw_img_write.m
29,939
utf_8
f83bd0814830119805ffef580d768cdc
function avw_img_write(avw, fileprefix, IMGorient, machine, verbose) % avw_img_write - write Analyze image files (*.img) % % avw_img_write(avw,fileprefix,[IMGorient],[machine],[verbose]) % % avw.img - a 3D matrix of image data (double precision). % avw.hdr - a struct with image data parameters. If % not empty, this function calls avw_hdr_write. % % fileprefix - a string, the filename without the .img % extension. If empty, may use avw.fileprefix % % IMGorient - optional int, force writing of specified % orientation, with values: % % [], if empty, will use avw.hdr.hist.orient field % 0, transverse/axial unflipped (default, radiological) % 1, coronal unflipped % 2, sagittal unflipped % 3, transverse/axial flipped, left to right % 4, coronal flipped, anterior to posterior % 5, sagittal flipped, superior to inferior % % This function will set avw.hdr.hist.orient and write the % image data in a corresponding order. This function is % in alpha development, so it has not been exhaustively % tested (07/2003). See avw_img_read for more information % and documentation on the orientation option. % Orientations 3-5 are NOT recommended! They are part % of the Analyze format, but only used in Analyze % for faster raster graphics during movies. % % machine - a string, see machineformat in fread for details. % The default here is 'ieee-le'. % % verbose - the default is to output processing information to the command % window. If verbose = 0, this will not happen. % % Tip: to change the data type, set avw.hdr.dime.datatype to: % % 1 Binary ( 1 bit per voxel) % 2 Unsigned character ( 8 bits per voxel) % 4 Signed short ( 16 bits per voxel) % 8 Signed integer ( 32 bits per voxel) % 16 Floating point ( 32 bits per voxel) % 32 Complex, 2 floats ( 64 bits per voxel), not supported % 64 Double precision ( 64 bits per voxel) % 128 Red-Green-Blue (128 bits per voxel), not supported % % See also: avw_write, avw_hdr_write, % avw_read, avw_hdr_read, avw_img_read, avw_view % % $Revision: 7123 $ $Date: 2009/01/14 09:24:45 $ % Licence: GNU GPL, no express or implied warranties % History: 05/2002, [email protected] % The Analyze format is copyright % (c) Copyright, 1986-1995 % Biomedical Imaging Resource, Mayo Foundation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %------------------------------------------------------------------------ % Check inputs if ~exist('avw','var'), doc avw_img_write; error('...no input avw.'); elseif isempty(avw), error('...empty input avw.'); elseif ~isfield(avw,'img'), error('...empty input avw.img'); end if ~exist('fileprefix','var'), if isfield(avw,'fileprefix'), if ~isempty(avw.fileprefix), fileprefix = avw.fileprefix; else fileprefix = []; end else fileprefix = []; end end if isempty(fileprefix), [fileprefix, pathname, filterindex] = uiputfile('*.hdr','Specify an output Analyze .hdr file'); if pathname, cd(pathname); end if ~fileprefix, doc avw_img_write; error('no output .hdr file specified'); end end if findstr('.hdr',fileprefix), % fprintf('AVW_IMG_WRITE: Removing .hdr extension from ''%s''\n',fileprefix); fileprefix = strrep(fileprefix,'.hdr',''); end if findstr('.img',fileprefix), % fprintf('AVW_IMG_WRITE: Removing .img extension from ''%s''\n',fileprefix); fileprefix = strrep(fileprefix,'.img',''); end if ~exist('IMGorient','var'), IMGorient = ''; end if ~exist('machine','var'), machine = 'ieee-le'; end if ~exist('verbose','var'), verbose = 1; end if isempty(IMGorient), IMGorient = ''; end if isempty(machine), machine = 'ieee-le'; end if isempty(verbose), verbose = 1; end %------------------------------------------------------------------------ % MAIN if verbose, version = '[$Revision: 7123 $]'; fprintf('\nAVW_IMG_WRITE [v%s]\n',version(12:16)); tic; end fid = fopen(sprintf('%s.img',fileprefix),'w',machine); if fid < 0, msg = sprintf('Cannot open file %s.img\n',fileprefix); error(msg); else avw = write_image(fid,avw,fileprefix,IMGorient,machine,verbose); end if verbose, t=toc; fprintf('...done (%5.2f sec).\n\n',t); end % MUST write header after the image, to ensure any % orientation changes during image write are saved % in the header avw_hdr_write(avw,fileprefix,machine,verbose); return function avw_hdr_write(avw, fileprefix, machine, verbose) % AVW_HDR_WRITE - Write Analyze header file (*.hdr) % % avw_hdr_write(avw,[fileprefix],[machine],[verbose]) % % eg, avw_hdr_write(avw,'test'); % % avw - a struct with .hdr field, which itself is a struct, % containing all fields of an Analyze header. % For details, see avw_hdr_read.m % % fileprefix - a string, the filename without the .hdr extension. % If empty, may use avw.fileprefix % % machine - a string, see machineformat in fread for details. % The default here is 'ieee-le'. % % verbose - the default is to output processing information to the command % window. If verbose = 0, this will not happen. % % See also, AVW_HDR_READ AVW_HDR_MAKE % AVW_IMG_READ AVW_IMG_WRITE % % $Revision: 7123 $ $Date: 2009/01/14 09:24:45 $ % Licence: GNU GPL, no express or implied warranties % History: 05/2002, [email protected] % 02/2003, [email protected] % - more specific data history var sizes % - 02/2003 confirmed, Darren % % The Analyze format and c code below is copyright % (c) Copyright, 1986-1995 % Biomedical Imaging Resource, Mayo Foundation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist('verbose','var'), verbose = 1; end if ~exist('machine','var'), machine = 'ieee-le'; end if verbose, version = '[$Revision: 7123 $]'; fprintf('AVW_HDR_WRITE [v%s]\n',version(12:16)); tic; end %---------------------------------------------------------------------------- % Check inputs if ~exist('avw','var'), warning('...no input avw - calling avw_hdr_make\n'); avw = avw_hdr_make; elseif isempty(avw), warning('...empty input avw - calling avw_hdr_make\n'); avw = avw_hdr_make; elseif ~isfield(avw,'hdr'), warning('...empty input avw.hdr - calling avw_hdr_make\n'); avw = avw_hdr_make; end if ~isequal(avw.hdr.hk.sizeof_hdr,348), msg = sprintf('...avw.hdr.hk.sizeof_hdr must be 348!\n'); error(msg); end quit = 0; if ~exist('fileprefix','var'), if isfield(avw,'fileprefix'), if ~isempty(avw.fileprefix), fileprefix = avw.fileprefix; else, quit = 1; end else quit = 1; end if quit, helpwin avw_hdr_write; error('...no input fileprefix - see help avw_hdr_write\n\n'); return; end end if findstr('.hdr',fileprefix), % fprintf('AVW_HDR_WRITE: Removing .hdr extension from ''%s''\n',fileprefix); fileprefix = strrep(fileprefix,'.hdr',''); end %---------------------------------------------------------------------------- % MAIN if verbose, tic; end % % force volume to 4D if necessary; conforms to AVW standard. i lifted this % % code from mri_toolbox/avw_hdr_read.m and modified it just a little bit % % (using minDim = 4; etc) % minDim = 4; % currDim = double(avw.hdr.dime.dim(1)); % if ( currDim < minDim ) % % fprintf( 'Warning %s: Forcing %d dimensions in avw.hdr.dime.dim\n', ... % % mfilename, minDim ); % avw.hdr.dime.dim(1) = int16(minDim); % avw.hdr.dime.dim(currDim+2:minDim+1) = int16(1); % avw.hdr.dime.pixdim(1) = int16(minDim); % avw.hdr.dime.pixdim(currDim+2:minDim+1) = int16(1); % end; fid = fopen(sprintf('%s.hdr',fileprefix),'w',machine); if fid < 0, msg = sprintf('Cannot write to file %s.hdr\n',fileprefix); error(msg); else if verbose, fprintf('...writing %s Analyze header.\n',machine); end write_header(fid,avw,verbose); end if verbose, t=toc; fprintf('...done (%5.2f sec).\n\n',t); end return %----------------------------------------------------------------------------------- function avw = write_image(fid,avw,fileprefix,IMGorient,machine,verbose) % short int bitpix; /* Number of bits per pixel; 1, 8, 16, 32, or 64. */ % short int datatype /* Datatype for this image set */ % /*Acceptable values for datatype are*/ % #define DT_NONE 0 % #define DT_UNKNOWN 0 /*Unknown data type*/ % #define DT_BINARY 1 /*Binary ( 1 bit per voxel)*/ % #define DT_UNSIGNED_CHAR 2 /*Unsigned character ( 8 bits per voxel)*/ % #define DT_SIGNED_SHORT 4 /*Signed short (16 bits per voxel)*/ % #define DT_SIGNED_INT 8 /*Signed integer (32 bits per voxel)*/ % #define DT_FLOAT 16 /*Floating point (32 bits per voxel)*/ % #define DT_COMPLEX 32 /*Complex,2 floats (64 bits per voxel)/* % #define DT_DOUBLE 64 /*Double precision (64 bits per voxel)*/ % #define DT_RGB 128 /*A Red-Green-Blue datatype*/ % #define DT_ALL 255 /*Undocumented*/ switch double(avw.hdr.dime.datatype), case 1, avw.hdr.dime.bitpix = int16( 1); precision = 'bit1'; case 2, avw.hdr.dime.bitpix = int16( 8); precision = 'uchar'; case 4, avw.hdr.dime.bitpix = int16(16); precision = 'int16'; case 8, avw.hdr.dime.bitpix = int16(32); precision = 'int32'; case 16, avw.hdr.dime.bitpix = int16(32); precision = 'single'; case 32, error('...complex datatype not yet supported.\n'); case 64, avw.hdr.dime.bitpix = int16(64); precision = 'double'; case 128, error('...RGB datatype not yet supported.\n'); otherwise warning('...unknown datatype, using type 16 (32 bit floats).\n'); avw.hdr.dime.datatype = int16(16); avw.hdr.dime.bitpix = int16(32); precision = 'single'; end % write the .img file, depending on the .img orientation if verbose, fprintf('...writing %s precision Analyze image (%s).\n',precision,machine); end fseek(fid,0,'bof'); % The standard image orientation is axial unflipped if isempty(avw.hdr.hist.orient), msg = [ '...avw.hdr.hist.orient ~= 0.\n',... ' This function assumes the input avw.img is\n',... ' in axial unflipped orientation in memory. This is\n',... ' created by the avw_img_read function, which converts\n',... ' any input file image to axial unflipped in memory.\n']; warning(msg) end if isempty(IMGorient), if verbose, fprintf('...no IMGorient specified, using avw.hdr.hist.orient value.\n'); end IMGorient = double(avw.hdr.hist.orient); end if ~isfinite(IMGorient), if verbose, fprintf('...IMGorient is not finite!\n'); end IMGorient = 99; end switch IMGorient, case 0, % transverse/axial unflipped % For the 'transverse unflipped' type, the voxels are stored with % Pixels in 'x' axis (varies fastest) - from patient right to left % Rows in 'y' axis - from patient posterior to anterior % Slices in 'z' axis - from patient inferior to superior if verbose, fprintf('...writing axial unflipped\n'); end avw.hdr.hist.orient = uint8(0); SliceDim = double(avw.hdr.dime.dim(4)); % z RowDim = double(avw.hdr.dime.dim(3)); % y PixelDim = double(avw.hdr.dime.dim(2)); % x SliceSz = double(avw.hdr.dime.pixdim(4)); RowSz = double(avw.hdr.dime.pixdim(3)); PixelSz = double(avw.hdr.dime.pixdim(2)); x = 1:PixelDim; for z = 1:SliceDim, for y = 1:RowDim, fwrite(fid,avw.img(x,y,z),precision); end end case 1, % coronal unflipped % For the 'coronal unflipped' type, the voxels are stored with % Pixels in 'x' axis (varies fastest) - from patient right to left % Rows in 'z' axis - from patient inferior to superior % Slices in 'y' axis - from patient posterior to anterior if verbose, fprintf('...writing coronal unflipped\n'); end avw.hdr.hist.orient = uint8(1); SliceDim = double(avw.hdr.dime.dim(3)); % y RowDim = double(avw.hdr.dime.dim(4)); % z PixelDim = double(avw.hdr.dime.dim(2)); % x SliceSz = double(avw.hdr.dime.pixdim(3)); RowSz = double(avw.hdr.dime.pixdim(4)); PixelSz = double(avw.hdr.dime.pixdim(2)); x = 1:PixelDim; for y = 1:SliceDim, for z = 1:RowDim, fwrite(fid,avw.img(x,y,z),precision); end end case 2, % sagittal unflipped % For the 'sagittal unflipped' type, the voxels are stored with % Pixels in 'y' axis (varies fastest) - from patient posterior to anterior % Rows in 'z' axis - from patient inferior to superior % Slices in 'x' axis - from patient right to left if verbose, fprintf('...writing sagittal unflipped\n'); end avw.hdr.hist.orient = uint8(2); SliceDim = double(avw.hdr.dime.dim(2)); % x RowDim = double(avw.hdr.dime.dim(4)); % z PixelDim = double(avw.hdr.dime.dim(3)); % y SliceSz = double(avw.hdr.dime.pixdim(2)); RowSz = double(avw.hdr.dime.pixdim(4)); PixelSz = double(avw.hdr.dime.pixdim(3)); y = 1:PixelDim; for x = 1:SliceDim, for z = 1:RowDim, fwrite(fid,avw.img(x,y,z),precision); end end case 3, % transverse/axial flipped % For the 'transverse flipped' type, the voxels are stored with % Pixels in 'x' axis (varies fastest) - from patient right to left % Rows in 'y' axis - from patient anterior to posterior* % Slices in 'z' axis - from patient inferior to superior if verbose, fprintf('...writing axial flipped (+Y from Anterior to Posterior)\n'); end avw.hdr.hist.orient = uint8(3); SliceDim = double(avw.hdr.dime.dim(4)); % z RowDim = double(avw.hdr.dime.dim(3)); % y PixelDim = double(avw.hdr.dime.dim(2)); % x SliceSz = double(avw.hdr.dime.pixdim(4)); RowSz = double(avw.hdr.dime.pixdim(3)); PixelSz = double(avw.hdr.dime.pixdim(2)); x = 1:PixelDim; for z = 1:SliceDim, for y = RowDim:-1:1, % flipped in Y fwrite(fid,avw.img(x,y,z),precision); end end case 4, % coronal flipped % For the 'coronal flipped' type, the voxels are stored with % Pixels in 'x' axis (varies fastest) - from patient right to left % Rows in 'z' axis - from patient inferior to superior % Slices in 'y' axis - from patient anterior to posterior if verbose, fprintf('...writing coronal flipped (+Z from Superior to Inferior)\n'); end avw.hdr.hist.orient = uint8(4); SliceDim = double(avw.hdr.dime.dim(3)); % y RowDim = double(avw.hdr.dime.dim(4)); % z PixelDim = double(avw.hdr.dime.dim(2)); % x SliceSz = double(avw.hdr.dime.pixdim(3)); RowSz = double(avw.hdr.dime.pixdim(4)); PixelSz = double(avw.hdr.dime.pixdim(2)); x = 1:PixelDim; for y = 1:SliceDim, for z = RowDim:-1:1, fwrite(fid,avw.img(x,y,z),precision); end end case 5, % sagittal flipped % For the 'sagittal flipped' type, the voxels are stored with % Pixels in 'y' axis (varies fastest) - from patient posterior to anterior % Rows in 'z' axis - from patient superior to inferior % Slices in 'x' axis - from patient right to left if verbose, fprintf('...writing sagittal flipped (+Z from Superior to Inferior)\n'); end avw.hdr.hist.orient = uint8(5); SliceDim = double(avw.hdr.dime.dim(2)); % x RowDim = double(avw.hdr.dime.dim(4)); % z PixelDim = double(avw.hdr.dime.dim(3)); % y SliceSz = double(avw.hdr.dime.pixdim(2)); RowSz = double(avw.hdr.dime.pixdim(4)); PixelSz = double(avw.hdr.dime.pixdim(3)); y = 1:PixelDim; for x = 1:SliceDim, for z = RowDim:-1:1, % superior to inferior fwrite(fid,avw.img(x,y,z),precision); end end otherwise, % transverse/axial unflipped % For the 'transverse unflipped' type, the voxels are stored with % Pixels in 'x' axis (varies fastest) - from patient right to left % Rows in 'y' axis - from patient posterior to anterior % Slices in 'z' axis - from patient inferior to superior if verbose, fprintf('...unknown orientation specified, assuming default axial unflipped\n'); end avw.hdr.hist.orient = uint8(0); SliceDim = double(avw.hdr.dime.dim(4)); % z RowDim = double(avw.hdr.dime.dim(3)); % y PixelDim = double(avw.hdr.dime.dim(2)); % x SliceSz = double(avw.hdr.dime.pixdim(4)); RowSz = double(avw.hdr.dime.pixdim(3)); PixelSz = double(avw.hdr.dime.pixdim(2)); x = 1:PixelDim; for z = 1:SliceDim, for y = 1:RowDim, fwrite(fid,avw.img(x,y,z),precision); end end end fclose(fid); % Update the header avw.hdr.dime.dim(2:4) = int16([PixelDim,RowDim,SliceDim]); avw.hdr.dime.pixdim(2:4) = single([PixelSz,RowSz,SliceSz]); return %---------------------------------------------------------------------------- function write_header(fid,avw,verbose) header_key(fid,avw.hdr.hk); image_dimension(fid,avw.hdr.dime); data_history(fid,avw.hdr.hist); % check the file size is 348 bytes fbytes = ftell(fid); fclose(fid); if ~isequal(fbytes,348), msg = sprintf('...file size is not 348 bytes!\n'); warning(msg); end return %---------------------------------------------------------------------------- function header_key(fid,hk) % Original header structures - ANALYZE 7.5 % struct header_key /* header key */ % { /* off + size */ % int sizeof_hdr /* 0 + 4 */ % char data_type[10]; /* 4 + 10 */ % char db_name[18]; /* 14 + 18 */ % int extents; /* 32 + 4 */ % short int session_error; /* 36 + 2 */ % char regular; /* 38 + 1 */ % char hkey_un0; /* 39 + 1 */ % }; /* total=40 bytes */ fseek(fid,0,'bof'); fwrite(fid, hk.sizeof_hdr(1), 'int32'); % must be 348! data_type = sprintf('%-10s',hk.data_type); % ensure it is 10 chars fwrite(fid, hk.data_type(1:10), 'uchar'); db_name = sprintf('%-18s',hk.db_name); % ensure it is 18 chars fwrite(fid, db_name(1:18), 'uchar'); fwrite(fid, hk.extents(1), 'int32'); fwrite(fid, hk.session_error(1),'int16'); regular = sprintf('%1s',hk.regular); % ensure it is 1 char fwrite(fid, regular(1), 'uchar'); % might be uint8 %hkey_un0 = sprintf('%1s',hk.hkey_un0); % ensure it is 1 char %fwrite(fid, hkey_un0(1), 'uchar'); fwrite(fid, hk.hkey_un0(1), 'uint8'); % >Would you set hkey_un0 as char or uint8? % Really doesn't make any difference. As far as anyone here can remember, % this was just to pad to an even byte boundary for that structure. I guess % I'd suggest setting it to a uint8 value of 0 (i.e, truly zero-valued) so % that it doesn't look like anything important! % Denny <[email protected]> return %---------------------------------------------------------------------------- function image_dimension(fid,dime) %struct image_dimension % { /* off + size */ % short int dim[8]; /* 0 + 16 */ % char vox_units[4]; /* 16 + 4 */ % char cal_units[8]; /* 20 + 8 */ % short int unused1; /* 28 + 2 */ % short int datatype; /* 30 + 2 */ % short int bitpix; /* 32 + 2 */ % short int dim_un0; /* 34 + 2 */ % float pixdim[8]; /* 36 + 32 */ % /* % pixdim[] specifies the voxel dimensions: % pixdim[1] - voxel width % pixdim[2] - voxel height % pixdim[3] - interslice distance % ..etc % */ % float vox_offset; /* 68 + 4 */ % float roi_scale; /* 72 + 4 */ % float funused1; /* 76 + 4 */ % float funused2; /* 80 + 4 */ % float cal_max; /* 84 + 4 */ % float cal_min; /* 88 + 4 */ % int compressed; /* 92 + 4 */ % int verified; /* 96 + 4 */ % int glmax; /* 100 + 4 */ % int glmin; /* 104 + 4 */ % }; /* total=108 bytes */ fwrite(fid, dime.dim(1:8), 'int16'); fwrite(fid, dime.vox_units(1:4),'uchar'); fwrite(fid, dime.cal_units(1:8),'uchar'); fwrite(fid, dime.unused1(1), 'int16'); fwrite(fid, dime.datatype(1), 'int16'); fwrite(fid, dime.bitpix(1), 'int16'); fwrite(fid, dime.dim_un0(1), 'int16'); fwrite(fid, dime.pixdim(1:8), 'float32'); fwrite(fid, dime.vox_offset(1), 'float32'); % Ensure compatibility with SPM (according to MRIcro) if dime.roi_scale == 0, dime.roi_scale = 0.00392157; end fwrite(fid, dime.roi_scale(1), 'float32'); fwrite(fid, dime.funused1(1), 'float32'); fwrite(fid, dime.funused2(1), 'float32'); fwrite(fid, dime.cal_max(1), 'float32'); fwrite(fid, dime.cal_min(1), 'float32'); fwrite(fid, dime.compressed(1), 'int32'); fwrite(fid, dime.verified(1), 'int32'); fwrite(fid, dime.glmax(1), 'int32'); fwrite(fid, dime.glmin(1), 'int32'); return %---------------------------------------------------------------------------- function data_history(fid,hist) % Original header structures - ANALYZE 7.5 %struct data_history % { /* off + size */ % char descrip[80]; /* 0 + 80 */ % char aux_file[24]; /* 80 + 24 */ % char orient; /* 104 + 1 */ % char originator[10]; /* 105 + 10 */ % char generated[10]; /* 115 + 10 */ % char scannum[10]; /* 125 + 10 */ % char patient_id[10]; /* 135 + 10 */ % char exp_date[10]; /* 145 + 10 */ % char exp_time[10]; /* 155 + 10 */ % char hist_un0[3]; /* 165 + 3 */ % int views /* 168 + 4 */ % int vols_added; /* 172 + 4 */ % int start_field; /* 176 + 4 */ % int field_skip; /* 180 + 4 */ % int omax; /* 184 + 4 */ % int omin; /* 188 + 4 */ % int smax; /* 192 + 4 */ % int smin; /* 196 + 4 */ % }; /* total=200 bytes */ descrip = sprintf('%-80s', hist.descrip); % 80 chars aux_file = sprintf('%-24s', hist.aux_file); % 24 chars originator = sprintf('%-10s', hist.originator); % 10 chars generated = sprintf('%-10s', hist.generated); % 10 chars scannum = sprintf('%-10s', hist.scannum); % 10 chars patient_id = sprintf('%-10s', hist.patient_id); % 10 chars exp_date = sprintf('%-10s', hist.exp_date); % 10 chars exp_time = sprintf('%-10s', hist.exp_time); % 10 chars hist_un0 = sprintf( '%-3s', hist.hist_un0); % 3 chars % --- % The following should not be necessary, but I actually % found one instance where it was, so this totally anal % retentive approach became necessary, despite the % apparently elegant solution above to ensuring that variables % are the right length. if length(descrip) < 80, paddingN = 80-length(descrip); padding = char(repmat(double(' '),1,paddingN)); descrip = [descrip,padding]; end if length(aux_file) < 24, paddingN = 24-length(aux_file); padding = char(repmat(double(' '),1,paddingN)); aux_file = [aux_file,padding]; end if length(originator) < 10, paddingN = 10-length(originator); padding = char(repmat(double(' '),1,paddingN)); originator = [originator, padding]; end if length(generated) < 10, paddingN = 10-length(generated); padding = char(repmat(double(' '),1,paddingN)); generated = [generated, padding]; end if length(scannum) < 10, paddingN = 10-length(scannum); padding = char(repmat(double(' '),1,paddingN)); scannum = [scannum, padding]; end if length(patient_id) < 10, paddingN = 10-length(patient_id); padding = char(repmat(double(' '),1,paddingN)); patient_id = [patient_id, padding]; end if length(exp_date) < 10, paddingN = 10-length(exp_date); padding = char(repmat(double(' '),1,paddingN)); exp_date = [exp_date, padding]; end if length(exp_time) < 10, paddingN = 10-length(exp_time); padding = char(repmat(double(' '),1,paddingN)); exp_time = [exp_time, padding]; end if length(hist_un0) < 10, paddingN = 10-length(hist_un0); padding = char(repmat(double(' '),1,paddingN)); hist_un0 = [hist_un0, padding]; end % -- if you thought that was anal, try this; % -- lets check for unusual ASCII char values! if find(double(descrip)>128), indexStrangeChar = find(double(descrip)>128); descrip(indexStrangeChar) = ' '; end if find(double(aux_file)>128), indexStrangeChar = find(double(aux_file)>128); aux_file(indexStrangeChar) = ' '; end if find(double(originator)>128), indexStrangeChar = find(double(originator)>128); originator(indexStrangeChar) = ' '; end if find(double(generated)>128), indexStrangeChar = find(double(generated)>128); generated(indexStrangeChar) = ' '; end if find(double(scannum)>128), indexStrangeChar = find(double(scannum)>128); scannum(indexStrangeChar) = ' '; end if find(double(patient_id)>128), indexStrangeChar = find(double(patient_id)>128); patient_id(indexStrangeChar) = ' '; end if find(double(exp_date)>128), indexStrangeChar = find(double(exp_date)>128); exp_date(indexStrangeChar) = ' '; end if find(double(exp_time)>128), indexStrangeChar = find(double(exp_time)>128); exp_time(indexStrangeChar) = ' '; end if find(double(hist_un0)>128), indexStrangeChar = find(double(hist_un0)>128); hist_un0(indexStrangeChar) = ' '; end % --- finally, we write the fields fwrite(fid, descrip(1:80), 'uchar'); fwrite(fid, aux_file(1:24), 'uchar'); %orient = sprintf( '%1s', hist.orient); % 1 char %fwrite(fid, orient(1), 'uchar'); fwrite(fid, hist.orient(1), 'uint8'); % see note below on char fwrite(fid, originator(1:10), 'uchar'); fwrite(fid, generated(1:10), 'uchar'); fwrite(fid, scannum(1:10), 'uchar'); fwrite(fid, patient_id(1:10), 'uchar'); fwrite(fid, exp_date(1:10), 'uchar'); fwrite(fid, exp_time(1:10), 'uchar'); fwrite(fid, hist_un0(1:3), 'uchar'); fwrite(fid, hist.views(1), 'int32'); fwrite(fid, hist.vols_added(1), 'int32'); fwrite(fid, hist.start_field(1),'int32'); fwrite(fid, hist.field_skip(1), 'int32'); fwrite(fid, hist.omax(1), 'int32'); fwrite(fid, hist.omin(1), 'int32'); fwrite(fid, hist.smax(1), 'int32'); fwrite(fid, hist.smin(1), 'int32'); return % Note on using char: % The 'char orient' field in the header is intended to % hold simply an 8-bit unsigned integer value, not the ASCII representation % of the character for that value. A single 'char' byte is often used to % represent an integer value in Analyze if the known value range doesn't % go beyond 0-255 - saves a byte over a short int, which may not mean % much in today's computing environments, but given that this format % has been around since the early 1980's, saving bytes here and there on % older systems was important! In this case, 'char' simply provides the % byte of storage - not an indicator of the format for what is stored in % this byte. Generally speaking, anytime a single 'char' is used, it is % probably meant to hold an 8-bit integer value, whereas if this has % been dimensioned as an array, then it is intended to hold an ASCII % character string, even if that was only a single character. % Denny <[email protected]> % See other notes in avw_hdr_read
github
philippboehmsturm/antx-master
bilinear.m
.m
antx-master/xspm8/external/fieldtrip/private/bilinear.m
4,339
utf_8
17250db27826cad87fa3384823e1242f
% Copyright (C) 1999 Paul Kienzle % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % usage: [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T) % [Zb, Za] = bilinear(Sb, Sa, T) % % Transform a s-plane filter specification into a z-plane % specification. Filters can be specified in either zero-pole-gain or % transfer function form. The input form does not have to match the % output form. 1/T is the sampling frequency represented in the z plane. % % Note: this differs from the bilinear function in the signal processing % toolbox, which uses 1/T rather than T. % % Theory: Given a piecewise flat filter design, you can transform it % from the s-plane to the z-plane while maintaining the band edges by % means of the bilinear transform. This maps the left hand side of the % s-plane into the interior of the unit circle. The mapping is highly % non-linear, so you must design your filter with band edges in the % s-plane positioned at 2/T tan(w*T/2) so that they will be positioned % at w after the bilinear transform is complete. % % The following table summarizes the transformation: % % +---------------+-----------------------+----------------------+ % | Transform | Zero at x | Pole at x | % | H(S) | H(S) = S-x | H(S)=1/(S-x) | % +---------------+-----------------------+----------------------+ % | 2 z-1 | zero: (2+xT)/(2-xT) | zero: -1 | % | S -> - --- | pole: -1 | pole: (2+xT)/(2-xT) | % | T z+1 | gain: (2-xT)/T | gain: (2-xT)/T | % +---------------+-----------------------+----------------------+ % % With tedious algebra, you can derive the above formulae yourself by % substituting the transform for S into H(S)=S-x for a zero at x or % H(S)=1/(S-x) for a pole at x, and converting the result into the % form: % % H(Z)=g prod(Z-Xi)/prod(Z-Xj) % % Please note that a pole and a zero at the same place exactly cancel. % This is significant since the bilinear transform creates numerous % extra poles and zeros, most of which cancel. Those which do not % cancel have a 'fill-in' effect, extending the shorter of the sets to % have the same number of as the longer of the sets of poles and zeros % (or at least split the difference in the case of the band pass % filter). There may be other opportunistic cancellations but I will % not check for them. % % Also note that any pole on the unit circle or beyond will result in % an unstable filter. Because of cancellation, this will only happen % if the number of poles is smaller than the number of zeros. The % analytic design methods all yield more poles than zeros, so this will % not be a problem. % % References: % % Proakis & Manolakis (1992). Digital Signal Processing. New York: % Macmillan Publishing Company. % Author: Paul Kienzle <[email protected]> function [Zz, Zp, Zg] = bilinear(Sz, Sp, Sg, T) if nargin==3 T = Sg; [Sz, Sp, Sg] = tf2zp(Sz, Sp); elseif nargin~=4 usage('[Zz, Zp, Zg]=bilinear(Sz,Sp,Sg,T) or [Zb, Za]=blinear(Sb,Sa,T)'); end; p = length(Sp); z = length(Sz); if z > p || p==0 error('bilinear: must have at least as many poles as zeros in s-plane'); end % ---------------- ------------------------- ------------------------ % Bilinear zero: (2+xT)/(2-xT) pole: (2+xT)/(2-xT) % 2 z-1 pole: -1 zero: -1 % S -> - --- gain: (2-xT)/T gain: (2-xT)/T % T z+1 % ---------------- ------------------------- ------------------------ Zg = real(Sg * prod((2-Sz*T)/T) / prod((2-Sp*T)/T)); Zp = (2+Sp*T)./(2-Sp*T); if isempty(Sz) Zz = -ones(size(Zp)); else Zz = [(2+Sz*T)./(2-Sz*T)]; Zz = postpad(Zz, p, -1); end if nargout==2, [Zz, Zp] = zp2tf(Zz, Zp, Zg); end
github
philippboehmsturm/antx-master
select_channel_list.m
.m
antx-master/xspm8/external/fieldtrip/private/select_channel_list.m
5,910
utf_8
51149b83e6eca7c0510e5a740c7f87e7
function [select] = select_channel_list(label, select, titlestr); % SELECT_CHANNEL_LIST presents a dialog for selecting multiple elements % from a cell array with strings, such as the labels of EEG channels. % The dialog presents two columns with an add and remove mechanism. % % select = select_channel_list(label, initial, titlestr) % % with % initial indices of channels that are initially selected % label cell array with channel labels (strings) % titlestr title for dialog (optional) % and % select indices of selected channels % % If the user presses cancel, the initial selection will be returned. % Copyright (C) 2003, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: select_channel_list.m 7123 2012-12-06 21:21:38Z roboos $ if nargin<3 titlestr = 'Select'; end pos = get(0,'DefaultFigurePosition'); pos(3:4) = [290 300]; dlg = dialog('Name', titlestr, 'Position', pos); select = select(:)'; % ensure that it is a row array userdata.label = label; userdata.select = select; userdata.unselect = setdiff(1:length(label), select); set(dlg, 'userdata', userdata); uicontrol(dlg, 'style', 'text', 'position', [ 10 240+20 80 20], 'string', 'unselected'); uicontrol(dlg, 'style', 'text', 'position', [200 240+20 80 20], 'string', 'selected '); uicontrol(dlg, 'style', 'listbox', 'position', [ 10 40+20 80 200], 'min', 0, 'max', 2, 'tag', 'lbunsel') uicontrol(dlg, 'style', 'listbox', 'position', [200 40+20 80 200], 'min', 0, 'max', 2, 'tag', 'lbsel') uicontrol(dlg, 'style', 'pushbutton', 'position', [105 175+20 80 20], 'string', 'add all >' , 'callback', @label_addall); uicontrol(dlg, 'style', 'pushbutton', 'position', [105 145+20 80 20], 'string', 'add >' , 'callback', @label_add); uicontrol(dlg, 'style', 'pushbutton', 'position', [105 115+20 80 20], 'string', '< remove' , 'callback', @label_remove); uicontrol(dlg, 'style', 'pushbutton', 'position', [105 85+20 80 20], 'string', '< remove all', 'callback', @label_removeall); uicontrol(dlg, 'style', 'pushbutton', 'position', [ 55 10 80 20], 'string', 'Cancel', 'callback', 'close'); uicontrol(dlg, 'style', 'pushbutton', 'position', [155 10 80 20], 'string', 'OK', 'callback', 'uiresume'); label_redraw(dlg); % wait untill the dialog is closed or the user presses OK/Cancel uiwait(dlg); if ishandle(dlg) % the user pressed OK, return the selection from the dialog userdata = get(dlg, 'userdata'); select = userdata.select; close(dlg); return else % the user pressed Cancel or closed the dialog, return the initial selection return end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_redraw(h); userdata = get(h, 'userdata'); set(findobj(h, 'tag', 'lbsel' ), 'string', userdata.label(userdata.select)); set(findobj(h, 'tag', 'lbunsel'), 'string', userdata.label(userdata.unselect)); % set the active element in the select listbox, based on the previous active element tmp = min(get(findobj(h, 'tag', 'lbsel'), 'value')); tmp = min(tmp, length(get(findobj(h, 'tag', 'lbsel'), 'string'))); if isempty(tmp) | tmp==0 tmp = 1; end set(findobj(h, 'tag', 'lbsel' ), 'value', tmp); % set the active element in the unselect listbox, based on the previous active element tmp = min(get(findobj(h, 'tag', 'lbunsel'), 'value')); tmp = min(tmp, length(get(findobj(h, 'tag', 'lbunsel'), 'string'))); if isempty(tmp) | tmp==0 tmp = 1; end set(findobj(h, 'tag', 'lbunsel' ), 'value', tmp); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_addall(h, eventdata, handles, varargin); h = get(h, 'parent'); userdata = get(h, 'userdata'); userdata.select = 1:length(userdata.label); userdata.unselect = []; set(findobj(h, 'tag', 'lbunsel' ), 'value', 1); set(h, 'userdata', userdata); label_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_removeall(h, eventdata, handles, varargin); h = get(h, 'parent'); userdata = get(h, 'userdata'); userdata.unselect = 1:length(userdata.label); userdata.select = []; set(findobj(h, 'tag', 'lbsel' ), 'value', 1); set(h, 'userdata', userdata); label_redraw(h); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_add(h, eventdata, handles, varargin); h = get(h, 'parent'); userdata = get(h, 'userdata'); if ~isempty(userdata.unselect) add = userdata.unselect(get(findobj(h, 'tag', 'lbunsel' ), 'value')); userdata.select = sort([userdata.select add]); userdata.unselect = sort(setdiff(userdata.unselect, add)); set(h, 'userdata', userdata); label_redraw(h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label_remove(h, eventdata, handles, varargin); h = get(h, 'parent'); userdata = get(h, 'userdata'); if ~isempty(userdata.select) remove = userdata.select(get(findobj(h, 'tag', 'lbsel' ), 'value')); userdata.select = sort(setdiff(userdata.select, remove)); userdata.unselect = sort([userdata.unselect remove]); set(h, 'userdata', userdata); label_redraw(h); end
github
philippboehmsturm/antx-master
artifact_viewer.m
.m
antx-master/xspm8/external/fieldtrip/private/artifact_viewer.m
6,725
utf_8
0045c4b5518e2d509c8d0d9892e389c2
function artifact_viewer(cfg, artcfg, zval, artval, zindx, inputdata); % ARTIFACT_VIEWER is a subfunction that reads a segment of data % (one channel only) and displays it together with the cummulated % z-value % Copyright (C) 2004-2006, Jan-Mathijs Schoffelen & Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: artifact_viewer.m 7123 2012-12-06 21:21:38Z roboos $ dat.cfg = cfg; dat.artcfg = artcfg; if nargin == 5 % no data is given dat.hdr = ft_read_header(cfg.headerfile); elseif nargin == 6 % data is given dat.hdr = ft_fetch_header(inputdata); % used name inputdata iso data, because data is already used later in this function dat.inputdata = inputdata; % to be able to get inputdata into h (by guidata) end dat.trlop = 1; dat.zval = zval; dat.artval = artval; dat.zindx = zindx; dat.stop = 0; dat.numtrl = size(cfg.trl,1); dat.trialok = zeros(1,dat.numtrl); for trlop=1:dat.numtrl dat.trialok(trlop) = ~any(artval{trlop}); end h = gcf; guidata(h,dat); uicontrol(gcf,'units','pixels','position',[5 5 40 18],'String','stop','Callback',@stop); uicontrol(gcf,'units','pixels','position',[50 5 25 18],'String','<','Callback',@prevtrial); uicontrol(gcf,'units','pixels','position',[75 5 25 18],'String','>','Callback',@nexttrial); uicontrol(gcf,'units','pixels','position',[105 5 25 18],'String','<<','Callback',@prev10trial); uicontrol(gcf,'units','pixels','position',[130 5 25 18],'String','>>','Callback',@next10trial); uicontrol(gcf,'units','pixels','position',[160 5 50 18],'String','<artfct','Callback',@prevartfct); uicontrol(gcf,'units','pixels','position',[210 5 50 18],'String','artfct>','Callback',@nextartfct); while ishandle(h), dat = guidata(h); if dat.stop == 0, read_and_plot(h); uiwait; else break end end if ishandle(h) close(h); end %------------ %subfunctions %------------ function read_and_plot(h) vlinecolor = [0 0 0]; dat = guidata(h); % make a local copy of the relevant variables trlop = dat.trlop; zval = dat.zval{trlop}; artval = dat.artval{trlop}; zindx = dat.zindx{trlop}; cfg = dat.cfg; artcfg = dat.artcfg; hdr = dat.hdr; trl = dat.artcfg.trl; trlpadsmp = round(artcfg.trlpadding*hdr.Fs); % determine the channel with the highest z-value [dum, indx] = max(zval); sgnind = zindx(indx); iscontinuous = 1; if isfield(dat, 'inputdata') data = ft_fetch_data(dat.inputdata, 'header', hdr, 'begsample', trl(trlop,1), 'endsample', trl(trlop,2), 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no')); else data = ft_read_data(cfg.datafile, 'header', hdr, 'begsample', trl(trlop,1), 'endsample', trl(trlop,2), 'chanindx', sgnind, 'checkboundary', strcmp(cfg.continuous,'no')); end % data = preproc(data, channel, hdr.Fs, artfctdef, [], fltpadding, fltpadding); str = sprintf('trial %3d, channel %s', dat.trlop, hdr.label{sgnind}); fprintf('showing %s\n', str); % plot z-values in lower subplot subplot(2,1,2); cla hold on xval = trl(trlop,1):trl(trlop,2); if trlpadsmp sel = 1:trlpadsmp; h = plot(xval(sel), zval(sel)); set(h, 'color', [0.5 0.5 1]); % plot the trialpadding in another color sel = trlpadsmp:(length(data)-trlpadsmp); plot(xval(sel), zval(sel), 'b'); sel = (length(data)-trlpadsmp):length(data); h = plot(xval(sel), zval(sel)); set(h, 'color', [0.5 0.5 1]); % plot the trialpadding in another color vline(xval( 1)+trlpadsmp, 'color', vlinecolor); vline(xval(end)-trlpadsmp, 'color', vlinecolor); else plot(xval, zval, 'b'); end % draw a line at the threshold level hline(artcfg.cutoff, 'color', 'r', 'linestyle', ':'); % make the artefact part red zval(~artval) = nan; plot(xval, zval, 'r-'); hold off xlabel('samples'); ylabel('zscore'); % plot data of most aberrant channel in upper subplot subplot(2,1,1); cla hold on if trlpadsmp sel = 1:trlpadsmp; h = plot(xval(sel), data(sel)); set(h, 'color', [0.5 0.5 1]); % plot the trialpadding in another color sel = trlpadsmp:(length(data)-trlpadsmp); plot(xval(sel), data(sel), 'b'); sel = (length(data)-trlpadsmp):length(data); h = plot(xval(sel), data(sel)); set(h, 'color', [0.5 0.5 1]); % plot the trialpadding in another color vline(xval( 1)+trlpadsmp, 'color', vlinecolor); vline(xval(end)-trlpadsmp, 'color', vlinecolor); else plot(xval, data, 'b'); end data(~artval) = nan; plot(xval, data, 'r-'); hold off xlabel('samples'); ylabel('uV or Tesla'); title(str); function varargout = nexttrial(h, eventdata, handles, varargin) dat = guidata(h); if dat.trlop < dat.numtrl, dat.trlop = dat.trlop + 1; end; guidata(h,dat); uiresume; function varargout = next10trial(h, eventdata, handles, varargin) dat = guidata(h); if dat.trlop < dat.numtrl - 10, dat.trlop = dat.trlop + 10; else dat.trlop = dat.numtrl; end; guidata(h,dat); uiresume; function varargout = prevtrial(h, eventdata, handles, varargin) dat = guidata(h); if dat.trlop > 1, dat.trlop = dat.trlop - 1; else dat.trlop = 1; end; guidata(h,dat); uiresume; function varargout = prev10trial(h, eventdata, handles, varargin) dat = guidata(h); if dat.trlop > 10, dat.trlop = dat.trlop - 10; else dat.trlop = 1; end; guidata(h,dat); uiresume; function varargout = nextartfct(h, eventdata, handles, varargin) dat = guidata(h); artfctindx = find(dat.trialok == 0); sel = find(artfctindx > dat.trlop); if ~isempty(sel) dat.trlop = artfctindx(sel(1)); else dat.trlop = dat.trlop; end guidata(h,dat); uiresume; function varargout = prevartfct(h, eventdata, handles, varargin) dat = guidata(h); artfctindx = find(dat.trialok == 0); sel = find(artfctindx < dat.trlop); if ~isempty(sel) dat.trlop = artfctindx(sel(end)); else dat.trlop = dat.trlop; end guidata(h,dat); uiresume; function varargout = stop(h, eventdata, handles, varargin) dat = guidata(h); dat.stop = 1; guidata(h,dat); uiresume; function vsquare(x1, x2, c) abc = axis; y1 = abc(3); y2 = abc(4); x = [x1 x2 x2 x1 x1]; y = [y1 y1 y2 y2 y1]; z = [-1 -1 -1 -1 -1]; h = patch(x, y, z, c); set(h, 'edgecolor', c)
github
philippboehmsturm/antx-master
rejectvisual_summary.m
.m
antx-master/xspm8/external/fieldtrip/private/rejectvisual_summary.m
19,077
utf_8
37d0a7a58af84def37cd501806ceeca4
function [chansel, trlsel, cfg] = rejectvisual_summary(cfg, data) % REJECTVISUAL_SUMMARY: subfunction for ft_rejectvisual % determine the initial selection of trials and channels nchan = length(data.label); ntrl = length(data.trial); cfg.channel = ft_channelselection(cfg.channel, data.label); trlsel = true(1,ntrl); chansel = false(1,nchan); chansel(match_str(data.label, cfg.channel)) = 1; % compute the sampling frequency from the first two timepoints fsample = 1/mean(diff(data.time{1})); % select the specified latency window from the data % here it is done BEFORE filtering and metric computation for i=1:ntrl begsample = nearest(data.time{i}, cfg.latency(1)); endsample = nearest(data.time{i}, cfg.latency(2)); data.time{i} = data.time{i}(begsample:endsample); data.trial{i} = data.trial{i}(:,begsample:endsample); end % compute the offset from the time axes offset = zeros(ntrl,1); for i=1:ntrl offset(i) = time2offset(data.time{i}, fsample); end % set up guidata info h = figure(); info = []; info.data = data; info.cfg = cfg; info.metric = cfg.metric; info.ntrl = ntrl; info.nchan = nchan; info.trlsel = trlsel; info.chansel = chansel; info.fsample = fsample; info.offset = offset; info.quit = 0; guidata(h,info); % set up display interactive = 1; info = guidata(h); % make the figure large enough to hold stuff set(h,'Position',[50 350 800 500]); % define three plots info.axes(1) = axes('position',[0.100 0.650 0.375 0.300]); % summary plot info.axes(2) = axes('position',[0.575 0.650 0.375 0.300]); % channels info.axes(3) = axes('position',[0.100 0.250 0.375 0.300]); % trials % callback function (for toggling trials/channels) is set later, so that % the user cannot try to toggle trials while nothing is present on the % plots % set up radio buttons for choosing metric bgcolor = get(h,'color'); g = uibuttongroup('Position',[0.525 0.275 0.375 0.250 ],'bordertype','none','backgroundcolor',bgcolor); r(1) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 7/7 0.40 0.15 ],'Style','radio','backgroundcolor',bgcolor,'string','var','HandleVisibility','off'); r(2) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 6/7 0.40 0.15 ],'Style','radio','backgroundcolor',bgcolor,'String','min','HandleVisibility','off'); r(3) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 5/7 0.40 0.15 ],'Style','Radio','backgroundcolor',bgcolor,'String','max','HandleVisibility','off'); r(4) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 4/7 0.40 0.15 ],'Style','Radio','backgroundcolor',bgcolor,'String','maxabs','HandleVisibility','off'); r(5) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 3/7 0.40 0.15 ],'Style','Radio','backgroundcolor',bgcolor,'String','range','HandleVisibility','off'); r(6) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 2/7 0.40 0.15 ],'Style','Radio','backgroundcolor',bgcolor,'String','kurtosis','HandleVisibility','off'); r(7) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 1/7 0.40 0.15 ],'Style','Radio','backgroundcolor',bgcolor,'String','1/var','HandleVisibility','off'); r(8) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 0/7 0.40 0.15 ],'Style','Radio','backgroundcolor',bgcolor,'String','zvalue','HandleVisibility','off'); r(9) = uicontrol('Units','normalized','parent',g,'position',[ 0.0 -1/7 0.40 0.15 ],'Style','Radio','backgroundcolor',bgcolor,'String','maxzvalue','HandleVisibility','off'); % pre-select appropriate metric, if defined set(g,'SelectionChangeFcn',@change_metric); for i=1:length(r) if strcmp(get(r(i),'string'), cfg.metric) set(g,'SelectedObject',r(i)); end end % editboxes for manually specifying which channels/trials to turn off uicontrol(h,'Units','normalized','position',[0.64 0.44 0.14 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color'),'string','Toggle trial #:'); uicontrol(h,'Units','normalized','position',[0.64 0.40 0.12 0.05],'Style','edit','HorizontalAlignment','left','backgroundcolor',[1 1 1],'callback',@toggle_trials); uicontrol(h,'Units','normalized','position',[0.64 0.31 0.14 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color'),'string','Toggle channel:'); uicontrol(h,'Units','normalized','position',[0.64 0.27 0.12 0.05],'Style','edit','HorizontalAlignment','left','backgroundcolor',[1 1 1],'callback',@toggle_channels); % editbox for trial plotting uicontrol(h,'Units','normalized','position',[0.500 0.165 0.10 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color'),'string','Plot trial:'); info.plottrltxt = uicontrol(h,'Units','normalized','position',[0.580 0.170 0.12 0.05],'Style','edit','HorizontalAlignment','left','backgroundcolor',[1 1 1],'callback',@display_trial); info.badtrllbl = uicontrol(h,'Units','normalized','position',[0.795 0.44 0.195 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color'),'string',sprintf('Rejected trials: %i/%i',sum(info.trlsel==0),info.ntrl)); info.badtrltxt = uicontrol(h,'Units','normalized','position',[0.795 0.3975 0.23 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color')); info.badchanlbl = uicontrol(h,'Units','normalized','position',[0.795 0.31 0.195 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color'),'string',sprintf('Rejected channels: %i/%i',sum(info.chansel==0),info.nchan)); info.badchantxt = uicontrol(h,'Units','normalized','position',[0.795 0.2625 0.23 0.05],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color')); % instructions instructions = sprintf('Drag the mouse over the channels/trials you wish to reject.'); uicontrol(h,'Units','normalized','position',[0.625 0.50 0.35 0.065],'Style','text','HorizontalAlignment','left','backgroundcolor',get(h,'color'),'string',instructions,'FontWeight','bold','ForegroundColor','b'); % "show rejected" button % ui_tog = uicontrol(h,'Units','normalized','position',[0.55 0.200 0.25 0.05],'Style','checkbox','backgroundcolor',get(h,'color'),'string','Show rejected?','callback',@toggle_rejected); % if strcmp(cfg.viewmode, 'toggle') % set(ui_tog,'value',1); % end % logbox info.output_box = uicontrol(h,'Units','normalized','position',[0.00 0.00 1.00 0.15],'Style','edit','HorizontalAlignment','left','Max',3,'Min',1,'Enable','inactive','FontName',get(0,'FixedWidthFontName'),'FontSize',9,'ForegroundColor',[0 0 0],'BackgroundColor',[1 1 1]); % quit button uicontrol(h,'Units','normalized','position',[0.80 0.175 0.10 0.05],'string','quit','callback',@quit); guidata(h, info); % disable trial plotting if cfg.layout not present if ~isfield(info.cfg,'layout') set(info.plottrltxt,'Enable','off'); update_log(info.output_box,sprintf('NOTE: "cfg.layout" parameter required for trial plotting!')); end % Compute initial metric... compute_metric(h); while interactive && ishandle(h) redraw(h); info = guidata(h); if info.quit == 0 uiwait(h); else chansel = info.chansel; trlsel = info.trlsel; cfg = info.cfg; delete(h); break; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function compute_metric(h) info = guidata(h); update_log(info.output_box,'Computing metric...'); ft_progress('init', info.cfg.feedback, 'computing metric'); level = zeros(info.nchan, info.ntrl); if strcmp(info.metric,'zvalue') || strcmp(info.metric, 'maxzvalue') % cellmean and cellstd (see ft_denoise_pca) would work instead of for-loops, % but they were too memory-intensive runsum=zeros(info.nchan, 1); runss=zeros(info.nchan,1); runnum=0; for i=1:info.ntrl [dat] = preproc(info.data.trial{i}, info.data.label, offset2time(info.offset(i), info.fsample, size(info.data.trial{i},2)), info.cfg.preproc); % not entirely sure whether info.data.time{i} is correct, so making it on the fly dat(info.chansel==0,:) = nan; runsum=runsum+sum(dat,2); runss=runss+sum(dat.^2,2); runnum=runnum+size(dat,2); end mval=runsum/runnum; sd=sqrt(runss/runnum - (runsum./runnum).^2); end for i=1:info.ntrl ft_progress(i/info.ntrl, 'computing metric %d of %d\n', i, info.ntrl); [dat, label, time, info.cfg.preproc] = preproc(info.data.trial{i}, info.data.label, offset2time(info.offset(i), info.fsample, size(info.data.trial{i},2)), info.cfg.preproc); % not entirely sure whether info.data.time{i} is correct, so making it on the fly dat(info.chansel==0,:) = nan; switch info.metric case 'var' level(:,i) = std(dat, [], 2).^2; case 'min' level(:,i) = min(dat, [], 2); case 'max' level(:,i) = max(dat, [], 2); case 'maxabs' level(:,i) = max(abs(dat), [], 2); case 'range' level(:,i) = max(dat, [], 2) - min(dat, [], 2); case 'kurtosis' level(:,i) = kurtosis(dat, [], 2); case '1/var' level(:,i) = 1./(std(dat, [], 2).^2); case 'zvalue' level(:,i) = mean( ( dat-repmat(mval,1,size(dat,2)) )./repmat(sd,1,size(dat,2)) ,2); case 'maxzvalue' level(:,i) = max( ( dat-repmat(mval,1,size(dat,2)) )./repmat(sd,1,size(dat,2)) , [], 2); otherwise error('unsupported method'); end end ft_progress('close'); update_log(info.output_box,'Done.'); % if metric calculated with channels off, then turning that channel on % won't show anything. Because of this, keep track of which channels were % off when calculated, so know when to recalculate. info.metric_chansel = info.chansel; % % reinsert the data for the selected channels % dum = nan(info.nchan, info.ntrl); % dum(info.chansel,:) = level; % origlevel = dum; % clear dum % % store original levels for later % info.origlevel = origlevel; info.level = level; guidata(h,info); function redraw(h) info = guidata(h); % work with a copy of the data level = info.level; level(~info.chansel,:) = nan; level(:,~info.trlsel) = nan; [maxperchan maxpertrl maxperchan_all maxpertrl_all] = set_maxper(level, info.chansel, info.trlsel); % make the three figures if gcf~=h, figure(h); end %datacursormode on; set(h,'CurrentAxes',info.axes(1)) cla(info.axes(1)); % imagesc(level(chansel, trlsel)); imagesc(level); axis xy; % colorbar; title(info.cfg.method); ylabel('channel number'); xlabel('trial number'); set(h,'CurrentAxes',info.axes(2)) cla(info.axes(2)); set(info.axes(2),'ButtonDownFcn',@toggle_visual); plot(maxperchan(info.chansel==1), find(info.chansel==1), '.'); if strcmp(info.cfg.viewmode, 'toggle') && (sum(info.chansel==0) > 0) hold on; plot(maxperchan_all(info.chansel==0), find(info.chansel==0), 'o'); hold off; end abc = axis; axis([abc(1:2) 0 info.nchan]); % have to use 0 as lower limit because ylim([1 1]) (i.e. the single-channel case) is invalid set(info.axes(2),'ButtonDownFcn',@toggle_visual); % needs to be here; call to axis resets this property ylabel('channel number'); set(h,'CurrentAxes',info.axes(3)) cla(info.axes(3)); plot(find(info.trlsel==1), maxpertrl(info.trlsel==1), '.'); if strcmp(info.cfg.viewmode, 'toggle') && (sum(info.trlsel==0) > 0) hold on; plot(find(info.trlsel==0), maxpertrl_all(info.trlsel==0), 'o'); hold off; end abc = axis; axis([1 info.ntrl abc(3:4)]); set(info.axes(3),'ButtonDownFcn',@toggle_visual); % needs to be here; call to axis resets this property xlabel('trial number'); % put rejected trials/channels in their respective edit boxes set(info.badchanlbl,'string',sprintf('Rejected channels: %i/%i',sum(info.chansel==0),info.nchan)); set(info.badtrllbl, 'string',sprintf('Rejected trials: %i/%i',sum(info.trlsel==0), info.ntrl)); if ~isempty(find(info.trlsel==0, 1)) set(info.badtrltxt,'String',num2str(find(info.trlsel==0)),'FontAngle','normal'); else set(info.badtrltxt,'String','No trials rejected','FontAngle','italic'); end if ~isempty(find(info.chansel==0, 1)) if isfield(info.data,'label') chanlabels = info.data.label(info.chansel==0); badchantxt = ''; for i=find(info.chansel==0) if ~isempty(badchantxt) badchantxt = [badchantxt ', ' info.data.label{i} '(' num2str(i) ')']; else badchantxt = [info.data.label{i} '(' num2str(i) ')']; end end set(info.badchantxt,'String',badchantxt,'FontAngle','normal'); else set(info.badtrltxt,'String',num2str(find(info.chansel==0)),'FontAngle','normal'); end else set(info.badchantxt,'String','No channels rejected','FontAngle','italic'); end function toggle_trials(h, eventdata) info = guidata(h); % extract trials from string rawtrls = get(h,'string'); if ~isempty(rawtrls) spltrls = regexp(rawtrls,'\s+','split'); trls = []; for n = 1:length(spltrls) trls(n) = str2num(cell2mat(spltrls(n))); end else update_log(info.output_box,sprintf('Please enter one or more trials')); uiresume; return; end toggle = trls; try info.trlsel(toggle) = ~info.trlsel(toggle); catch update_log(info.output_box,sprintf('ERROR: Trial value too large!')); end guidata(h, info); uiresume; % process input from the "toggle channels" textbox function toggle_channels(h, eventdata) info = guidata(h); rawchans = get(h,'string'); if ~isempty(rawchans) splchans = regexp(rawchans,'\s+','split'); chans = zeros(1,length(splchans)); % determine whether identifying channels via number or label [junk junk junk procchans] = regexp(rawchans,'([A-Za-z]+|[0-9]{4,})'); clear junk; if isempty(procchans) % if using channel numbers for n = 1:length(splchans) chans(n) = str2num(splchans{n}); end else % if using channel labels for n = 1:length(splchans) try chans(n) = find(ismember(info.data.label,splchans(n))); catch update_log(info.output_box,sprintf('ERROR: Please ensure the channel name is correct (case-sensitive)!')); uiresume; return; end end end else update_log(info.output_box,sprintf('Please enter one or more channels')); uiresume; return; end toggle = chans; try info.chansel(toggle) = ~info.chansel(toggle); % if levels data from channel being toggled was calculated from another % metric, recalculate the metric if info.metric_chansel(toggle) == 0 compute_metric(h) end catch update_log(info.output_box,sprintf('ERROR: Channel value too large!')); end guidata(h, info); uiresume; function toggle_visual(h, eventdata) % copied from select2d, without waitforbuttonpress command point1 = get(gca,'CurrentPoint'); % button down detected finalRect = rbbox; % return figure units point2 = get(gca,'CurrentPoint'); % button up detected point1 = point1(1,1:2); % extract x and y point2 = point2(1,1:2); x = sort([point1(1) point2(1)]); y = sort([point1(2) point2(2)]); g = get(gca,'Parent'); info = guidata(g); [maxperchan maxpertrl] = set_maxper(info.level, info.chansel, info.trlsel); % toggle channels if gca == info.axes(2) % if strcmp(info.cfg.viewmode, 'toggle') chanlabels = 1:info.nchan; % else % perchan = max(info.level,[],2); % maxperchan = perchan(info.chansel==1); % chanlabels = find(info.chansel==1); % end toggle = find( ... chanlabels >= y(1) & ... chanlabels <= y(2) & ... maxperchan(:)' >= x(1) & ... maxperchan(:)' <= x(2)); info.chansel(toggle) = 0; % if levels data from channel being toggled was calculated from another % metric, recalculate the metric if info.metric_chansel(toggle) == 0 compute_metric(h) end % toggle trials elseif gca == info.axes(3) % if strcmp(info.cfg.viewmode, 'toggle') trllabels = 1:info.ntrl; % else % pertrl = max(info.level,[],1); % maxpertrl = pertrl(info.trlsel==1); % trllabels = find(info.trlsel==1); % end toggle = find( ... trllabels >= x(1) & ... trllabels <= x(2) & ... maxpertrl(:)' >= y(1) & ... maxpertrl(:)' <= y(2)); info.trlsel(toggle) = 0; end guidata(h, info); uiresume; % function display_trial(h, eventdata) % info = guidata(h); % rawtrls = get(h,'string'); % if ~isempty(rawtrls) % spltrls = regexp(rawtrls,' ','split'); % trls = []; % for n = 1:length(spltrls) % trls(n) = str2num(cell2mat(spltrls(n))); % end % else % update_log(info.output_box,sprintf('Please enter one or more trials')); % uiresume; % return; % end % if all(trls==0) % % use visual selection % update_log(info.output_box,sprintf('make visual selection of trials to be plotted seperately...')); % [x, y] = select2d; % maxpertrl = max(info.origlevel,[],1); % toggle = find(1:ntrl>=x(1) & ... % 1:ntrl<=x(2) & ... % maxpertrl(:)'>=y(1) & ... % maxpertrl(:)'<=y(2)); % else % toggle = trls; % end % for i=1:length(trls) % figure % % the data being displayed here is NOT filtered % %plot(data.time{toggle(i)}, data.trial{toggle(i)}(chansel,:)); % tmp = info.data.trial{toggle(i)}(info.chansel,:); % tmp = tmp - repmat(mean(tmp,2), [1 size(tmp,2)]); % plot(info.data.time{toggle(i)}, tmp); % title(sprintf('trial %d', toggle(i))); % end function quit(h, eventdata) info = guidata(h); info.quit = 1; guidata(h, info); uiresume; function change_metric(h, eventdata) info = guidata(h); info.metric = get(eventdata.NewValue, 'string'); guidata(h, info); compute_metric(h); uiresume; function toggle_rejected(h, eventdata) info = guidata(h); toggle = get(h,'value'); if toggle == 0 info.cfg.viewmode = 'remove'; else info.cfg.viewmode = 'toggle'; end guidata(h, info); uiresume; function update_log(h, new_text) new_text = [datestr(now,13) '# ' new_text]; curr_text = get(h, 'string'); size_curr_text = size(curr_text,2); size_new_text = size(new_text,2); if size_curr_text > size_new_text new_text = [new_text blanks(size_curr_text-size_new_text)]; else curr_text = [curr_text repmat(blanks(size_new_text-size_curr_text), size(curr_text,1), 1)]; end set(h, 'String', [new_text; curr_text]); drawnow; function [maxperchan,maxpertrl,varargout] = set_maxper(level,chansel,trlsel) level_all = level; % determine the maximum value level(~chansel,:) = nan; level(:,~trlsel) = nan; maxperchan = max(level,[],2); maxpertrl = max(level,[],1); maxperchan_all = max(level_all,[],2); maxpertrl_all = max(level_all,[],1); varargout(1) = {maxperchan_all}; varargout(2) = {maxpertrl_all}; function display_trial(h, eventdata) info = guidata(h); rawtrls = get(h,'string'); if isempty(rawtrls) return; else spltrls = regexp(rawtrls,'\s+','split'); trls = []; for n = 1:length(spltrls) trls(n) = str2num(cell2mat(spltrls(n))); end end cfg_mp = []; cfg_mp.layout = info.cfg.layout; cfg_mp.channel = info.data.label(info.chansel); currfig = gcf; for n = 1:length(trls) figure() cfg_mp.trials = trls(n); cfg_mp.interactive = 'yes'; ft_multiplotER(cfg_mp, info.data); title(sprintf('Trial %i',trls(n))); end figure(currfig); return;
github
philippboehmsturm/antx-master
warning_once.m
.m
antx-master/xspm8/external/fieldtrip/private/warning_once.m
3,832
utf_8
07dc728273934663973f4c716e7a3a1c
function [ws warned] = warning_once(varargin) % % Use as one of the following % warning_once(string) % warning_once(string, timeout) % warning_once(id, string) % warning_once(id, string, timeout) % where timeout should be inf if you don't want to see the warning ever % again. The default timeout value is 60 seconds. % % It can be used instead of the MATLAB built-in function WARNING, thus as % s = warning_once(...) % or as % warning_once(s) % where s is a structure with fields 'identifier' and 'state', storing the % state information. In other words, warning_once accepts as an input the % same structure it returns as an output. This returns or restores the % states of warnings to their previous values. % % It can also be used as % [s w] = warning_once(...) % 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 % warning_once('the value is %d', 10) % instead you should do % warning_once(sprintf('the value is %d', 10)) % Copyright (C) 2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: warning_once.m 7123 2012-12-06 21:21:38Z roboos $ persistent stopwatch previous if nargin < 1 error('You need to specify at least a warning message'); end warned = false; if isstruct(varargin{1}) warning(varargin{1}); return; end % 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); timeout = varargin{3}; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==2 && isnumeric(varargin{2}) % calling syntax (msg, timeout) warningArgs = varargin(1); timeout = varargin{2}; fname = warningArgs{1}; elseif nargin==2 && ~isnumeric(varargin{2}) % calling syntax (id, msg) warningArgs = varargin(1:2); timeout = 60; fname = [warningArgs{1} '_' warningArgs{2}]; elseif nargin==1 % calling syntax (msg) warningArgs = varargin(1); timeout = 60; % default timeout in seconds fname = [warningArgs{1}]; end if isempty(timeout) error('Timeout ill-specified'); end if isempty(stopwatch) stopwatch = tic; end if isempty(previous) previous = struct; end now = toc(stopwatch); % measure time since first function call fname = decomma(fixname(fname)); % make a nice string that is allowed as structure fieldname if length(fname) > 63 % MATLAB max name fname = fname(1:63); end if ~isfield(previous, fname) || ... (isfield(previous, fname) && now>previous.(fname).timeout) % warning never given before or timed out ws = warning(warningArgs{:}); previous.(fname).timeout = now+timeout; previous.(fname).ws = ws; warned = true; else % the warning has been issued before, but has not timed out yet ws = previous.(fname).ws; end end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function name = decomma(name) name(name==',')=[]; end % function
github
philippboehmsturm/antx-master
rejectvisual_channel.m
.m
antx-master/xspm8/external/fieldtrip/private/rejectvisual_channel.m
10,456
utf_8
774bc8d49d85b915def3a1c7e08ec8e5
function [chansel, trlsel, cfg] = rejectvisual_channel(cfg, data); % SUBFUNCTION for rejectvisual % Copyright (C) 2006, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: rejectvisual_channel.m 7123 2012-12-06 21:21:38Z roboos $ % determine the initial selection of trials and channels nchan = length(data.label); ntrl = length(data.trial); cfg.channel = ft_channelselection(cfg.channel, data.label); trlsel = logical(ones(1,ntrl)); chansel = logical(zeros(1,nchan)); chansel(match_str(data.label, cfg.channel)) = 1; % remove all non-wanted channels nchan = sum(chansel); data = ft_selectdata(data, 'channel', cfg.channel); % compute the sampling frequency from the first two timepoints fsample = 1/mean(diff(data.time{1})); % compute the offset from the time axes offset = zeros(ntrl,1); for i=1:ntrl offset(i) = time2offset(data.time{i}, fsample); end if (isfield(cfg, 'preproc') && ~isempty(cfg.preproc)) ft_progress('init', cfg.feedback, 'filtering data'); for i=1:ntrl ft_progress(i/ntrl, 'filtering data in trial %d of %d\n', i, ntrl); [data.trial{i}, label, time, cfg.preproc] = preproc(data.trial{i}, data.label, data.time{i}, cfg.preproc); end ft_progress('close'); end % select the specified latency window from the data % this is done AFTER the filtering to prevent edge artifacts for i=1:ntrl begsample = nearest(data.time{i}, cfg.latency(1)); endsample = nearest(data.time{i}, cfg.latency(2)); data.time{i} = data.time{i}(begsample:endsample); data.trial{i} = data.trial{i}(:,begsample:endsample); end h = figure; axis([0 1 0 1]); axis off % the info structure will be attached to the figure % and passed around between the callback functions if strcmp(cfg.plotlayout,'1col') % hidden config option for plotting trials differently info = []; info.ncols = 1; info.nrows = ntrl; info.trlop = 1; info.chanlop = 1; info.lchanlop= 0; info.quit = 0; info.ntrl = ntrl; info.nchan = nchan; info.data = data; info.cfg = cfg; info.offset = offset; info.chansel = chansel; info.trlsel = trlsel; % determine the position of each subplot within the axis for row=1:info.nrows for col=1:info.ncols indx = (row-1)*info.ncols + col; if indx>info.ntrl continue end info.x(indx) = (col-0.9)/info.ncols; info.y(indx) = 1 - (row-0.45)/(info.nrows+1); info.label{indx} = sprintf('trial %03d', indx); end end elseif strcmp(cfg.plotlayout,'square') info = []; info.ncols = ceil(sqrt(ntrl)); info.nrows = ceil(sqrt(ntrl)); info.trlop = 1; info.chanlop = 1; info.lchanlop= 0; info.quit = 0; info.ntrl = ntrl; info.nchan = nchan; info.data = data; info.cfg = cfg; info.offset = offset; info.chansel = chansel; info.trlsel = trlsel; % determine the position of each subplot within the axis for row=1:info.nrows for col=1:info.ncols indx = (row-1)*info.ncols + col; if indx>info.ntrl continue end info.x(indx) = (col-0.9)/info.ncols; info.y(indx) = 1 - (row-0.45)/(info.nrows+1); info.label{indx} = sprintf('trial %03d', indx); end end end info.ui.quit = uicontrol(h,'units','pixels','position',[ 5 5 40 18],'String','quit','Callback',@stop); info.ui.prev = uicontrol(h,'units','pixels','position',[ 50 5 25 18],'String','<','Callback',@prev); info.ui.next = uicontrol(h,'units','pixels','position',[ 75 5 25 18],'String','>','Callback',@next); info.ui.prev10 = uicontrol(h,'units','pixels','position',[105 5 25 18],'String','<<','Callback',@prev10); info.ui.next10 = uicontrol(h,'units','pixels','position',[130 5 25 18],'String','>>','Callback',@next10); info.ui.bad = uicontrol(h,'units','pixels','position',[160 5 50 18],'String','bad','Callback',@markbad); info.ui.good = uicontrol(h,'units','pixels','position',[210 5 50 18],'String','good','Callback',@markgood); info.ui.badnext = uicontrol(h,'units','pixels','position',[270 5 50 18],'String','bad>','Callback',@markbad_next); info.ui.goodnext = uicontrol(h,'units','pixels','position',[320 5 50 18],'String','good>','Callback',@markgood_next); set(gcf, 'WindowButtonUpFcn', @button); set(gcf, 'KeyPressFcn', @key); guidata(h,info); interactive = 1; while interactive && ishandle(h) redraw(h); info = guidata(h); if info.quit == 0, uiwait; else chansel = info.chansel; trlsel = info.trlsel; delete(h); break end end % while interactive %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function varargout = markbad_next(varargin) markbad(varargin{:}); next(varargin{:}); function varargout = markgood_next(varargin) markgood(varargin{:}); next(varargin{:}); function varargout = next(h, eventdata, handles, varargin) info = guidata(h); info.lchanlop = info.chanlop; if info.chanlop < info.nchan, info.chanlop = info.chanlop + 1; end; guidata(h,info); uiresume; function varargout = prev(h, eventdata, handles, varargin) info = guidata(h); info.lchanlop = info.chanlop; if info.chanlop > 1, info.chanlop = info.chanlop - 1; end; guidata(h,info); uiresume; function varargout = next10(h, eventdata, handles, varargin) info = guidata(h); info.lchanlop = info.chanlop; if info.chanlop < info.nchan - 10, info.chanlop = info.chanlop + 10; else info.chanlop = info.nchan; end; guidata(h,info); uiresume; function varargout = prev10(h, eventdata, handles, varargin) info = guidata(h); info.lchanlop = info.chanlop; if info.chanlop > 10, info.chanlop = info.chanlop - 10; else info.chanlop = 1; end; guidata(h,info); uiresume; function varargout = markgood(h, eventdata, handles, varargin) info = guidata(h); info.chansel(info.chanlop) = 1; fprintf(description_channel(info)); title(description_channel(info)); guidata(h,info); % uiresume; function varargout = markbad(h, eventdata, handles, varargin) info = guidata(h); info.chansel(info.chanlop) = 0; fprintf(description_channel(info)); title(description_channel(info)); guidata(h,info); % uiresume; function varargout = key(h, eventdata, handles, varargin) info = guidata(h); switch lower(eventdata.Key) case 'rightarrow' if info.chanlop ~= info.nchan next(h); else fprintf('at last channel\n'); end case 'leftarrow' if info.chanlop ~= 1 prev(h); else fprintf('at last channel\n'); end case 'g' markgood(h); case 'b' markbad(h); case 'q' stop(h); otherwise fprintf('unknown key pressed\n'); end function varargout = button(h, eventdata, handles, varargin) pos = get(gca, 'CurrentPoint'); x = pos(1,1); y = pos(1,2); info = guidata(h); dx = info.x - x; dy = info.y - y; dd = sqrt(dx.^2 + dy.^2); [d, i] = min(dd); if d<0.5/max(info.nrows, info.ncols) && i<=info.ntrl info.trlsel(i) = ~info.trlsel(i); % toggle info.trlop = i; fprintf(description_trial(info)); guidata(h,info); uiresume; else fprintf('button clicked\n'); return end function varargout = stop(h, eventdata, handles, varargin) info = guidata(h); info.quit = 1; guidata(h,info); uiresume; function str = description_channel(info); if info.chansel(info.chanlop) str = sprintf('channel %s marked as GOOD\n', info.data.label{info.chanlop}); else str = sprintf('channel %s marked as BAD\n', info.data.label{info.chanlop}); end function str = description_trial(info); if info.trlsel(info.trlop) str = sprintf('trial %d marked as GOOD\n', info.trlop); else str = sprintf('trial %d marked as BAD\n', info.trlop); end function redraw(h) if ~ishandle(h) return end info = guidata(h); fprintf(description_channel(info)); cla; title(''); drawnow hold on % determine the maximum value for this channel over all trials amax = -inf; tmin = inf; tmax = -inf; for trlindx=find(info.trlsel) tmin = min(info.data.time{trlindx}(1) , tmin); tmax = max(info.data.time{trlindx}(end), tmax); amax = max(max(abs(info.data.trial{trlindx}(info.chanlop,:))), amax); end if ~isempty(info.cfg.alim) % use fixed amplitude limits for the amplitude scaling amax = info.cfg.alim; end for row=1:info.nrows for col=1:info.ncols trlindx = (row-1)*info.ncols + col; if trlindx>info.ntrl || ~info.trlsel(trlindx) continue end % scale the time values between 0.1 and 0.9 time = info.data.time{trlindx}; time = 0.1 + 0.8*(time-tmin)/(tmax-tmin); % scale the amplitude values between -0.5 and 0.5, offset should not be removed dat = info.data.trial{trlindx}(info.chanlop,:); dat = dat ./ (2*amax); % scale the time values for this subplot tim = (col-1)/info.ncols + time/info.ncols; % scale the amplitude values for this subplot amp = dat./info.nrows + 1 - row/(info.nrows+1); plot(tim, amp, 'k') end end % enable or disable buttons as appropriate if info.chanlop == 1 set(info.ui.prev, 'Enable', 'off'); set(info.ui.prev10, 'Enable', 'off'); else set(info.ui.prev, 'Enable', 'on'); set(info.ui.prev10, 'Enable', 'on'); end if info.chanlop == info.nchan set(info.ui.next, 'Enable', 'off'); set(info.ui.next10, 'Enable', 'off'); else set(info.ui.next, 'Enable', 'on'); set(info.ui.next10, 'Enable', 'on'); end if info.lchanlop == info.chanlop && info.chanlop == info.nchan set(info.ui.badnext,'Enable', 'off'); set(info.ui.goodnext,'Enable', 'off'); else set(info.ui.badnext,'Enable', 'on'); set(info.ui.goodnext,'Enable', 'on'); end text(info.x, info.y, info.label); title(description_channel(info)); hold off
github
philippboehmsturm/antx-master
triangulate_seg.m
.m
antx-master/xspm8/external/fieldtrip/private/triangulate_seg.m
4,749
utf_8
43f67dbe00353d8bb75b709aa97d7ce0
function [pnt, tri] = triangulate_seg(seg, npnt, origin) % TRIANGULATE_SEG constructs a triangulation of the outer surface of a % segmented volume. It starts at the center of the volume and projects the % vertices of an evenly triangulated sphere onto the outer surface. The % resulting surface is star-shaped from the origin of the sphere. % % Use as % [pnt, tri] = triangulate_seg(seg, npnt, origin) % % Input arguments: % seg = 3D-matrix (boolean) containing segmented volume. If not boolean % seg = seg(~=0); % npnt = requested number of vertices % origin = 1x3 vector specifying the location of the origin of the sphere % in voxel indices. This argument is optional. If undefined, the % origin of the sphere will be in the centre of the volume. % % Output arguments: % pnt = Nx3 matrix of vertex locations % tri = Mx3 matrix of triangles % % Seg will be checked for holes, and filled if necessary. Also, seg will be % checked to consist of a single boolean blob. If not, only the outer surface % of the largest will be triangulated. SPM is used for both the filling and % checking for multiple blobs. % % See also KSPHERE % Copyright (C) 2005-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: triangulate_seg.m 7123 2012-12-06 21:21:38Z roboos $ % impose it to be boolean seg = (seg~=0); dim = size(seg); len = ceil(sqrt(sum(dim.^2))/2); if ~any(seg(:)) error('the segmentation is empty') end % define the origin if it is not provided in the input arguments if nargin<3 origin(1) = dim(1)/2; origin(2) = dim(2)/2; origin(3) = dim(3)/2; end % ensure that the seg consists of only one filled blob. % if not filled: throw a warning and fill % if more than one blob: throw a warning and use the biggest ft_hastoolbox('SPM8', 1); % look for holes seg = volumefillholes(seg); % look for >1 blob [lab, num] = spm_bwlabel(double(seg), 26); if num>1, warning('the segmented volume consists of more than one compartment, using only the biggest one for the segmentation'); for k = 1:num n(k) = sum(lab(:)==k); end [m,ix] = max(n); seg(lab~=ix) = false; end % start with a unit sphere with evenly distributed vertices [pnt, tri] = ksphere(npnt); ishollow = false; for i=1:npnt % construct a sampled line from the center of the volume outward into the direction of the vertex lin = (0:0.5:len)' * pnt(i,:); lin(:,1) = lin(:,1) + origin(1); lin(:,2) = lin(:,2) + origin(2); lin(:,3) = lin(:,3) + origin(3); % round the sampled line towards the nearest voxel indices, which allows % a quick nearest-neighbour interpolation/lookup lin = round(lin); % exclude indices that do not lie within the volume sel = lin(:,1)<1 | lin(:,1)>dim(1) | ... lin(:,2)<1 | lin(:,2)>dim(2) | ... lin(:,3)<1 | lin(:,3)>dim(3); lin = lin(~sel,:); sel = sub2ind(dim, lin(:,1), lin(:,2), lin(:,3)); % interpolate the segmented volume along the sampled line int = seg(sel); % the value along the line is expected to be 1 at first and then drop to 0 % anything else suggests that the segmentation is hollow ishollow = any(diff(int)==1); % find the last sample along the line that is inside the segmentation sel = find(int, 1, 'last'); % this is a problem if sel is empty. If so, use the edge of the volume if ~isempty(sel) % take the last point inside and average with the first point outside pnt(i,:) = lin(sel,:); else % take the edge pnt(i,:) = lin(end,:); end end if ishollow % this should not have hapened, especially not after filling the holes warning('the segmentation is not star-shaped, please check the surface mesh'); end % undo the shift of the origin from where the projection is done % pnt(:,1) = pnt(:,1) - origin(1); % pnt(:,2) = pnt(:,2) - origin(2); % pnt(:,3) = pnt(:,3) - origin(3); % fast unconditional re-implementation of the standard Matlab function function [s] = sub2ind(dim, i, j, k) s = i + (j-1)*dim(1) + (k-1)*dim(1)*dim(2);
github
philippboehmsturm/antx-master
browse_simpleFFT.m
.m
antx-master/xspm8/external/fieldtrip/private/browse_simpleFFT.m
3,848
utf_8
8a1561f6249a7c96e15d8a38485f6df3
function browse_simpleFFT(cfg, data) % BROWSE_SIMPLEFFT is a helper function for FT_DATABROWSER that shows a % simple FFT of the data. % % Included are a button to switch between log and non-log space, and a selection button to deselect channels, % for the purpose of zooming in on bad channels. % % % % See also BROWSE_MOVIEPLOTER, BROWSE_TOPOPLOTER, BROWSE_MULTIPLOTER, BROWSE_TOPOPLOTVAR, BROWSE_SIMPLEFFT % Copyright (C) 2011, Roemer van der Meij % call ft_freqanalysis on data cfgfreq = []; cfgfreq.method = 'mtmfft'; cfgfreq.taper = 'boxcar'; freqdata = ft_freqanalysis(cfgfreq,data); % remove zero-bin for plotting if freqdata.freq(1) == 0 freqdata.freq = freqdata.freq(2:end); freqdata.powspctrm = freqdata.powspctrm(:,2:end); end %%% FIXME: call ft_singleplotER for everything below % make figure window for fft ffth = figure('name',cfg.figurename,'numbertitle','off','units','normalized'); % set button butth = uicontrol('tag', 'simplefft_l2', 'parent', ffth, 'units', 'normalized', 'style', 'checkbox', 'string','log10 of power','position', [0.87, 0.6 , 0.12, 0.05], 'value',1,'callback',{@draw_simple_fft_cb},'backgroundcolor',[.8 .8 .8]); uicontrol('tag', 'simplefft_l2_chansel', 'parent', ffth, 'units', 'normalized', 'style', 'pushbutton', 'string','select channels','position', [0.87, 0.45 , 0.12, 0.10],'callback',{@selectchan_fft_cb}); % put dat in fig (sparse) fftopt = []; fftopt.freqdata = freqdata; fftopt.chancolors = cfg.chancolors; fftopt.chansel = 1:numel(data.label); fftopt.butth = butth; setappdata(ffth, 'fftopt', fftopt); % draw fig draw_simple_fft_cb(butth) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function selectchan_fft_cb(h,eventdata) ffth = get(h,'parent'); fftopt = getappdata(ffth, 'fftopt'); % open chansel dialog chansel = select_channel_list(fftopt.opt.freq.label, fftopt.chansel, 'select channels for viewing power'); % output data fftopt.chansel = chansel; setappdata(ffth, 'fftopt', fftopt); draw_simple_fft_cb(fftopt.butth) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function draw_simple_fft_cb(h,eventdata) togglestate = get(h,'value'); ffth = get(h,'parent'); fftopt = getappdata(ffth, 'fftopt'); % clear axis (for switching) cla % switch log10 or nonlog10 if togglestate == 0 dat = fftopt.freqdata.powspctrm; elseif togglestate == 1 dat = log10(fftopt.freqdata.powspctrm); end % select data and chanel colors chancolors = fftopt.chancolors(fftopt.chansel,:); dat = dat(fftopt.chansel,:); % plot using specified colors set(0,'currentFigure',ffth) for ichan = 1:size(dat,1) color = chancolors(ichan,:); ft_plot_vector(fftopt.freqdata.freq, dat(ichan,:), 'box', false, 'color', color) end ylabel('log10(power)') xlabel('frequency (hz)') yrange = abs(max(max(dat)) - min(min(dat))); axis([fftopt.freqdata.freq(1) fftopt.freqdata.freq(end) (min(min(dat)) - yrange.*.1) (max(max(dat)) + yrange*.1)]) % switch log10 or nonlog10 if togglestate == 0 ylabel('power') axis([fftopt.freqdata.freq(1) fftopt.freqdata.freq(end) 0 (max(max(dat)) + yrange*.1)]) elseif togglestate == 1 ylabel('log10(power)') axis([fftopt.freqdata.freq(1) fftopt.freqdata.freq(end) (min(min(dat)) - yrange.*.1) (max(max(dat)) + yrange*.1)]) end set(gca,'Position', [0.13 0.11 0.725 0.815])
github
philippboehmsturm/antx-master
prepare_mesh_manual.m
.m
antx-master/xspm8/external/fieldtrip/private/prepare_mesh_manual.m
29,475
utf_8
0d8c0801202308a5c8afddd585a4e695
function bnd = prepare_mesh_manual(cfg, mri) % PREPARE_MESH_MANUAL is called by PREPARE_MESH and opens a GUI to manually % select points/polygons in an mri dataset. % % It allows: % Visualization of 3d data in 3 different projections % Adjustment of brightness for every slice % Storage of the data points in an external .mat file % Retrieval of previously saved data points % Slice fast scrolling with keyboard arrows % Polygons or points selection/deselection % % See also PREPARE_MESH_SEGMENTATION, PREPARE_MESH_HEADSHAPE % Copyrights (C) 2009, Cristiano Micheli & Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: prepare_mesh_manual.m 7123 2012-12-06 21:21:38Z roboos $ % FIXME: control slice's cmap referred to abs values % FIXME: clean structure slicedata % FIXME: check function assign3dpoints global obj bnd.pnt = []; bnd.tri = []; hasheadshape = isfield(cfg, 'headshape'); hasbnd = isfield(cfg, 'bnd'); % FIXME why is this in cfg? hasmri = nargin>1; % check the consistency of the input arguments if hasheadshape && hasbnd error('you should not specify cfg.headshape and cfg.bnd simultaneously'); end % check the consistency of the input arguments if ~hasmri % FIXME give a warning or so? mri.anatomy = []; mri.transform = eye(4); else % ensure that it is double precision mri.anatomy = double(mri.anatomy); end if hasheadshape if ~isempty(cfg.headshape) % get the surface describing the head shape if isstruct(cfg.headshape) && isfield(cfg.headshape, 'pnt') % use the headshape surface specified in the configuration headshape = cfg.headshape; elseif isnumeric(cfg.headshape) && size(cfg.headshape,2)==3 % use the headshape points specified in the configuration headshape.pnt = cfg.headshape; elseif ischar(cfg.headshape) % read the headshape from file headshape = read_headshape(cfg.headshape); else headshape = []; end if ~isfield(headshape, 'tri') for i=1:length(headshape) % generate a closed triangulation from the surface points headshape(i).pnt = unique(headshape(i).pnt, 'rows'); headshape(i).tri = projecttri(headshape(i).pnt); end end % start with the headshape bnd = headshape; end elseif hasbnd if ~isempty(cfg.bnd) % start with the prespecified boundaries bnd = cfg.bnd; end else % start with an empty boundary if not specified bnd.pnt = []; bnd.tri = []; end % creating the GUI fig = figure; % initialize some values slicedata = []; points = bnd.pnt; axs = floor(size(mri.anatomy,1)/2); % initialize properties set(fig, 'KeyPressFcn',@keypress); set(fig, 'CloseRequestFcn', @cb_close); setappdata(fig,'data',mri.anatomy); setappdata(fig,'prop',{1,axs,0,[]}); setappdata(fig,'slicedata',slicedata); setappdata(fig,'points',points); setappdata(fig,'box',[]); % add GUI elements cb_creategui(gca); cb_redraw(gca); waitfor(fig); % close sequence global pnt try tmp = pnt; clear global pnt pnt = tmp; clear tmp [tri] = projecttri(pnt); bnd.pnt = pnt; bnd.tri = tri; catch bnd.pnt = []; bnd.tri = []; end function cb_redraw(hObject, eventdata, handles); fig = get(hObject, 'parent'); prop = getappdata(fig,'prop'); data = getappdata(fig,'data'); slicedata = getappdata(fig,'slicedata'); points = getappdata(fig,'points'); % draw image try cla % i,j,k axes if (prop{1}==1) %jk imh=imagesc(squeeze(data(prop{2},:,:))); xlabel('k'); ylabel('j'); colormap bone elseif (prop{1}==2) %ik imh=imagesc(squeeze(data(:,prop{2},:))); xlabel('k'); ylabel('i'); colormap bone elseif (prop{1}==3) %ij imh=imagesc(squeeze(data(:,:,prop{2}))); xlabel('j'); ylabel('i'); colormap bone end axis equal; axis tight brighten(prop{3}); title([ 'slice ' num2str(prop{2}) ]) catch end if ~ishold,hold on,end % draw points and lines for zz = 1:length(slicedata) if(slicedata(zz).proj==prop{1}) if(slicedata(zz).slice==prop{2}) polygon = slicedata(zz).polygon; for kk=1:length(polygon) if ~isempty(polygon{kk}) [xs,ys]=deal(polygon{kk}(:,1),polygon{kk}(:,2)); plot(xs, ys, 'g.-'); end end end end end % end for % draw other slices points points = getappdata(fig,'points'); pnts = round(points); if ~isempty(pnts) % exclude polygons inside the same slice indx = find(points(:,prop{1})==prop{2}); tmp = ones(1,size(points,1)); tmp(indx) = 0; pnts = points(find(tmp),:); % calculate indexes of other proj falling in current slice indx2 = find(round(pnts(:,prop{1}))==prop{2}); rest = setdiff([1 2 3],prop{1}); % plot the points for jj=1:length(indx2) [x,y] = deal(pnts(indx2(jj),rest(1)),pnts(indx2(jj),rest(2))); plot(y,x,'g*') end end % add blue cross markers in case of box selection box = getappdata(fig,'box'); point2mark = getappdata(fig,'point2mark'); if ~isempty(point2mark) plot(point2mark.x,point2mark.y,'marker','+') end if ~isempty(box) for kk=1:size(box,1) proj = box(kk,1); slice = box(kk,2); rowmin = box(kk,3); rowmax = box(kk,4); colmin = box(kk,5); colmax = box(kk,6); aaa = get(findobj(fig, 'color', 'g')); for ii=1:length(aaa) if ispolygon(aaa(ii)) L = length(aaa(ii).YData); for jj=1:L cond = lt(aaa(ii).YData(jj),rowmax).*gt(aaa(ii).YData(jj),rowmin).* ... lt(aaa(ii).XData(jj),colmax).*gt(aaa(ii).XData(jj),colmin); if cond plot(aaa(ii).XData(jj),aaa(ii).YData(jj),'marker','+') end end elseif ispoint(aaa(ii)) cond = lt(aaa(ii).YData,rowmax).*gt(aaa(ii).YData,rowmin).* ... lt(aaa(ii).XData,colmax).*gt(aaa(ii).XData,colmin); % the test after cond takes care the box doesnt propagate in 3D if (cond && (proj == prop{1}) && (slice == prop{2})) plot(aaa(ii).XData,aaa(ii).YData,'marker','+') end end end end end if get(findobj(fig, 'tag', 'toggle axes'), 'value') axis on else axis off end function cb_creategui(hObject, eventdata, handles) fig = get(hObject, 'parent'); % define the position of each GUI element position = { [1] % view radio [1 1] % del ins [1] % label slice [1 1] % slice [1] % brightness [1 1] % brightness [1] % axis visible [1 1] % view ij [1 1] % jk ik [1] % label mesh [1 1] % view open mesh [1 1] % save exit buttons }; % define the style of each GUI element style = { {'radiobutton'} {'radiobutton' 'radiobutton'} {'text' } {'pushbutton' 'pushbutton'} {'text'} {'pushbutton' 'pushbutton'} {'checkbox'} {'text' 'radiobutton'} {'radiobutton' 'radiobutton'} {'text' } {'pushbutton' 'pushbutton'} {'pushbutton' 'pushbutton'} }; % define the descriptive string of each GUI element string = { {'View'} {'Ins' 'Del'} {'slice'} {'<' '>'} {'brightness'} {'+' '-'} {'axes'} {'plane' 'jk'} {'ik' 'ij'} {'mesh'} {'smooth' 'view'} {'Cancel' 'OK'} }; % define the value of each GUI element prop = getappdata(fig,'prop'); value = { {1} {0 0} {[]} {[] []} {[]} {[] []} {0} {[] 1} {0 0} {[]} {1 1} {1 1} }; % define a tag for each GUI element tag = { {'view'} {'ins' 'del' } {'slice'} {'min' 'max'} {'brightness'} {'plus' 'minus'} {'toggle axes'} {'plane' 'one'} {'two' 'three'} {'mesh'} {'smoothm' 'viewm'} {'cancel' 'OK'} }; % define the callback function of each GUI element callback = { {@which_task1} {@which_task2 @which_task3} {[]} {@cb_btn @cb_btn} {[]} {@cb_btn @cb_btn} {@cb_redraw} {[] @cb_btnp1} {@cb_btnp2 @cb_btnp3} {[]} {@smooth_mesh @view_mesh} {@cancel_mesh @cb_btn} }; visible = { {'on'} {'on' 'on'} {'on'} {'on' 'on'} {'on'} {'on' 'on'} {'on'} {'on' 'on'} {'on' 'on'} {'on'} {'on' 'on'} {'on' 'on'} }; layoutgui(fig, [0.77 0.10 0.20 0.85], position, style, string, value, tag, callback,visible); function h = layoutgui(fig, geometry, position, style, string, value, tag, callback,visible); horipos = geometry(1); % lower left corner of the GUI part in the figure vertpos = geometry(2); % lower left corner of the GUI part in the figure width = geometry(3); % width of the GUI part in the figure height = geometry(4); % height of the GUI part in the figure horidist = 0.05; vertdist = 0.05; options = {'units', 'normalized', 'HorizontalAlignment', 'center'}; % 'VerticalAlignment', 'middle' Nrow = size(position,1); h = cell(Nrow,1); for i=1:Nrow if isempty(position{i}) continue; end position{i} = position{i} ./ sum(position{i}); Ncol = size(position{i},2); ybeg = (Nrow-i )/Nrow + vertdist/2; yend = (Nrow-i+1)/Nrow - vertdist/2; for j=1:Ncol xbeg = sum(position{i}(1:(j-1))) + horidist/2; xend = sum(position{i}(1:(j ))) - horidist/2; pos(1) = xbeg*width + horipos; pos(2) = ybeg*height + vertpos; pos(3) = (xend-xbeg)*width; pos(4) = (yend-ybeg)*height; h{i}{j} = uicontrol(fig, ... options{:}, ... 'position', pos, ... 'style', style{i}{j}, ... 'string', string{i}{j}, ... 'tag', tag{i}{j}, ... 'value', value{i}{j}, ... 'callback', callback{i}{j}, ... 'visible', visible{i}{j} ... ); end end function cb_btn(hObject, eventdata, handles) fig = get(gca, 'parent'); prop = getappdata(fig,'prop'); slice = prop{2}; br = prop{3}; datdim = size(getappdata(fig,'data')); % p1 = [];p2 = [];p3 = []; p1 = get(findobj('string','jk'),'value'); p2 = get(findobj('string','ik'),'value'); p3 = get(findobj('string','ij'),'value'); set(findobj('string','-'),'Value',prop{3}); set(findobj('string','+'),'Value',prop{3}); beta = get(findobj('string','-'),'Value'); if (p1) %jk setappdata(fig,'prop',{1,round(datdim(1)/2),br,prop{4}}); cb_redraw(gca); elseif (p2) %ik setappdata(fig,'prop',{2,round(datdim(2)/2),br,prop{4}}); cb_redraw(gca); elseif (p3) %ij setappdata(fig,'prop',{3,round(datdim(3)/2),br,prop{4}}); cb_redraw(gca); end if strcmp(get(hObject,'string'),'-') beta=beta-0.05; set(findobj('string','-'),'Value',beta); set(findobj('string','+'),'Value',beta); setappdata(fig,'prop',{prop{1},prop{2},beta,prop{4}}); cb_redraw(gca); elseif strcmp(get(hObject,'string'),'+') beta=beta+0.05; set(findobj('string','+'),'Value',beta); setappdata(fig,'prop',{prop{1},prop{2},beta,prop{4}}); cb_redraw(gca); end if strcmp(get(hObject,'string'),'<') setappdata(fig,'prop',{prop{1},slice-1,0,prop{4}}); cb_redraw(gca); end if strcmp(get(hObject,'string'),'>') setappdata(fig,'prop',{prop{1},slice+1,0,prop{4}}); cb_redraw(gca); end if strcmp(get(hObject,'string'),'OK') close(fig) end function keypress(h, eventdata, handles, varargin) fig = get(gca, 'parent'); prop = getappdata(fig,'prop'); dat = guidata(gcbf); key = get(gcbf, 'CurrentCharacter'); slice = prop{2}; if key switch key case 28 setappdata(fig,'prop',{prop{1},slice-1,0,prop{4}}); cb_redraw(gca); case 29 setappdata(fig,'prop',{prop{1},slice+1,0,prop{4}}); cb_redraw(gca); otherwise end end uiresume(h) function build_polygon fig = get(gca, 'parent'); prop = getappdata(fig,'prop'); data = getappdata(fig,'data'); ss = size(data); proj = prop{1}; slice = prop{2}; thispolygon =1; polygon{thispolygon} = zeros(0,2); maskhelp = [ ... '------------------------------------------------------------------------\n' ... 'specify polygons for masking the topographic interpolation\n' ... 'press the right mouse button to add another point to the current polygon\n' ... 'press backspace on the keyboard to remove the last point\n' ... 'press "c" on the keyboard to close this polygon and start with another\n' ... 'press "q" or ESC on the keyboard to continue\n' ... ]; again = 1; if ~ishold,hold,end fprintf(maskhelp); fprintf('\n'); while again for i=1:length(polygon) fprintf('polygon %d has %d points\n', i, size(polygon{i},1)); end [x, y, k] = ginput(1); okflag = 0; % check points do not fall out of image boundaries if get(findobj('string','Ins'),'value') if (proj == 1 && y<ss(2) && x<ss(3) && x>1 && y>1) okflag = 1; elseif (proj == 2 && y<ss(1) && x<ss(3) && x>1 && y>1) okflag = 1; elseif (proj == 3 && y<ss(1) && x<ss(2) && x>1 && y>1) okflag = 1; else okflag = 0; end end if okflag switch lower(k) case 1 polygon{thispolygon} = cat(1, polygon{thispolygon}, [x y]); % add the last line segment to the figure if size(polygon{thispolygon},1)>1 x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); end plot(x, y, 'g.-'); case 8 % backspace if size(polygon{thispolygon},1)>0 % redraw existing polygons cb_redraw(gca); % remove the last point of current polygon polygon{thispolygon} = polygon{thispolygon}(1:end-1,:); for i=1:length(polygon) x = polygon{i}(:,1); y = polygon{i}(:,2); if i~=thispolygon % close the polygon in the figure x(end) = x(1); y(end) = y(1); end set(gca,'nextplot','new') plot(x, y, 'g.-'); end end case 'c' if size(polygon{thispolygon},1)>0 % close the polygon polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:); % close the polygon in the figure x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); plot(x, y, 'g.-'); % switch to the next polygon thispolygon = thispolygon + 1; polygon{thispolygon} = zeros(0,2); slicedata = getappdata(fig,'slicedata'); m = length(slicedata); slicedata(m+1).proj = prop{1}; slicedata(m+1).slice = prop{2}; slicedata(m+1).polygon = polygon; setappdata(fig,'slicedata',slicedata); end case {'q', 27} if size(polygon{thispolygon},1)>0 % close the polygon polygon{thispolygon}(end+1,:) = polygon{thispolygon}(1,:); % close the polygon in the figure x = polygon{i}([end-1 end],1); y = polygon{i}([end-1 end],2); plot(x, y, 'g.-'); end again = 0; %set(gcf,'WindowButtonDownFcn',''); slicedata = getappdata(fig,'slicedata'); m = length(slicedata); if ~isempty(polygon{thispolygon}) slicedata(m+1).proj = prop{1}; slicedata(m+1).slice = prop{2}; slicedata(m+1).polygon = polygon; setappdata(fig,'slicedata',slicedata); end otherwise warning('invalid button (%d)', k); end end assign_points3d end function cb_btn_dwn(hObject, eventdata, handles) build_polygon uiresume function cb_btn_dwn2(hObject, eventdata, handles) global obj erase_points2d(obj) uiresume function erase_points2d (obj) fig = get(gca, 'parent'); prop = getappdata(fig,'prop'); slicedata = getappdata(fig,'slicedata'); pntsslice = []; % 2d slice selected box boundaries if strcmp(get(obj,'string'),'box') [x, y] = ft_select_box; rowmin = min(y); rowmax = max(y); colmin = min(x); colmax = max(x); box = getappdata(fig,'box'); box = [box; prop{1} prop{2} rowmin rowmax colmin colmax]; setappdata(fig,'box',box); else % converts lines to points pos = slicedata2pnts(prop{1},prop{2}); tmp = ft_select_point(pos); point2mark.x = tmp(1); point2mark.y = tmp(2); setappdata(fig,'point2mark',point2mark); end maskhelp = [ ... '------------------------------------------------------------------------\n' ... 'Delete points:\n' ... 'press "c" on the keyboard to undo all selections\n' ... 'press "d" or DEL on the keyboard to delete all selections\n' ... ]; fprintf(maskhelp); fprintf('\n'); again = 1; if ~ishold,hold,end cb_redraw(gca); % waits for a key press while again [junk1, junk2, k] = ginput(1); switch lower(k) case 'c' if strcmp(get(obj,'string'),'box') % undoes all the selections, but only in the current slice ind = []; for ii=1:size(box,1) if box(ii,1)==prop{1} && box(ii,2)==prop{2} ind = [ind,ii]; end end box(ind,:) = []; setappdata(fig,'box',box); cb_redraw(gca); again = 0; set(gcf,'WindowButtonDownFcn',''); else setappdata(fig,'point2mark',[]); cb_redraw(gca); again = 0; set(gcf,'WindowButtonDownFcn',''); end case {'d', 127} if strcmp(get(obj,'string'),'box') update_slicedata % deletes only the points selected in the current slice ind = []; for ii=1:size(box,1) if box(ii,1)==prop{1} && box(ii,2)==prop{2} ind = [ind,ii]; end end box(ind,:) = []; setappdata(fig,'box',box); cb_redraw(gca); again = 0; set(gcf,'WindowButtonDownFcn',''); else update_slicedata setappdata(fig,'point2mark',[]); cb_redraw(gca); again = 0; set(gcf,'WindowButtonDownFcn',''); end otherwise end end assign_points3d function assign_points3d fig = get(gca, 'parent'); slicedata = getappdata(fig,'slicedata'); points = []; for zz = 1:length(slicedata) slice = slicedata(zz).slice; proj = slicedata(zz).proj; polygon = slicedata(zz).polygon; for kk=1:length(polygon) if ~isempty(polygon{kk}) [xs,ys]=deal(polygon{kk}(:,1),polygon{kk}(:,2)); if (proj==1) %jk tmp = [ slice*ones(length(xs),1),ys(:),xs(:) ]; points = [points; unique(tmp,'rows')]; elseif (proj==2) %ik tmp = [ ys(:),slice*ones(length(xs),1),xs(:) ]; points = [points; unique(tmp,'rows')]; elseif (proj==3) %ij tmp = [ ys(:),xs(:),slice*ones(length(xs),1) ]; points = [points; unique(tmp,'rows')]; end end end end setappdata(fig,'points',points); function update_slicedata fig = get(gca, 'parent'); prop = getappdata(fig,'prop'); slicedata = getappdata(fig,'slicedata'); box = getappdata(fig,'box'); point2mark = getappdata(fig,'point2mark'); % case of box selection if ~isempty(box) && ~isempty(slicedata) for zz = 1:length(slicedata) slice = slicedata(zz).slice; proj = slicedata(zz).proj; polygon = slicedata(zz).polygon; for uu=1:size(box,1) if (box(uu,1)==proj) && (box(uu,2)==slice) for kk=1:length(polygon) if ~isempty(polygon{kk}) [xs,ys] = deal(polygon{kk}(:,1),polygon{kk}(:,2)); tmpind = lt(ys,ones(length(xs),1)*box(uu,4)).*gt(ys,ones(length(xs),1)*box(uu,3)).* ... lt(xs,ones(length(xs),1)*box(uu,6)).*gt(xs,ones(length(xs),1)*box(uu,5)); slicedata(zz).polygon{kk} = [ xs(find(~tmpind)),ys(find(~tmpind)) ]; end end end end end % case of point selection else if ~isempty(slicedata) for zz = 1:length(slicedata) slice = slicedata(zz).slice; proj = slicedata(zz).proj; polygon = slicedata(zz).polygon; for kk=1:length(polygon) if ~isempty(polygon{kk}) [xs,ys] = deal(polygon{kk}(:,1),polygon{kk}(:,2)); tmpind = eq(xs,point2mark.x).*eq(ys,point2mark.y); slicedata(zz).polygon{kk} = [ xs(find(~tmpind)),ys(find(~tmpind)) ]; end end end end end setappdata(fig,'slicedata',slicedata) % FIXME: obsolete: replaced by headshape at the beginning function smooth_mesh(hObject, eventdata, handles) fig = get(gca,'parent'); disp('not yet implemented') % FIXME: make it work for pre-loaded meshes function view_mesh(hObject, eventdata, handles) fig = get(gca, 'parent'); assign_points3d pnt = getappdata(fig,'points'); pnt_ = pnt; if ~isempty(pnt) tri = projecttri(pnt); bnd.pnt = pnt_; bnd.tri = tri; slicedata = getappdata(fig,'slicedata'); figure ft_plot_mesh(bnd,'vertexcolor','k'); end function cancel_mesh(hObject, eventdata, handles) fig = get(gca, 'parent'); close(fig) function cb_close(hObject, eventdata, handles) % get the points from the figure fig = hObject; global pnt pnt = getappdata(fig, 'points'); set(fig, 'CloseRequestFcn', @delete); delete(fig); function cb_btnp1(hObject, eventdata, handles) set(findobj('string','jk'),'value',1); set(findobj('string','ik'),'value',0); set(findobj('string','ij'),'value',0); cb_btn(hObject); function cb_btnp2(hObject, eventdata, handles) set(findobj('string','jk'),'value',0); set(findobj('string','ik'),'value',1); set(findobj('string','ij'),'value',0); cb_btn(hObject); function cb_btnp3(hObject, eventdata, handles) set(findobj('string','jk'),'value',0); set(findobj('string','ik'),'value',0); set(findobj('string','ij'),'value',1); cb_btn(hObject); function which_task1(hObject, eventdata, handles) set(gcf,'WindowButtonDownFcn',''); set(findobj('string','View'),'value',1); set(findobj('string','Ins'), 'value',0); set(findobj('string','Del'), 'value',0); set(gcf,'WindowButtonDownFcn',''); change_panel function which_task2(hObject, eventdata, handles) set(findobj('string','View'),'value',0); set(findobj('string','Ins'), 'value',1); set(findobj('string','Del'), 'value',0); set(gcf,'WindowButtonDownFcn',@cb_btn_dwn); change_panel function which_task3(hObject, eventdata, handles) set(gcf,'WindowButtonDownFcn',''); set(findobj('string','View'),'value',0); set(findobj('string','Ins'), 'value',0); set(findobj('string','Del'), 'value',1); change_panel function change_panel % affect panel visualization w1 = get(findobj('string','View'),'value'); w2 = get(findobj('string','Ins'), 'value'); w3 = get(findobj('string','Del'), 'value'); if w1 set(findobj('tag','slice'),'string','slice'); set(findobj('tag','min'),'string','<'); set(findobj('tag','max'),'string','>'); set(findobj('tag','min'),'style','pushbutton'); set(findobj('tag','max'),'style','pushbutton'); set(findobj('tag','min'),'callback',@cb_btn); set(findobj('tag','max'),'callback',@cb_btn); set(findobj('tag','mesh'),'visible','on'); set(findobj('tag','openm'),'visible','on'); set(findobj('tag','viewm'),'visible','on'); set(findobj('tag','brightness'),'visible','on'); set(findobj('tag','plus'),'visible','on'); set(findobj('tag','minus'),'visible','on'); set(findobj('tag','toggle axes'),'visible','on'); set(findobj('tag','plane'),'visible','on'); set(findobj('tag','one'),'visible','on'); set(findobj('tag','two'),'visible','on'); set(findobj('tag','three'),'visible','on'); elseif w2 set(findobj('tag','slice'),'string','select points'); set(findobj('tag','min'),'string','close'); set(findobj('tag','max'),'string','next'); set(findobj('tag','min'),'style','pushbutton'); set(findobj('tag','max'),'style','pushbutton'); set(findobj('tag','min'),'callback',@tins_close); set(findobj('tag','max'),'callback',@tins_next); set(findobj('tag','mesh'),'visible','off'); set(findobj('tag','openm'),'visible','off'); set(findobj('tag','viewm'),'visible','off'); set(findobj('tag','brightness'),'visible','off'); set(findobj('tag','plus'),'visible','off'); set(findobj('tag','minus'),'visible','off'); set(findobj('tag','toggle axes'),'visible','off'); set(findobj('tag','plane'),'visible','off'); set(findobj('tag','one'),'visible','off'); set(findobj('tag','two'),'visible','off'); set(findobj('tag','three'),'visible','off'); elseif w3 set(findobj('tag','slice'),'string','select points'); set(findobj('tag','min'),'string','box'); set(findobj('tag','max'),'string','point'); set(findobj('tag','min'),'style','pushbutton'); set(findobj('tag','max'),'style','pushbutton'); set(findobj('tag','min'),'callback',@tdel_box); set(findobj('tag','max'),'callback',@tdel_single); set(findobj('tag','mesh'),'visible','off'); set(findobj('tag','openm'),'visible','off'); set(findobj('tag','viewm'),'visible','off'); set(findobj('tag','brightness'),'visible','off'); set(findobj('tag','plus'),'visible','off'); set(findobj('tag','minus'),'visible','off'); set(findobj('tag','toggle axes'),'visible','off'); set(findobj('tag','plane'),'visible','off'); set(findobj('tag','one'),'visible','off'); set(findobj('tag','two'),'visible','off'); set(findobj('tag','three'),'visible','off'); end function tins_close(hObject, eventdata, handles) set(gcf,'WindowButtonDownFcn',''); function tins_next(hObject, eventdata, handles) set(gcf,'WindowButtonDownFcn',''); function tdel_box(hObject, eventdata, handles) global obj obj = gco; set(gcf,'WindowButtonDownFcn',@cb_btn_dwn2); function tdel_single(hObject, eventdata, handles) global obj obj = gco; set(gcf,'WindowButtonDownFcn',@cb_btn_dwn2); % accessory functions: function [pnts] = slicedata2pnts(proj,slice) fig = get(gca, 'parent'); slicedata = getappdata(fig,'slicedata'); pnts = []; for i=1:length(slicedata) if slicedata(i).slice==slice && slicedata(i).proj == proj for j=1:length(slicedata(i).polygon) if ~isempty(slicedata(i).polygon{j}) tmp = slicedata(i).polygon{j}; xs = tmp(:,1); ys = tmp(:,2); pnts = [pnts;[unique([xs,ys],'rows')]]; end end end end function h = ispolygon(x) h = length(x.XData)>1; function h = ispoint(x) h = length(x.XData)==1; function [T,P] = points2param(pnt) x = pnt(:,1); y = pnt(:,2); z = pnt(:,3); [phi,theta,R] = cart2sph(x,y,z); theta = theta + pi/2; phi = phi + pi; T = theta(:); P = phi(:); function [bnd2,a,Or] = spherical_harmonic_mesh(bnd, nl) % SPHERICAL_HARMONIC_MESH realizes the smoothed version of a mesh contained in the first % argument bnd. The boundary argument (bnd) contains typically 2 fields % called .pnt and .tri referring to vertices and triangulation of a mesh. % The degree of smoothing is given by the order in the second input: nl % % Use as % bnd2 = spherical_harmonic_mesh(bnd, nl); % nl = 12; % from van 't Ent paper bnd2 = []; % calculate midpoint Or = mean(bnd.pnt); % rescale all points x = bnd.pnt(:,1) - Or(1); y = bnd.pnt(:,2) - Or(2); z = bnd.pnt(:,3) - Or(3); X = [x(:), y(:), z(:)]; % convert points to parameters [T,P] = points2param(X); % basis function B = shlib_B(nl, T, P); Y = B'*X; % solve the linear system a = pinv(B'*B)*Y; % build the surface Xs = zeros(size(X)); for l = 0:nl-1 for m = -l:l if m<0 Yml = shlib_Yml(l, abs(m), T, P); Yml = (-1)^m*conj(Yml); else Yml = shlib_Yml(l, m, T, P); end indx = l^2 + l + m+1; Xs = Xs + Yml*a(indx,:); end fprintf('%d of %d\n', l, nl); end % Just take the real part Xs = real(Xs); % reconstruct the matrices for plotting. xs = reshape(Xs(:,1), size(x,1), size(x,2)); ys = reshape(Xs(:,2), size(x,1), size(x,2)); zs = reshape(Xs(:,3), size(x,1), size(x,2)); bnd2.pnt = [xs(:)+Or(1) ys(:)+Or(2) zs(:)+Or(3)]; [bnd2.tri] = projecttri(bnd.pnt); function B = shlib_B(nl, theta, phi) % function B = shlib_B(nl, theta, phi) % % Constructs the matrix of basis functions % where b(i,l^2 + l + m) = Yml(theta, phi) % % See also: shlib_Yml.m, shlib_decomp.m, shlib_gen_shfnc.m % % Dr. A. I. Hanna (2006). B = zeros(length(theta), nl^2+2*nl+1); for l = 0:nl-1 for m = -l:l if m<0 Yml = shlib_Yml(l, abs(m), theta, phi); Yml = (-1)^m*conj(Yml); else Yml = shlib_Yml(l, m, theta, phi); end indx = l^2 + l + m+1; B(:, indx) = Yml; end end return; function Yml = shlib_Yml(l, m, theta, phi) % function Yml = shlib_Yml(l, m, theta, phi) % % A matlab function that takes a given order and degree, and the matrix of % theta and phi and constructs a spherical harmonic from these. The % analogue in the 1D case would be to give a particular frequency. % % Inputs: % m - order of the spherical harmonic % l - degree of the spherical harmonic % theta - matrix of polar coordinates \theta \in [0, \pi] % phi - matrix of azimuthal cooridinates \phi \in [0, 2\pi) % % Example: % % [x, y] = meshgrid(-1:.1:1); % z = x.^2 + y.^2; % [phi,theta,R] = cart2sph(x,y,z); % Yml = spharm_aih(2,2, theta(:), phi(:)); % % See also: shlib_B.m, shlib_decomp.m, shlib_gen_shfnc.m % % Dr. A. I. Hanna (2006) Pml=legendre(l,cos(theta)); if l~=0 Pml=squeeze(Pml(m+1,:,:)); end Pml = Pml(:); % Yml = sqrt(((2*l+1)/4).*(factorial(l-m)/factorial(l+m))).*Pml.*exp(sqrt(-1).*m.*phi); % new: Yml = sqrt(((2*l+1)/(4*pi)).*(factorial(l-m)/factorial(l+m))).*Pml.*exp(sqrt(-1).*m.*phi); return;
github
philippboehmsturm/antx-master
nanmean.m
.m
antx-master/xspm8/external/fieldtrip/private/nanmean.m
165
utf_8
e6c473a49d8be6e12960af55ced45e54
% NANMEAN provides a replacement for MATLAB's nanmean. % % For usage see MEAN. function y = nanmean(x, dim) N = sum(~isnan(x), dim); y = nansum(x, dim) ./ N; end
github
philippboehmsturm/antx-master
moviefunction.m
.m
antx-master/xspm8/external/fieldtrip/private/moviefunction.m
33,279
utf_8
c7d6d7c70dddcb8f371c2bd1260e6067
function moviefunction(cfg, data) % we need cfg.plotfun to plot the data % data needs to be 3D, N x time x freq (last can be singleton) % N needs to correspond to number of vertices (channels, gridpoints, etc) ft_defaults ft_preamble help ft_preamble callinfo ft_preamble trackconfig ft_preamble loadvar data data = ft_checkdata(data, 'datatype', {'timelock', 'freq', 'source'}); % check if the input cfg is valid for this function cfg = ft_checkconfig(cfg, 'renamedval', {'zlim', 'absmax', 'maxabs'}); cfg = ft_checkconfig(cfg, 'renamed', {'zparam', 'funparameter'}); cfg = ft_checkconfig(cfg, 'renamed', {'parameter', 'funparameter'}); cfg = ft_checkconfig(cfg, 'renamed', {'mask', 'maskparameter'}); cfg = ft_checkconfig(cfg, 'deprecated', {'xparam'}); cfg = ft_checkconfig(cfg, 'forbidden', {'yparam'}); % set data flags opt = []; opt.issource = ft_datatype(data, 'source'); opt.isfreq = ft_datatype(data, 'freq'); opt.istimelock = ft_datatype(data, 'timelock'); if opt.issource+opt.isfreq+opt.istimelock ~= 1 error('data cannot be definitely deteced as frequency, timelock or source data'); end if opt.issource % transfer anatomical information to opt if isfield(data, 'sulc') opt.anatomy.sulc = data.sulc; end if isfield(data, 'tri') opt.anatomy.tri = data.tri; else error('source.tri missing, this function requires a triangulated cortical sheet as source model'); end if isfield(data, 'pnt') opt.anatomy.pnt = data.pnt; elseif isfield(data, 'pos') opt.anatomy.pos = data.pos; else error('source.pos or source.pnt is missing'); end end % set the defaults cfg.xlim = ft_getopt(cfg, 'xlim', 'maxmin'); cfg.ylim = ft_getopt(cfg, 'ylim', 'maxmin'); cfg.zlim = ft_getopt(cfg, 'zlim', 'maxmin'); cfg.xparam = ft_getopt(cfg, 'xparam', 'time'); cfg.yparam = ft_getopt(cfg, 'yparam', '[]'); if isempty(cfg.yparam ) && isfield(data, 'freq') cfg.yparam = 'freq'; else cfg.yparam = []; end if opt.isfreq cfg.funparameter = ft_getopt(cfg, 'funparameter', 'powspctrm'); % use power as default elseif opt.istimelock cfg.funparameter = ft_getopt(cfg, 'funparameter', 'avg'); % use power as default elseif opt.issource cfg.funparameter = ft_getopt(cfg, 'funparameter', 'avg.pow'); % use power as default end cfg.maskparameter = ft_getopt(cfg, 'maskparameter'); cfg.inputfile = ft_getopt(cfg, 'inputfile', []); cfg.samperframe = ft_getopt(cfg, 'samperframe', 1); cfg.framespersec = ft_getopt(cfg, 'framespersec', 5); cfg.framesfile = ft_getopt(cfg, 'framesfile', []); cfg.moviefreq = ft_getopt(cfg, 'moviefreq', []); cfg.movietime = ft_getopt(cfg, 'movietime', []); cfg.movierpt = ft_getopt(cfg, 'movierpt', 1); cfg.interactive = ft_getopt(cfg, 'interactive', 'yes'); opt.record = ~istrue(cfg.interactive); % read or create the layout that will be used for plotting: if isfield(cfg, 'layout') opt.layout = ft_prepare_layout(cfg); % select the channels in the data that match with the layout: [seldat, sellay] = match_str(data.label, opt.layout.label); if isempty(seldat) error('labels in data and labels in layout do not match'); end % get the x and y coordinates and labels of the channels in the data opt.chanx = opt.layout.pos(sellay,1); opt.chany = opt.layout.pos(sellay,2); else if ~opt.issource error('you need to specify a layout in case of freq or timelock data'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the actual computation is done in the middle part %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% opt.xvalues = data.(cfg.xparam); opt.yvalues = []; if ~isempty(cfg.yparam) opt.yvalues = data.(cfg.yparam); end opt.dat = getsubfield(data, cfg.funparameter); % check consistency of xparam and yparam % NOTE: i set two different defaults for the 'chan_time' and the 'chan_freq_time' case if isfield(data,'dimord') % get dimord dimensions dims = textscan(data.dimord,'%s', 'Delimiter', '_'); dims = dims{1}; % remove subject dimension rpt_dim = strcmp('rpt', dims) | strcmp('subj', dims); if sum(rpt_dim)~=0 dims(rpt_dim) = []; opt.dat = squeeze(nanmean(opt.dat, find(rpt_dim))); end opt.ydim = find(strcmp(cfg.yparam, dims)); opt.xdim = find(strcmp(cfg.xparam, dims)); opt.zdim = setdiff(1:ndims(opt.dat), [opt.ydim opt.xdim]); if opt.zdim ~=1 error('input data does not have the correct format of N x time (x freq)'); end % and permute opt.dat = permute(opt.dat, [opt.zdim(:)' opt.xdim opt.ydim]); end if opt.issource if size(data.pos)~=size(opt.dat,1) error('inconsistent number of vertices in the cortical mesh'); end if ~isfield(data, 'tri') error('source.tri missing, this function requires a triangulated cortical sheet as source model'); end end opt.xdim = 2; if ~isempty(cfg.yparam) opt.ydim = 3; else opt.ydim = []; end if ~isempty(cfg.maskparameter) && ischar(cfg.maskparameter) opt.mask = double(getsubfield(data, cfg.maskparameter)~=0); else opt.mask =ones(size(opt.dat)); end if length(opt.xvalues)~=size(opt.dat, opt.xdim) error('inconsistent size of "%s" compared to "%s"', cfg.funparameter, cfg.xparam); end if ~isempty(opt.ydim) && length(opt.yvalues)~=size(opt.dat,opt.ydim) error('inconsistent size of "%s" compared to "%s"', cfg.funparameter, cfg.yparam); end % TODO handle colorbar stuff here % create GUI and plot stuff opt = createGUI(opt); if isempty(cfg.yparam) set(opt.handles.label.yparam, 'Visible', 'off'); set(opt.handles.slider.yparam, 'Visible', 'off'); opt.yparam = ''; else opt.yparam = [upper(cfg.yparam(1)) lower(cfg.yparam(2:end))]; set(opt.handles.label.yparam, 'String', opt.yparam); end opt.xparam = [upper(cfg.xparam(1)) lower(cfg.xparam(2:end))]; set(opt.handles.label.xparam, 'String', opt.xparam); % set timer opt.timer = timer; set(opt.timer, 'timerfcn', {@cb_timer, opt.handles.figure}, 'period', 0.1, 'executionmode', 'fixedSpacing'); opt = prepareBrainplot(opt); opt.speed = 1; guidata(opt.handles.figure, opt); % init first screen cb_slider(opt.handles.figure); %uicontrol(opt.handles.colorbar); cb_colorbar(opt.handles.figure); if opt.record start(opt.timer); end end %% % ************************************************************** % ********************* CREATE GUI ***************************** % ************************************************************** function opt = createGUI(opt) % main figure opt.handles.figure = figure(... 'Units','characters',... 'Color',[0.941176470588235 0.941176470588235 0.941176470588235],... 'Colormap',[0 0 0.5625;0 0 0.625;0 0 0.6875;0 0 0.75;0 0 0.8125;0 0 0.875;0 0 0.9375;0 0 1;0 0.0625 1;0 0.125 1;0 0.1875 1;0 0.25 1;0 0.3125 1;0 0.375 1;0 0.4375 1;0 0.5 1;0 0.5625 1;0 0.625 1;0 0.6875 1;0 0.75 1;0 0.8125 1;0 0.875 1;0 0.9375 1;0 1 1;0.0625 1 1;0.125 1 0.9375;0.1875 1 0.875;0.25 1 0.8125;0.3125 1 0.75;0.375 1 0.6875;0.4375 1 0.625;0.5 1 0.5625;0.5625 1 0.5;0.625 1 0.4375;0.6875 1 0.375;0.75 1 0.3125;0.8125 1 0.25;0.875 1 0.1875;0.9375 1 0.125;1 1 0.0625;1 1 0;1 0.9375 0;1 0.875 0;1 0.8125 0;1 0.75 0;1 0.6875 0;1 0.625 0;1 0.5625 0;1 0.5 0;1 0.4375 0;1 0.375 0;1 0.3125 0;1 0.25 0;1 0.1875 0;1 0.125 0;1 0.0625 0;1 0 0;0.9375 0 0;0.875 0 0;0.8125 0 0;0.75 0 0;0.6875 0 0;0.625 0 0;0.5625 0 0],... 'IntegerHandle','off',... 'InvertHardcopy',get(0,'defaultfigureInvertHardcopy'),... 'Name','ft_movieplot',... 'Menu', 'none', ... 'Toolbar', 'figure', ... 'NumberTitle','off',... 'PaperPosition',get(0,'defaultfigurePaperPosition'),... 'Position',[103.8 14.0769230769231 180.2 50],... 'HandleVisibility','callback',... 'WindowButtonUpFcn', @cb_stopDrag, ... 'UserData',[],... 'Tag','mainFigure',... 'Visible','on'); % view panel (between different views can be switched) opt.handles.panel.view = uipanel(... 'Parent',opt.handles.figure,... 'Title','View',... 'Tag','viewPanel',... 'Clipping','on',... 'Visible', 'off', ... 'Position',[0.842397336293008 -0.00307692307692308 0.155382907880133 1.00153846153846] ); % axes for switching to topo viewmode opt.handles.axes.topo = axes(... 'Parent',opt.handles.panel.view,... 'Position',[0.0441176470588235 0.728706624605678 0.955882352941177 0.205047318611987],... 'CameraPosition',[0.5 0.5 9.16025403784439],... 'CameraPositionMode',get(0,'defaultaxesCameraPositionMode'),... 'Color',[0.941176470588235 0.941176470588235 0.941176470588235],... 'ColorOrder',get(0,'defaultaxesColorOrder'),... 'LooseInset',[0.115903614457831 0.107232704402516 0.0846987951807229 0.0731132075471698],... 'XColor',get(0,'defaultaxesXColor'),... 'YColor',get(0,'defaultaxesYColor'),... 'ZColor',get(0,'defaultaxesZColor'),... 'ButtonDownFcn',@(hObject,eventdata)test_movieplot_export('topoAxes_ButtonDownFcn',hObject,eventdata,guidata(hObject)),... 'Tag','topoAxes',... 'HandleVisibility', 'on', ... 'UserData',[]); % axes for switching to multiplot viewmode opt.handles.axes.multi = axes(... 'Parent',opt.handles.panel.view,... 'Position',[0.0441176470588235 0.413249211356467 0.955882352941177 0.205047318611987],... 'CameraPosition',[0.5 0.5 9.16025403784439],... 'CameraPositionMode',get(0,'defaultaxesCameraPositionMode'),... 'Color',[0.941176470588235 0.941176470588235 0.941176470588235],... 'ColorOrder',get(0,'defaultaxesColorOrder'),... 'LooseInset',[0.0302261898791314 0.128446186295888 0.0220883695270575 0.0875769452017415],... 'XColor',get(0,'defaultaxesXColor'),... 'YColor',get(0,'defaultaxesYColor'),... 'ZColor',get(0,'defaultaxesZColor'),... 'ButtonDownFcn',@(hObject,eventdata)test_movieplot_export('multiAxes_ButtonDownFcn',hObject,eventdata,guidata(hObject)),... 'Tag','multiAxes',... 'HandleVisibility', 'on', ... 'UserData',[]); % axes for switching to singleplot viewmode opt.handles.axes.single = axes(... 'Parent',opt.handles.panel.view,... 'Position',[0.0441176470588235 0.0977917981072555 0.955882352941177 0.205047318611987],... 'CameraPosition',[0.5 0.5 9.16025403784439],... 'CameraPositionMode',get(0,'defaultaxesCameraPositionMode'),... 'Color',[0.941176470588235 0.941176470588235 0.941176470588235],... 'ColorOrder',get(0,'defaultaxesColorOrder'),... 'LooseInset',[0.0302261898791314 0.128446186295888 0.0220883695270575 0.0875769452017415],... 'XColor',get(0,'defaultaxesXColor'),... 'YColor',get(0,'defaultaxesYColor'),... 'ZColor',get(0,'defaultaxesZColor'),... 'Tag','singleAxes',... 'HandleVisibility', 'on', ... 'UserData',[]); % main control panel opt.handles.panel.control = uipanel(... 'Parent',opt.handles.figure,... 'Title','Controls',... 'Tag','controlPanel',... 'Clipping','on',... 'Position',[0.660377358490566 -0.00307692307692308 0.177580466148724 0.153846153846154]); % buttons opt.handles.button.play = uicontrol(... 'Parent',opt.handles.panel.control,... 'Units','normalized',... 'Callback',@cb_playbutton,... 'Position',[0.0973193473193473 0.457831325301205 0.314685314685315 0.530120481927711],... 'String','Play',... 'Tag','playButton'); opt.handles.button.record = uicontrol(... 'Parent',opt.handles.panel.control,... 'Units','normalized',... 'Callback',@cb_recordbutton, ... 'Position',[0.551864801864802 0.457831325301205 0.321678321678322 0.530120481927711],... 'String','Record',... 'Tag','recordButton'); % speed control opt.handles.slider.speed = uicontrol(... 'Parent',opt.handles.panel.control,... 'Units','normalized',... 'BackgroundColor',[0.9 0.9 0.9],... 'Callback',@cb_speed, ... 'Position',[0.0256410256410256 0.0843373493975904 0.493589743589744 0.204819277108434],... 'String',{ 'Slider' },... 'Style','slider',... 'Value',0.5,... 'Tag','speedSlider'); opt.MIN_SPEED = 0.01; opt.AVG_SPEED = 1; opt.MAX_SPEED = 100; opt.handles.label.speed = uicontrol(... 'Parent',opt.handles.panel.control,... 'Units','normalized',... 'HorizontalAlignment','left',... 'Position',[0.532051282051282 0.108433734939759 0.448717948717949 0.168674698795181],... 'String','Speed 1.0x',... 'Style','text',... 'Value',0.5,... 'Tag','speedLabel'); % parameter control opt.handles.panel.parameter = uipanel(... 'Parent',opt.handles.figure,... 'Title','Parameter',... 'Tag','parameterPanel',... 'Clipping','on',... 'Position',[-0.00110987791342952 -0.00307692307692308 0.658157602663707 0.155384615384615]); opt.handles.slider.xparam = uicontrol(... 'Parent',opt.handles.panel.parameter,... 'Units','normalized',... 'BackgroundColor',[0.9 0.9 0.9],... 'Callback',@cb_slider,... 'Position',[0.0186757215619694 0.250000000000001 0.969439728353141 0.214285714285714],... 'String',{ 'Slider' },... 'Style','slider',... 'Tag','xparamslider'); opt.handles.label.xparam = uicontrol(... 'Parent',opt.handles.panel.parameter,... 'Units','normalized',... 'Position',[0.0186757215619694 0.0476190476190483 0.967741935483871 0.178571428571429],... 'String','xparamLabel',... 'Style','text',... 'Tag','xparamLabel'); opt.handles.slider.yparam = uicontrol(... 'Parent',opt.handles.panel.parameter,... 'Units','normalized',... 'BackgroundColor',[0.9 0.9 0.9],... 'Callback',@cb_slider,... 'Position',[0.0186757215619694 0.690476190476191 0.969439728353141 0.202380952380952],... 'String',{ 'Slider' },... 'Style','slider',... 'Tag','yparamSlider'); opt.handles.label.yparam = uicontrol(... 'Parent',opt.handles.panel.parameter,... 'Units','normalized',... 'Position',[0.0186757215619694 0.500000000000001 0.967741935483871 0.178571428571429],... 'String','yparamLabel',... 'Style','text',... 'Tag','text3'); opt.handles.buttongroup.color = uibuttongroup(... 'Parent',opt.handles.figure,... 'Title','Colormap',... 'Tag','colorGroup',... 'Clipping','on',... 'Position',[0.725860155382908 0.150769230769231 0.112097669256382 0.847692307692308],... 'SelectedObject',[],... 'SelectionChangeFcn',[],... 'OldSelectedObject',[]); opt.handles.axes.colorbar = axes(... 'Parent',opt.handles.buttongroup.color,... 'Position',[-0.0103092783505155 0.157303370786517 1.04123711340206 0.771535580524345],... 'CameraPosition',[0.5 0.5 9.16025403784439],... 'CameraPositionMode',get(0,'defaultaxesCameraPositionMode'),... 'Color',[0.941176470588235 0.941176470588235 0.941176470588235],... 'ColorOrder',get(0,'defaultaxesColorOrder'),... 'LooseInset',[6.37540259335975e-007 1.19260520025353e-007 4.65894804899366e-007 8.13139909263772e-008],... 'XColor',get(0,'defaultaxesXColor'),... 'YColor',get(0,'defaultaxesYColor'),... 'ZColor',get(0,'defaultaxesZColor'),... 'ButtonDownFcn',@(hObject,eventdata)test_movieplot_export('colorbarAxes_ButtonDownFcn',hObject,eventdata,guidata(hObject)),... 'HandleVisibility', 'on', ... 'Tag','colorbarAxes', ... 'YLim', [0 1], ... 'YLimMode', 'manual', ... 'XLim', [0 1], ... 'XLimMode', 'manual'); % set colorbar opt.handles.colorbar = colorbar('ButtonDownFcn', []); set(opt.handles.colorbar, 'Parent', opt.handles.figure); set(opt.handles.colorbar, 'Position', [0.7725 0.305 0.02 0.6]); if (gcf~=opt.handles.figure) close gcf; % sometimes there is a new window that opens up end % set lines %YLim = get(opt.handles.colorbar, 'YLim'); opt.handles.lines.upperColor = line([-1 0], [32 32], ... 'Color', 'black', ... 'LineWidth', 4, ... 'ButtonDownFcn', @cb_startDrag, ... 'Parent', opt.handles.colorbar, ... 'Visible', 'off', ... 'Tag', 'upperColor'); opt.handles.lines.lowerColor = line([1 2], [32 32], ... 'Color', 'black', ... 'LineWidth', 4, ... 'ButtonDownFcn', @cb_startDrag, ... 'Parent', opt.handles.colorbar, ... 'Visible', 'off', ... 'Tag', 'lowerColor'); opt.handles.menu.colormap = uicontrol(... 'Parent',opt.handles.buttongroup.color,... 'Units','normalized',... 'BackgroundColor',[1 1 1],... 'Callback',@cb_colormap,... 'Position',[0.0721649484536082 0.951310861423221 0.865979381443299 0.0374531835205993],... 'String',{ 'jet'; 'hot'; 'cool' },... 'Style','popupmenu',... 'Value',1, ... 'Tag','colormapMenu'); opt.handles.checkbox.auto = uicontrol(... 'Parent',opt.handles.buttongroup.color,... 'Units','normalized',... 'Callback',@cb_colorbar,... 'Position',[0.103092783505155 0.0898876404494382 0.77319587628866 0.0430711610486891],... 'String','automatic',... 'Style','checkbox',... 'Value', 1, ... % TODO make this dependet on cfg.zlim 'Tag','autoCheck'); opt.handles.checkbox.symmetric = uicontrol(... 'Parent',opt.handles.buttongroup.color,... 'Units','normalized',... 'Callback',@cb_colorbar,... 'Position',[0.103092783505155 0.0449438202247191 0.77319587628866 0.0430711610486891],... 'String','symmetric',... 'Style','checkbox',... 'Value', 0, ... % TODO make this dependet on cfg.zlim 'Tag','symCheck'); % buttons opt.handles.button.decrUpperColor = uicontrol(... 'Parent', opt.handles.buttongroup.color,... 'Units','normalized',... 'Enable', 'off', ... 'Callback',@cb_colorbar,... 'Position',[0.503092783505155 0.9149438202247191 0.17319587628866 0.0330711610486891],... 'String','-',... 'Tag','decrUpperColor'); opt.handles.button.incrLowerColor = uicontrol(... 'Parent', opt.handles.buttongroup.color,... 'Units','normalized',... 'Enable', 'off', ... 'Callback',@cb_colorbar,... 'Position',[0.303092783505155 0.1449438202247191 0.17319587628866 0.0330711610486891],... 'String','+',... 'Tag','incrLowerColor'); opt.handles.button.incrUpperColor = uicontrol(... 'Parent', opt.handles.buttongroup.color,... 'Units','normalized',... 'Enable', 'off', ... 'Callback',@cb_colorbar,... 'Position',[0.303092783505155 0.9149438202247191 0.17319587628866 0.0330711610486891],... 'String','+',... 'Tag','incrUpperColor'); opt.handles.button.decrLowerColor = uicontrol(... 'Parent', opt.handles.buttongroup.color,... 'Units','normalized',... 'Enable', 'off', ... 'Callback',@cb_colorbar,... 'Position',[0.503092783505155 0.1449438202247191 0.17319587628866 0.0330711610486891],... 'String','-',... 'Tag','decrLowerColor'); opt.handles.axes.movie = axes(... 'Parent',opt.handles.figure,... 'Position',[-0.00110987791342952 0.150769230769231 0.722530521642619 0.847692307692308],... 'CameraPosition',[0.5 0.5 9.16025403784439],... 'CameraPositionMode',get(0,'defaultaxesCameraPositionMode'),... 'CLim',get(0,'defaultaxesCLim'),... 'CLimMode','manual',... 'Color',[0.941176470588235 0.941176470588235 0.941176470588235],... 'ColorOrder',get(0,'defaultaxesColorOrder'),... 'LooseInset',[0.120510948905109 0.11 0.088065693430657 0.075],... 'XColor',get(0,'defaultaxesXColor'),... 'YColor',get(0,'defaultaxesYColor'),... 'ZColor',get(0,'defaultaxesZColor'),... 'HandleVisibility', 'on', ... 'ButtonDownFcn',@(hObject,eventdata)test_movieplot_export('movieAxes_ButtonDownFcn',hObject,eventdata,guidata(hObject)),... 'Tag','movieAxes'); % Disable axis labels axis(opt.handles.axes.movie, 'equal'); axis(opt.handles.axes.colorbar, 'equal'); axis(opt.handles.axes.topo, 'equal'); axis(opt.handles.axes.multi, 'equal'); axis(opt.handles.axes.single, 'equal'); axis(opt.handles.axes.movie, 'off'); axis(opt.handles.axes.colorbar, 'off'); axis(opt.handles.axes.topo, 'off'); axis(opt.handles.axes.multi, 'off'); axis(opt.handles.axes.single, 'off'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function updateMovie(opt, valx, valy) if ~opt.issource set(opt.handles.grid, 'cdata', griddata(opt.chanx, opt.chany, opt.mask(:,valx,valy).*opt.dat(:,valx,valy), opt.xdata, opt.nanmask.*opt.ydata, 'v4')); else set(opt.handles.mesh, 'FaceVertexCData', squeeze(opt.dat(:,valx,valy))); set(opt.handles.mesh, 'FaceVertexAlphaData', squeeze(opt.mask(:,valx,valy))); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_speed(h, eventdata) if ~ishandle(h) return end opt = guidata(h); val = get(opt.handles.slider.speed, 'value'); val = exp(log(opt.MAX_SPEED) * (val-.5)./0.5); % make sure we can easily get back to normal speed if abs(val-opt.AVG_SPEED) < 0.08 val = opt.AVG_SPEED; set(opt.handles.slider.speed, 'value', 0.5); end opt.speed = val; if val >=100 set(opt.handles.label.speed, 'String', ['Speed ' num2str(opt.speed, '%.1f'), 'x']) elseif val >= 10 set(opt.handles.label.speed, 'String', ['Speed ' num2str(opt.speed, '%.2f'), 'x']) else set(opt.handles.label.speed, 'String', ['Speed ' num2str(opt.speed, '%.3f'), 'x']) end guidata(h, opt); uiresume; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_timer(obj, info, h) if ~ishandle(h) return end opt = guidata(h); delta = opt.speed/size(opt.dat,opt.xdim); val = get(opt.handles.slider.xparam, 'value'); val = val + delta; if opt.record if val>1 % stop recording stop(opt.timer); % save movie if isfield(opt, 'framesfile') && ~isempty(opt.framesfile) save(opt.framesfile, 'F'); end % play movie if ~isfield(opt, 'framespersec') opt.framespersec = 4; opt.movierpt = 3; end % reset again val = 0; set(opt.handles.slider.xparam, 'value', val); cb_slider(h); cb_recordbutton(opt.handles.button.record); movie(opt.F, opt.movierpt, opt.framespersec); guidata(h, opt); return; end end if val>1 val = val-1; end set(opt.handles.slider.xparam, 'value', val); cb_slider(h); if opt.record if ~isfield(opt, 'F') % init F opt.F(1) = getframe(opt.handles.figure); else opt.F(end+1) = getframe(opt.handles.figure); end guidata(h, opt); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_slider(h, eventdata) opt = guidata(h); valx = get(opt.handles.slider.xparam, 'value'); valx = round(valx*(size(opt.dat,opt.xdim)-1))+1; valx = min(valx, size(opt.dat,opt.xdim)); valx = max(valx, 1); set(opt.handles.label.xparam, 'String', [opt.xparam ' ' num2str(opt.xvalues(valx), '%.2f') 's']); if ~isempty(opt.yvalues) valy = get(opt.handles.slider.yparam, 'value'); valy = round(valy*(size(opt.dat, opt.ydim)-1))+1; valy = min(valy, size(opt.dat, opt.ydim)); valy = max(valy, 1); set(opt.handles.label.yparam, 'String', [opt.yparam ' ' num2str(opt.yvalues(valy), '%.2f') 'Hz']); else valy = 1; end updateMovie(opt, valx, valy); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_playbutton(h, eventdata) if ~ishandle(h) return end opt = guidata(h); switch get(h, 'string') case 'Play' set(h, 'string', 'Stop'); start(opt.timer); case 'Stop' set(h, 'string', 'Play'); stop(opt.timer); end uiresume; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_recordbutton(h, eventdata) if ~ishandle(h) return end opt = guidata(h); opt.record = ~opt.record; % switch state if isfield(opt, 'F') opt = rmfield(opt, 'F'); end if opt.record % FIXME open new window to play in there, so that frame getting works set(h, 'string', 'Stop'); start(opt.timer); else % FIXME set handle back to old window set(h, 'string', 'Record'); stop(opt.timer); end guidata(h, opt); % % % This function should open a new window, plot in there, extract every % % frame, store the movie in opt and return again % % % this is not needed, no new window is needed % %scrsz = get(0, 'ScreenSize'); % %f = figure('Position',[1 1 scrsz(3) scrsz(4)]); % % % FIXME disable buttons (apart from RECORD) when recording % % if record is pressed, stop recording and immediately return % % % adapted from ft_movieplotTFR % % % frequency/time selection % if ~isempty(opt.yvalues) && any(~isnan(yvalues)) % if ~isempty(cfg.movietime) % indx = cfg.movietime; % for iFrame = 1:floor(size(opt.dat, opt.xdim)/cfg.samperframe) % indy = ((iFrame-1)*cfg.samperframe+1):iFrame*cfg.samperframe; % updateMovie(opt, indx, indy); % F(iFrame) = getframe; % end % elseif ~isempty(cfg.moviefreq) % indy = cfg.moviefreq; % for iFrame = 1:floor(size(opt.dat, opt.ydim)/cfg.samperframe) % indx = ((iFrame-1)*cfg.samperframe+1):iFrame*cfg.samperframe; % updateMovie(opt, indx, indy); % F(iFrame) = getframe; % end % else % error('Either moviefreq or movietime should contain a bin number') % end % else % for iFrame = 1:floor(size(opt.dat, opt.xdim)/cfg.samperframe) % indx = ((iFrame-1)*cfg.samperframe+1):iFrame*cfg.samperframe; % updateMovie(opt, indx, 1); % F(iFrame) = getframe; % end % end % % % save movie % if ~isempty(cfg.framesfile) % save(cfg.framesfile, 'F'); % end % % play movie % movie(F, cfg.movierpt, cfg.framespersec); uiresume; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_colormap(h, eventdata) maps = get(h, 'String'); val = get(h, 'Value'); while ~strcmp(get(h, 'Tag'), 'mainFigure') h = get(h, 'Parent'); end opt = guidata(h); cmap = colormap(opt.handles.axes.movie, maps{val}); if get(opt.handles.checkbox.auto, 'Value') colormap(opt.handles.axes.movie, cmap); else adjust_colorbar(opt); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_colorbar(h, eventdata) if strcmp(get(h, 'Tag'), 'mainFigure') % this is the init call incr = false; decr = false; else incr = strcmp(get(h, 'String'), '+'); decr = strcmp(get(h, 'String'), '-'); lower = strfind(get(h, 'Tag'), 'Lower')>0; while ~strcmp(get(h, 'Tag'), 'mainFigure') h = get(h, 'Parent'); end end opt = guidata(h); [zmin zmax] = caxis(opt.handles.axes.movie); yLim = get(opt.handles.colorbar, 'YLim'); if incr yTick = linspace(zmin, zmax, yLim(end)); if get(opt.handles.checkbox.symmetric, 'Value') zmin = zmin - mean(diff(yTick)); zmax = zmax + mean(diff(yTick)); elseif (lower) zmin = zmin + mean(diff(yTick)); else zmax = zmax + mean(diff(yTick)); end elseif decr yTick = linspace(zmin, zmax, yLim(end)); if get(opt.handles.checkbox.symmetric, 'Value') zmin = zmin + mean(diff(yTick)); zmax = zmax - mean(diff(yTick)); elseif (lower) zmin = zmin - mean(diff(yTick)); else zmax = zmax - mean(diff(yTick)); end elseif get(opt.handles.checkbox.auto, 'Value') % if automatic set(opt.handles.lines.upperColor, 'Visible', 'off'); set(opt.handles.lines.lowerColor, 'Visible', 'off'); set(opt.handles.lines.upperColor, 'YData', [yLim(end)/2 yLim(end)/2]); set(opt.handles.lines.lowerColor, 'YData', [yLim(end)/2 yLim(end)/2]); set(opt.handles.button.incrUpperColor, 'Enable', 'off'); set(opt.handles.button.decrUpperColor, 'Enable', 'off'); set(opt.handles.button.incrLowerColor, 'Enable', 'off'); set(opt.handles.button.decrLowerColor, 'Enable', 'off'); if get(opt.handles.checkbox.symmetric, 'Value') % maxabs zmax = max(abs(opt.dat(:))); zmin = -zmax; else % maxmin zmin = min(opt.dat(:)); zmax = max(opt.dat(:)); end else set(opt.handles.lines.upperColor, 'Visible', 'on'); set(opt.handles.lines.lowerColor, 'Visible', 'on') set(opt.handles.button.incrUpperColor, 'Enable', 'on'); set(opt.handles.button.decrLowerColor, 'Enable', 'on'); if get(opt.handles.checkbox.symmetric, 'Value') % maxabs set(opt.handles.button.decrUpperColor, 'Enable', 'off'); set(opt.handles.button.incrLowerColor, 'Enable', 'off'); zmax = max(abs(caxis(opt.handles.axes.movie))); zmin = -zmax; else set(opt.handles.button.decrUpperColor, 'Enable', 'on'); set(opt.handles.button.incrLowerColor, 'Enable', 'on'); [zmin zmax] = caxis(opt.handles.axes.movie); end end % incr, decr, automatic, else maps = get(opt.handles.menu.colormap, 'String'); cmap = colormap(opt.handles.axes.movie, maps{get(opt.handles.menu.colormap, 'Value')}); adjust_colorbar(opt); if (gcf~=opt.handles.figure) close gcf; % sometimes there is a new window that opens up end caxis(opt.handles.axes.movie, [zmin zmax]); yTick = linspace(zmin, zmax, yLim(end)); % truncate intelligently/-ish yTick = yTick(get(opt.handles.colorbar, 'YTick')); yTick = num2str(yTick', 5); set(opt.handles.colorbar, 'YTickLabel', yTick, 'FontSize', 8); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % CALLBACK FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cb_startDrag(h, eventdata) f = get(h, 'Parent'); while ~strcmp(get(f, 'Tag'), 'mainFigure') f = get(f, 'Parent'); end opt = guidata(f); opt.handles.current.line = h; if strfind(get(h, 'Tag'), 'Color')>0 opt.handles.current.axes = opt.handles.colorbar; opt.handles.current.color = true; else disp('Figure out if it works for xparam and yparam'); keyboard end set(f, 'WindowButtonMotionFcn', @cb_dragLine); guidata(h, opt); end function cb_dragLine(h, eventdata) opt = guidata(h); pt = get(opt.handles.current.axes, 'CurrentPoint'); yLim = get(opt.handles.colorbar, 'YLim'); % upper (lower) bar must not below (above) lower (upper) bar if ~(opt.handles.current.line == opt.handles.lines.upperColor && ... (any(pt(3)*[1 1]<get(opt.handles.lines.lowerColor, 'YData')) || ... yLim(end) <= pt(3))) ... && ~(opt.handles.current.line == opt.handles.lines.lowerColor && ... (any(pt(3)*[1 1]>get(opt.handles.lines.upperColor, 'YData')) || ... yLim(1) >= pt(3))) set(opt.handles.current.line, 'YData', pt(3)*[1 1]); end adjust_colorbar(opt); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function adjust_colorbar(opt) % adjust colorbar upper = get(opt.handles.lines.upperColor, 'YData'); lower = get(opt.handles.lines.lowerColor, 'YData'); if any(round(upper)==0) || any(round(lower)==0) return; end maps = get(opt.handles.menu.colormap, 'String'); cmap = colormap(opt.handles.axes.movie, maps{get(opt.handles.menu.colormap, 'Value')}); cmap(round(lower(1)):round(upper(1)), :) = repmat(cmap(round(lower(1)), :), 1+round(upper(1))-round(lower(1)), 1); colormap(opt.handles.axes.movie, cmap); end function cb_stopDrag(h, eventdata) while ~strcmp(get(h, 'Tag'), 'mainFigure') h = get(h, 'Parent'); end set(h, 'WindowButtonMotionFcn', ''); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function opt = prepareBrainplot(opt) if opt.issource if isfield(opt, 'sulc') vdat = opt.sulc; vdat(vdat>0.5) = 0.5; vdat(vdat<-0.5)= -0.5; vdat = vdat-min(vdat); vdat = 0.35.*(vdat./max(vdat))+0.3; vdat = repmat(vdat,[1 3]); mesh = ft_plot_mesh(opt.anatomy, 'edgecolor', 'none', 'vertexcolor', vdat); else mesh = ft_plot_mesh(opt.anatomy, 'edgecolor', 'none', 'facecolor', [0.5 0.5 0.5]); end lighting gouraud set(mesh, 'Parent', opt.handles.axes.movie); % mesh = ft_plot_mesh(source, 'edgecolor', 'none', 'vertexcolor', 0*opt.dat(:,1,1), 'facealpha', 0*opt.mask(:,1,1)); opt.handles.mesh = ft_plot_mesh(opt.anatomy, 'edgecolor', 'none', 'vertexcolor', opt.dat(:,1,1)); set(opt.handles.mesh, 'AlphaDataMapping', 'scaled'); set(opt.handles.mesh, 'FaceAlpha', 'interp'); set(opt.handles.mesh, 'FaceVertexAlphaData', opt.mask(:,1,1)); lighting gouraud cam1 = camlight('left'); set(cam1, 'Parent', opt.handles.axes.movie); cam2 = camlight('right'); set(cam2, 'Parent', opt.handles.axes.movie); set(opt.handles.mesh, 'Parent', opt.handles.axes.movie); % cameratoolbar(opt.handles.figure, 'Show'); else axes(opt.handles.axes.movie) [dum, opt.handles.grid] = ft_plot_topo(opt.layout.pos(sellay,1), opt.layout.pos(sellay,2), zeros(numel(sellay),1), 'mask', opt.layout.mask, 'outline', opt.layout.outline, 'interpmethod', 'v4', 'interplim', 'mask', 'parent', opt.handles.axes.movie); %[dum, opt.handles.grid] = ft_plot_topo(layout.pos(sellay,1), layout.pos(sellay,2), zeros(numel(sellay),1), 'mask',layout.mask, 'outline', layout.outline, 'interpmethod', 'v4', 'interplim', 'mask', 'parent', opt.handles.axes.movie); % set(opt.handles.grid, 'Parent', opt.handles.axes.movie); opt.xdata = get(opt.handles.grid, 'xdata'); opt.ydata = get(opt.handles.grid, 'ydata'); opt.nanmask = 1-get(opt.handles.grid, 'cdata'); if (gcf~=opt.handles.figure) close gcf; % sometimes there is a new window that opens up end end end
github
philippboehmsturm/antx-master
nanvar.m
.m
antx-master/xspm8/external/fieldtrip/private/nanvar.m
1,093
utf_8
d9641af3bba1e2c6e3512199221e686c
% NANVAR provides a replacement for MATLAB's nanvar that is almost % compatible. % % For usage see VAR. Note that the weight-vector is not supported. If you % need it, please file a ticket at our bugtracker. function Y = nanvar(X, w, dim) switch nargin case 1 % VAR(x) % Normalize by n-1 when no dim is given. Y = nanvar_base(X); n = nannumel(X); w = 0; case 2 % VAR(x, 1) % VAR(x, w) % In this case, the default of normalizing by n is expected. Y = nanvar_base(X); n = nannumel(X); case 3 % VAR(x, w, dim) % if w=0 normalize by n-1, if w=1 normalize by n. Y = nanvar_base(X, dim); n = nannumel(X, dim); otherwise error ('Too many input arguments!') end % Handle different forms of normalization: if numel(w) == 0 % empty weights vector defaults to 0 w = 0; end if numel(w) ~= 1 error('Weighting vector w is not implemented! Please file a bug.'); end if ~isreal(X) Y = real(Y) + imag(Y); n = real(n); end if w == 1 Y = Y ./ n; end if w == 0 Y = Y ./ max(1, (n - 1)); % don't divide by zero! end
github
philippboehmsturm/antx-master
tinv.m
.m
antx-master/xspm8/external/fieldtrip/private/tinv.m
7,634
utf_8
8fe66ec125f91e1a7ac5f8d3cb2ac51a
function x = tinv(p,v); % TINV Inverse of Student's T cumulative distribution function (cdf). % X=TINV(P,V) returns the inverse of Student's T cdf with V degrees % of freedom, at the values in P. % % The size of X is the common size of P and V. A scalar input % functions as a constant matrix of the same size as the other input. % % This is an open source function that was assembled by Eric Maris using % open source subfunctions found on the web. % Subversion does not use the Log keyword, use 'svn log <filename>' or 'svn -v log | less' to get detailled information if nargin < 2, error('Requires two input arguments.'); end [errorcode p v] = distchck(2,p,v); if errorcode > 0 error('Requires non-scalar arguments to match in size.'); end % Initialize X to zero. x=zeros(size(p)); k = find(v < 0 | v ~= round(v)); if any(k) tmp = NaN; x(k) = tmp(ones(size(k))); end k = find(v == 1); if any(k) x(k) = tan(pi * (p(k) - 0.5)); end % The inverse cdf of 0 is -Inf, and the inverse cdf of 1 is Inf. k0 = find(p == 0); if any(k0) tmp = Inf; x(k0) = -tmp(ones(size(k0))); end k1 = find(p ==1); if any(k1) tmp = Inf; x(k1) = tmp(ones(size(k1))); end k = find(p >= 0.5 & p < 1); if any(k) z = betainv(2*(1-p(k)),v(k)/2,0.5); x(k) = sqrt(v(k) ./ z - v(k)); end k = find(p < 0.5 & p > 0); if any(k) z = betainv(2*(p(k)),v(k)/2,0.5); x(k) = -sqrt(v(k) ./ z - v(k)); end %%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION distchck %%%%%%%%%%%%%%%%%%%%%%%%% function [errorcode,varargout] = distchck(nparms,varargin) %DISTCHCK Checks the argument list for the probability functions. errorcode = 0; varargout = varargin; if nparms == 1 return; end % Get size of each input, check for scalars, copy to output isscalar = (cellfun('prodofsize',varargin) == 1); % Done if all inputs are scalars. Otherwise fetch their common size. if (all(isscalar)), return; end n = nparms; for j=1:n sz{j} = size(varargin{j}); end t = sz(~isscalar); size1 = t{1}; % Scalars receive this size. Other arrays must have the proper size. for j=1:n sizej = sz{j}; if (isscalar(j)) t = zeros(size1); t(:) = varargin{j}; varargout{j} = t; elseif (~isequal(sizej,size1)) errorcode = 1; return; end end %%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION betainv %%%%%%%%%%%%%%%%%%%%%%%%%%% function x = betainv(p,a,b); %BETAINV Inverse of the beta cumulative distribution function (cdf). % X = BETAINV(P,A,B) returns the inverse of the beta cdf with % parameters A and B at the values in P. % % The size of X is the common size of the input arguments. A scalar input % functions as a constant matrix of the same size as the other inputs. % % BETAINV uses Newton's method to converge to the solution. % Reference: % [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical % Functions", Government Printing Office, 1964. % B.A. Jones 1-12-93 if nargin < 3, error('Requires three input arguments.'); end [errorcode p a b] = distchck(3,p,a,b); if errorcode > 0 error('Requires non-scalar arguments to match in size.'); end % Initialize x to zero. x = zeros(size(p)); % Return NaN if the arguments are outside their respective limits. k = find(p < 0 | p > 1 | a <= 0 | b <= 0); if any(k), tmp = NaN; x(k) = tmp(ones(size(k))); end % The inverse cdf of 0 is 0, and the inverse cdf of 1 is 1. k0 = find(p == 0 & a > 0 & b > 0); if any(k0), x(k0) = zeros(size(k0)); end k1 = find(p==1); if any(k1), x(k1) = ones(size(k1)); end % Newton's Method. % Permit no more than count_limit interations. count_limit = 100; count = 0; k = find(p > 0 & p < 1 & a > 0 & b > 0); pk = p(k); % Use the mean as a starting guess. xk = a(k) ./ (a(k) + b(k)); % Move starting values away from the boundaries. if xk == 0, xk = sqrt(eps); end if xk == 1, xk = 1 - sqrt(eps); end h = ones(size(pk)); crit = sqrt(eps); % Break out of the iteration loop for the following: % 1) The last update is very small (compared to x). % 2) The last update is very small (compared to 100*eps). % 3) There are more than 100 iterations. This should NEVER happen. while(any(abs(h) > crit * abs(xk)) & max(abs(h)) > crit ... & count < count_limit), count = count+1; h = (betacdf(xk,a(k),b(k)) - pk) ./ betapdf(xk,a(k),b(k)); xnew = xk - h; % Make sure that the values stay inside the bounds. % Initially, Newton's Method may take big steps. ksmall = find(xnew < 0); klarge = find(xnew > 1); if any(ksmall) | any(klarge) xnew(ksmall) = xk(ksmall) /10; xnew(klarge) = 1 - (1 - xk(klarge))/10; end xk = xnew; end % Return the converged value(s). x(k) = xk; if count==count_limit, fprintf('\nWarning: BETAINV did not converge.\n'); str = 'The last step was: '; outstr = sprintf([str,'%13.8f'],h); fprintf(outstr); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION betapdf %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = betapdf(x,a,b) %BETAPDF Beta probability density function. % Y = BETAPDF(X,A,B) returns the beta probability density % function with parameters A and B at the values in X. % % The size of Y is the common size of the input arguments. A scalar input % functions as a constant matrix of the same size as the other inputs. % References: % [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical % Functions", Government Printing Office, 1964, 26.1.33. if nargin < 3, error('Requires three input arguments.'); end [errorcode x a b] = distchck(3,x,a,b); if errorcode > 0 error('Requires non-scalar arguments to match in size.'); end % Initialize Y to zero. y = zeros(size(x)); % Return NaN for parameter values outside their respective limits. k1 = find(a <= 0 | b <= 0 | x < 0 | x > 1); if any(k1) tmp = NaN; y(k1) = tmp(ones(size(k1))); end % Return Inf for x = 0 and a < 1 or x = 1 and b < 1. % Required for non-IEEE machines. k2 = find((x == 0 & a < 1) | (x == 1 & b < 1)); if any(k2) tmp = Inf; y(k2) = tmp(ones(size(k2))); end % Return the beta density function for valid parameters. k = find(~(a <= 0 | b <= 0 | x <= 0 | x >= 1)); if any(k) y(k) = x(k) .^ (a(k) - 1) .* (1 - x(k)) .^ (b(k) - 1) ./ beta(a(k),b(k)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION betacdf %%%%%%%%%%%%%%%%%%%%%%%%%%%% function p = betacdf(x,a,b); %BETACDF Beta cumulative distribution function. % P = BETACDF(X,A,B) returns the beta cumulative distribution % function with parameters A and B at the values in X. % % The size of P is the common size of the input arguments. A scalar input % functions as a constant matrix of the same size as the other inputs. % % BETAINC does the computational work. % Reference: % [1] M. Abramowitz and I. A. Stegun, "Handbook of Mathematical % Functions", Government Printing Office, 1964, 26.5. if nargin < 3, error('Requires three input arguments.'); end [errorcode x a b] = distchck(3,x,a,b); if errorcode > 0 error('Requires non-scalar arguments to match in size.'); end % Initialize P to 0. p = zeros(size(x)); k1 = find(a<=0 | b<=0); if any(k1) tmp = NaN; p(k1) = tmp(ones(size(k1))); end % If is X >= 1 the cdf of X is 1. k2 = find(x >= 1); if any(k2) p(k2) = ones(size(k2)); end k = find(x > 0 & x < 1 & a > 0 & b > 0); if any(k) p(k) = betainc(x(k),a(k),b(k)); end % Make sure that round-off errors never make P greater than 1. k = find(p > 1); p(k) = ones(size(k));
github
philippboehmsturm/antx-master
prepare_timefreq_data.m
.m
antx-master/xspm8/external/fieldtrip/private/prepare_timefreq_data.m
23,749
utf_8
70b5b3af723b814cdf5e9ac09f3c3317
function [cfg, data] = prepare_timefreq_data(cfg, varargin); % PREPARE_TIMEFREQ_DATA collects the overlapping data from multiple ERPs % or ERFs according to the channel/time/freq-selection in the configuration % and returns it with a dimord of 'repl_chan_freq_time'. % % Supported input data is from TIMELOCKANALYSIS, TIMELOCKGRANDAVERAGE, % FREQANALYSIS or FREQDESCRIPTIVES. % % Use as % [cfg, data] = prepare_timefreq_data(cfg, varargin) % where the configuration can contain % cfg.channel = cell-array of size Nx1, see CHANNELSELECTION, or % cfg.channelcmb = cell-array of size Nx2, see CHANNELCOMBINATION % cfg.latency = [begin end], can be 'all' (default) % cfg.frequency = [begin end], can be 'all' (default) % cfg.avgoverchan = 'yes' or 'no' (default) % cfg.avgovertime = 'yes' or 'no' (default) % cfg.avgoverfreq = 'yes' or 'no' (default) % cfg.datarepresentation = 'cell-array' or 'concatenated' % cfg.precision = 'single' or 'double' (default) % % If the data contains both power- and cross-spectra, they will be concatenated % and treated together. In that case you should specify cfg.channelcmb instead % of cfg.channel. % % This function can serve as a subfunction for TIMEFREQRANDOMIZATION, % TIMEFREQCLUSTER and other statistical functions, so that those functions % do not have to do the bookkeeping themselves. % KNOWN BUGS AND LIMITATIONS % copying of data is not memory efficient for cell-array output % cfg.precision is not used for cell-array output % Copyright (C) 2004, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: prepare_timefreq_data.m 7123 2012-12-06 21:21:38Z roboos $ % set the defaults if ~isfield(cfg, 'channel'), cfg.channel = 'all'; end if ~isfield(cfg, 'channelcmb'), cfg.channelcmb = []; end if ~isfield(cfg, 'latency'), cfg.latency = 'all'; end if ~isfield(cfg, 'frequency'), cfg.frequency = 'all'; end if ~isfield(cfg, 'avgoverchan'), cfg.avgoverchan = 'no'; end if ~isfield(cfg, 'avgovertime'), cfg.avgovertime = 'no'; end if ~isfield(cfg, 'avgoverfreq'), cfg.avgoverfreq = 'no'; end if ~isfield(cfg, 'datarepresentation'), cfg.datarepresentation = 'cell-array'; end if ~isfield(cfg, 'precision'), cfg.precision = 'double'; end % initialize containsdof = false; % count the number of input datasets Nvarargin = length(varargin); remember = {}; % initialize swapmemfile; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % collect information over all data sets required for a consistent selection % this is the first time that the data will be swapped from file into memory %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for c=1:Nvarargin % swap the data into memory varargin{c} = swapmemfile(varargin{c}); % for backward compatibility with old data structures varargin{c} = fixdimord(varargin{c}); % reformat the data, and combine cross and power spectra [remember{c}, hascrsspctrm] = forcedimord(varargin{c}); % keep a small part of the data in memory if hascrsspctrm remember{c} = rmfield(remember{c}, 'dat'); remember{c} = rmfield(remember{c}, 'crs'); else remember{c} = rmfield(remember{c}, 'dat'); end % swap the data out of memory varargin{c} = swapmemfile(varargin{c}); end if hascrsspctrm % by default this should be empty cfg.channel = []; if isempty(cfg.channelcmb) % default is to copy the channelcombinations from the first dataset % and these have been concatenated by forcedimord -> tear them apart cfg.channelcmb = label2cmb(remember{1}.label); end % instead of matching channelcombinations, we will match channels that % consist of the concatenated labels of the channelcombinations cfg.channel = cmb2label(cfg.channelcmb); cfg.channelcmb = []; % this will be reconstructed at the end else % by default this should be empty cfg.channelcmb = []; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % adjust the selection of channels, latency and frequency so that it % matches with all datasets %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for c=1:Nvarargin % match the channel selection with this dataset cfg.channel = ft_channelselection(cfg.channel, remember{c}.label); % match the selected latency with this dataset if isempty(findstr(remember{c}.dimord, 'time')) || all(isnan(remember{c}.time)) cfg.latency = []; elseif ischar(cfg.latency) && strcmp(cfg.latency, 'all') cfg.latency = []; cfg.latency(1) = min(remember{c}.time); cfg.latency(2) = max(remember{c}.time); else cfg.latency(1) = max(cfg.latency(1), min(remember{c}.time)); cfg.latency(2) = min(cfg.latency(2), max(remember{c}.time)); end % match the selected frequency with this dataset if isempty(findstr(remember{c}.dimord, 'freq')) || all(isnan(remember{c}.freq)) cfg.frequency = []; elseif ischar(cfg.frequency) && strcmp(cfg.frequency, 'all') cfg.frequency = []; cfg.frequency(1) = min(remember{c}.freq); cfg.frequency(2) = max(remember{c}.freq); else cfg.frequency(1) = max(cfg.frequency(1), min(remember{c}.freq)); cfg.frequency(2) = min(cfg.frequency(2), max(remember{c}.freq)); end % keep track of the number of replications Nrepl(c) = length(remember{c}.repl); end % count the number of channels, time bins and frequency bins dimord = remember{c}.dimord; if ~isempty(cfg.latency) && ~all(isnan(cfg.latency)) timesel = nearest(remember{1}.time, cfg.latency(1)):nearest(remember{1}.time, cfg.latency(2)); else timesel = 1; end if ~isempty(cfg.frequency) && ~all(isnan(cfg.frequency)) freqsel = nearest(remember{1}.freq, cfg.frequency(1)):nearest(remember{1}.freq, cfg.frequency(2)); else freqsel = 1; end Nchan = length(cfg.channel); Ntime = length(timesel); Nfreq = length(freqsel); if ~hascrsspctrm % print the information for channels if Nchan<1 error('channel selection is empty') elseif strcmp(cfg.avgoverchan, 'yes') fprintf('averaging over %d channels\n', Nchan); Nchan = 1; % after averaging else fprintf('selected %d channels\n', Nchan); end else % print the (same) information for channelcombinations if Nchan<1 error('channelcombination selection is empty') elseif strcmp(cfg.avgoverchan, 'yes') fprintf('averaging over %d channelcombinations\n', Nchan); Nchan = 1; % after averaging else fprintf('selected %d channelcombinations\n', Nchan); end end if Ntime<1 error('latency selection is empty') elseif strcmp(cfg.avgovertime, 'yes') fprintf('averaging over %d time bins\n', Ntime); Ntime = 1; % after averaging else fprintf('selected %d time bins\n', Ntime); end if Nfreq<1 error('latency selection is empty') elseif strcmp(cfg.avgoverfreq, 'yes') fprintf('averaging over %d frequency bins\n', Nfreq); Nfreq = 1; % after averaging else fprintf('selected %d frequency bins\n', Nfreq); end % determine whether, and over which dimensions the data should be averaged tok = tokenize(dimord, '_'); chandim = find(strcmp(tok, 'chan')); timedim = find(strcmp(tok, 'time')); freqdim = find(strcmp(tok, 'freq')); avgdim = []; if strcmp(cfg.avgoverchan, 'yes') && ~isempty(chandim) avgdim = [avgdim chandim]; end if strcmp(cfg.avgovertime, 'yes') && ~isempty(timedim) avgdim = [avgdim timedim]; end if strcmp(cfg.avgoverfreq, 'yes') && ~isempty(freqdim) avgdim = [avgdim freqdim]; end % this will hold the output data if strcmp(cfg.datarepresentation, 'cell-array') dat = {}; dof = {}; elseif strcmp(cfg.datarepresentation, 'concatenated') % preallocate memory to hold all the data if hascrsspctrm if str2num(version('-release'))>=14 dat = complex(zeros(sum(Nrepl), Nchan, Nfreq, Ntime, cfg.precision)); else % use double precision for default and Matlab versions prior to release 14 if ~strcmp(cfg.precision, 'double') warning('Matlab versions prior to release 14 only support double precision'); end dat = complex(zeros(sum(Nrepl), Nchan, Nfreq, Ntime)); end else if str2num(version('-release'))>=14 dat = zeros(sum(Nrepl), Nchan, Nfreq, Ntime, cfg.precision); else % use double precision for default and Matlab versions prior to release 14 if ~strcmp(cfg.precision, 'double') warning('Matlab versions prior to release 14 only support double precision'); end dat = zeros(sum(Nrepl), Nchan, Nfreq, Ntime); end end if isempty(avgdim) dof = zeros(sum(Nrepl), Nfreq, Ntime); end; else error('unsupported output data representation'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % select the desired channels, latency and frequency bins from each dataset % this is the second time that the data will be swapped from file into memory %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% for c=1:Nvarargin % swap the data into memory varargin{c} = swapmemfile(varargin{c}); % reformat the data, and combine cross and power spectra [varargin{c}, hascrsspctrm] = forcedimord(varargin{c}); % select the channels, sorted according to the order in the configuration [dum, chansel] = match_str(cfg.channel, varargin{c}.label); if ~isempty(cfg.latency) timesel = nearest(varargin{c}.time, cfg.latency(1)):nearest(varargin{c}.time, cfg.latency(2)); end if ~isempty(cfg.frequency) freqsel = nearest(varargin{c}.freq, cfg.frequency(1)):nearest(varargin{c}.freq, cfg.frequency(2)); end if hascrsspctrm Nfreq = size(varargin{c}.crs, 3); Ntime = size(varargin{c}.crs, 4); % separate selection for the auto-spectra and cross-spectra Ndat = size(varargin{c}.dat, 2); % count the total number of auto-spectra Ncrs = size(varargin{c}.crs, 2); % count the total number of cross-spectra [dum, chansel_dat] = ismember(chansel, 1:Ndat); % selection of auto-spectra chansel_dat=chansel_dat(chansel_dat~=0)'; [dum, chansel_crs] = ismember(chansel, (1:Ncrs)+Ndat); % selection of cross-spectra chansel_crs=chansel_crs(chansel_crs~=0)'; Ndatsel = length(chansel_dat); % count the number of selected auto-spectra Ncrssel = length(chansel_crs); % count the number of selected cross-spectra else Nfreq = size(varargin{c}.dat, 3); Ntime = size(varargin{c}.dat, 4); end % collect the data, average if required if strcmp(cfg.datarepresentation, 'cell-array') if hascrsspctrm dat{c} = cat(2, avgoverdim(varargin{c}.dat(:, chansel_dat, freqsel, timesel), avgdim), avgoverdim(varargin{c}.crs(:, chansel_crs, freqsel, timesel), avgdim)); else dat{c} = avgoverdim(varargin{c}.dat(:, chansel, freqsel, timesel), avgdim); end if isfield(varargin{c},'dof') containsdof = isempty(avgdim); if containsdof dof{c} = varargin{c}.dof(:,freqsel,timesel); else warning('Degrees of freedom cannot be calculated if averaging over channels, frequencies, or time bins is requested.'); end; end; elseif strcmp(cfg.datarepresentation, 'concatenated') if c==1 trialsel = 1:Nrepl(1); else trialsel = (1+sum(Nrepl(1:(c-1)))):sum(Nrepl(1:c)); end % THIS IS IMPLEMENTED WITH STRICT MEMORY CONSIDERATIONS % handle cross-spectrum and auto-spectrum separately % first copy complex part (crs) then real part (pow), otherwise dat first will be made real and then complex again % copy selection of "all" as complete matrix and not as selection % copy selection with for loops (not yet implemented below) if isempty(avgdim) && hascrsspctrm if length(chansel_crs)==Ncrs && length(freqsel)==Nfreq && length(timesel)==Ntime && all(chansel_crs==(1:Ncrs)) && all(freqsel==(1:Nfreq)) && all(timesel==(1:Ntime)) % copy everything into the output data array % this is more memory efficient than selecting everything dat(trialsel,(1:Ncrssel)+Ndatsel,:,:) = varargin{c}.crs; else % copy only a selection into the output data array % this could be made more memory efficient using for-loops dat(trialsel,(1:Ncrssel)+Ndatsel,:,:) = varargin{c}.crs(:, chansel_crs, freqsel, timesel); end dat(trialsel,1:Ndatsel,:,:) = varargin{c}.dat(:, chansel_dat, freqsel, timesel); elseif ~isempty(avgdim) && hascrsspctrm if length(chansel_crs)==Ncrs && length(freqsel)==Nfreq && length(timesel)==Ntime && all(chansel_crs==(1:Ncrs)) && all(freqsel==(1:Nfreq)) && all(timesel==(1:Ntime)) % copy everything into the output data array % this is more memory efficient than selecting everything dat(trialsel,(1:Ncrssel)+Ndatsel,:,:) = avgoverdim(varargin{c}.crs, avgdim); else % copy only a selection into the output data array % this could be made more memory efficient using for-loops dat(trialsel,(1:Ncrssel)+Ndatsel,:,:) = avgoverdim(varargin{c}.crs(:, chansel_crs, freqsel, timesel), avgdim); end dat(trialsel,1:Ndatsel,:,:) = avgoverdim(varargin{c}.dat(:, chansel_dat, freqsel, timesel), avgdim); elseif isempty(avgdim) && ~hascrsspctrm dat(trialsel,:,:,:) = varargin{c}.dat(:, chansel, freqsel, timesel); elseif ~isempty(avgdim) && ~hascrsspctrm dat(trialsel,:,:,:) = avgoverdim(varargin{c}.dat(:, chansel, freqsel, timesel), avgdim); end if isfield(varargin{c},'dof') containsdof = isempty(avgdim); if containsdof dof(trialsel,:,:) = varargin{c}.dof(:,freqsel,timesel); else warning('Degrees of freedom cannot be calculated if averaging over channels, frequencies, or time bins is requested.'); end; end; end % swap the data out of memory varargin{c} = swapmemfile(varargin{c}); end % collect the output data data.biol = dat; data.dimord = dimord; if containsdof data.dof = dof; end; if strcmp(cfg.datarepresentation, 'concatenated') % all trials are combined together, construct a design matrix to ensure % that they can be identified afterwards data.design(:,1) = 1:sum(Nrepl); for c=1:Nvarargin if c==1 trialsel = 1:Nrepl(1); else trialsel = (1+sum(Nrepl(1:(c-1)))):sum(Nrepl(1:c)); end data.design(trialsel,2) = 1:length(trialsel); data.design(trialsel,3) = c; end end if ~hascrsspctrm if strcmp(cfg.avgoverchan, 'yes') concatlabel = sprintf('%s+', remember{end}.label{chansel}); % concatenate the labels with a '+' in between concatlabel(end) = []; % remove the last '+' data.label = {concatlabel}; % this should be a cell-array else data.label = remember{end}.label(chansel); end else % specify the correct dimord and channelcombinations labelcmb = label2cmb(remember{end}.label(chansel)); if strcmp(cfg.avgoverchan, 'yes') % the cross-spectra have been averaged, therefore there is only one combination left str1 = sprintf('%s+', labelcmb{:,1}); str1(end) = []; str2 = sprintf('%s+', labelcmb{:,2}); str2(end) = []; data.labelcmb = {str1, str2}; else data.labelcmb = labelcmb; end % the dimord should specify chancmb instead of chan s = strfind(dimord, 'chan'); data.dimord = [data.dimord(1:(s-1)) 'chancmb' data.dimord((s+4):end)]; end if ~all(isnan(cfg.latency)) if strcmp(cfg.avgovertime, 'yes') data.time = mean(remember{end}.time(timesel)); else data.time = remember{end}.time(timesel); end else % the output data contains a time dimension, but the input data did not contain a time axis data.time = nan; cfg.latency = []; end if ~all(isnan(cfg.frequency)) if strcmp(cfg.avgoverfreq, 'yes') data.freq = mean(remember{end}.freq(freqsel)); else data.freq = remember{end}.freq(freqsel); end else % the output data contains a freq dimension, but the input data did not contain a freq axis data.freq = nan; cfg.frequency = []; end % add version information to the configuration cfg.version.name = mfilename('fullpath'); cfg.version.id = '$Id: prepare_timefreq_data.m 7123 2012-12-06 21:21:38Z roboos $'; cfg.previous = []; % remember the configuration details from the input data for c=1:Nvarargin try, cfg.previous{c} = remember{c}.cfg; end end % remember the full configuration details data.cfg = cfg; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to help with the averaging over multiple dimensions at the % same time. Furthermore, the output data will have the same NUMBER of % dimensions as the input data (i.e. no squeezing) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [dat] = avgoverdim(dat, dim); siz = size(dat); siz((end+1):4) = 1; % this should work at least up to 4 dimensions, also if not present in the data for i=dim siz(i) = 1; dat = mean(dat, i); % compute the mean over this dimension dat = reshape(dat, siz); % ensure that the number of dimenstions remains the same end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that reformats the data into a consistent struct with a fixed % dimord and that combines power and cross-spectra %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [output, hascrsspctrm] = forcedimord(input); % for backward compatibility with old timelockanalysis data that does not contain a dimord if ~isfield(input, 'dimord') && isfield(input, 'avg') && isfield(input, 'var') && isfield(input, 'trial') input.dimord = 'repl_chan_time'; elseif ~isfield(input, 'dimord') && isfield(input, 'avg') && isfield(input, 'var') && ~isfield(input, 'trial') input.dimord = 'chan_time'; end outputdim = tokenize('repl_chan_freq_time', '_'); inputdim = tokenize(input.dimord, '_'); % ensure consistent names of the dimensions try, inputdim{strcmp(inputdim, 'rpt')} = 'repl'; end; try, inputdim{strcmp(inputdim, 'rpttap')} = 'repl'; end; try, inputdim{strcmp(inputdim, 'trial')} = 'repl'; end; try, inputdim{strcmp(inputdim, 'subj')} = 'repl'; end; try, inputdim{strcmp(inputdim, 'sgncmb')} = 'chan'; end; try, inputdim{strcmp(inputdim, 'sgn')} = 'chan'; end; try, inputdim{strcmp(inputdim, 'frq')} = 'freq'; end; try, inputdim{strcmp(inputdim, 'tim')} = 'time'; end; try, output.cfg = input.cfg; end; % general try, output.time = input.time; end; % for ERPs and TFRs try, output.freq = input.freq; end; % for frequency data if isfield(input, 'powspctrm') && isfield(input, 'crsspctrm') hascrsspctrm = 1; chandim = find(strcmp(inputdim, 'chan')); % concatenate powspctrm and crsspctrm % output.dat = cat(chandim, input.powspctrm, input.crsspctrm); % seperate output for auto and cross-spectra output.dat = input.powspctrm; output.crs = input.crsspctrm; % concatenate the labels of the channelcombinations into one Nx1 cell-array output.label = cmb2label([[input.label(:) input.label(:)]; input.labelcmb]); elseif isfield(input, 'powspctrm') hascrsspctrm = 0; % output only power spectrum output.dat = input.powspctrm; output.label = input.label; elseif isfield(input, 'fourierspctrm') hascrsspctrm = 0; % output only fourier spectrum output.dat = input.fourierspctrm; output.label = input.label; else hascrsspctrm = 0; try, output.dat = input.avg; end; % for average ERP try, output.dat = input.trial; end; % for average ERP with keeptrial try, output.dat = input.individual; end; % for grandaverage ERP with keepsubject output.label = input.label; end % determine the size of each dimension repldim = find(strcmp(inputdim, 'repl')); chandim = find(strcmp(inputdim, 'chan')); freqdim = find(strcmp(inputdim, 'freq')); timedim = find(strcmp(inputdim, 'time')); if isempty(repldim) Nrepl = 1; else Nrepl = size(output.dat, repldim); end if isempty(chandim) error('data must contain channels'); else if hascrsspctrm Nchan = size(output.dat, chandim) + size(output.crs, chandim); Ncrs = size(output.crs, chandim); else Nchan = size(output.dat, chandim); end end if isempty(freqdim) Nfreq = 1; else Nfreq = size(output.dat, freqdim); end if isempty(timedim) Ntime = 1; else Ntime = size(output.dat, timedim); end % find the overlapping dimensions in the input and output [dum, inputorder, outputorder] = intersect(inputdim, outputdim); % sort them according to the specified output dimensions [outputorder, indx] = sort(outputorder); inputorder = inputorder(indx); % rearrange the input dimensions in the same order as the desired output if ~all(inputorder==sort(inputorder)) if hascrsspctrm output.dat = permute(output.dat, inputorder); output.crs = permute(output.crs, inputorder); else output.dat = permute(output.dat, inputorder); end end % reshape the data so that it contains the (optional) singleton dimensions if ~(size(output.dat,1)==Nrepl && size(output.dat,2)==Nchan && size(output.dat,3)==Nfreq && size(output.dat,4)==Ntime) if hascrsspctrm output.dat = reshape(output.dat, Nrepl, Nchan-Ncrs, Nfreq, Ntime); output.crs = reshape(output.crs, Nrepl, Ncrs , Nfreq, Ntime); else output.dat = reshape(output.dat, Nrepl, Nchan, Nfreq, Ntime); end end if isfield(input,'dof') && numel(input.dof)==Nrepl*Nfreq*Ntime output.dof=reshape(input.dof, Nrepl, Nfreq, Ntime); end; % add the fields that describe the axes of the data if ~isfield(output, 'time') output.time = nan; end if ~isfield(output, 'freq') output.freq = nan; end % create replication axis, analogous to time and frequency axis output.repl = 1:Nrepl; output.dimord = 'repl_chan_freq_time'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION convert Nx2 cell array with channel combinations into Nx1 cell array with labels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label = cmb2label(labelcmb); label = {}; for i=1:size(labelcmb) label{i,1} = [labelcmb{i,1} '&' labelcmb{i,2}]; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION convert Nx1 cell array with labels into N2x cell array with channel combinations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function labelcmb = label2cmb(label); labelcmb = {}; for i=1:length(label) labelcmb(i,1:2) = tokenize(label{i}, '&'); end
github
philippboehmsturm/antx-master
bsscca.m
.m
antx-master/xspm8/external/fieldtrip/private/bsscca.m
7,428
utf_8
d64d6dd63efc92dff2aabe9e03c7dbb1
function [w,rho] = bsscca(X, delay) % BSSCCA computes the unmixing matrix based on the canonical correlation between a signal and its lagged-one copy. It implements the algorithm described in [1] % % DeClercq et al 2006, IEEE Biomed Eng 2583. if nargin<2, delay = 1; end % hmmmm we need to observe the epochs' boundaries to not create rubbish % support cell array input if isa(X, 'cell') delay = setdiff(delay(:)', 0); n = size(X{1},1); mX = cellmean(X,2); X = cellvecadd(X, -mX); C = cellcovshift(X,[0 delay],2,0); m = size(C,1)-n; XY = C(1:n, (n+1):end); % cross terms XY XX = C(1:n, 1:n); % auto terms X; YY = C((n+1):end, (n+1):end); % auto terms Y YX = C((n+1):end, 1:n); %A(1:n,1:n) = 0; %A((n+1):end,(n+1):end) = 0; %B(1:n,(n+1):end) = 0; %B((n+1):end,1:n) = 0; else % input is a single data matrix assumed to be a continuous stretch [n,m] = size(X); % get the means %m = ones(1,m-1); %mX = mean(X(:,2:end),2); % lag zero %mX2 = mean(X(:,1:end-1),2); % lag one % use Borga's (2001) formulation from 'a unified approach to PCA, PLS, MLR % and CCA' A = zeros(2*n); B = zeros(2*n); if numel(delay)==1 Xlag = X(:,1:(m-delay)); else end XY = X(:,delay+(1:(m-delay)))*Xlag'; XX = X(:,delay+(1:(m-delay)))*X(:,delay+(1:(m-delay)))'; YY = Xlag*Xlag'; %XY = (X(:,2:end)-mX*m)*(X(:,1:end-1)-mX2*m)'; A(1:n,(n+1):end) = XY; A((n+1):end,1:n) = XY'; B(1:n,1:n) = XX; B((n+1):end,(n+1):end) = YY; %B(1:n,1:n) = (X(:,2:end)-mX*m)*(X(:,2:end)-mX*m)'; %B((n+1):end,(n+1):end) = (X(:,1:end-1)-mX2*m)*(X(:,1:end-1)-mX2*m)'; end %if cond(B)>1e8 % s = svd(B); % [w,rho] = eig((B+eye(size(B,1))*s(1)*0.00000001)\A); %else % [w,rho] = eig(B\A); %end if cond(XX)>1e8 s = svd(XX); XX = XX+eye(size(XX,1))*s(1)*0.00000001; end if cond(YY)>1e8 s = svd(YY); YY = YY+eye(size(YY,1))*s(1)*0.00000001; end [wx,rho] = eig((XX\XY)*(YY\YX)); rho = sqrt(real(diag(rho))); [dummy,ix] = sort(rho, 'descend'); rho = rho(ix); wx = wx(:,ix); w = wx'; %[dummy,ix] = sort(diag(abs(rho).^2),'descend'); %w = w(1:n,ix(2:2:end))'; %w = w(1:n,1:n); %rho = abs(rho(ix(2:2:2*n),ix(2:2:2*n))).^2; % normalise to unit norm %for k= 1:size(w,1) % w(k,:) = w(k,:)./norm(w(k,:)); %end function [m] = cellmean(x, dim) % [M] = CELLMEAN(X, DIM) computes the mean, across all cells in x along % the dimension dim. % % X should be an linear cell-array of matrices for which the size in at % least one of the dimensions should be the same for all cells nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellmean'); end if nargin==1, scx1 = cellfun('size', x, 1); scx2 = cellfun('size', x, 2); if all(scx2==scx2(1)), dim = 2; %let second dimension prevail elseif all(scx1==scx1(1)), dim = 1; else error('no dimension to compute mean for'); end end nx = max(nx); nsmp = cellfun('size', x, dim); ssmp = cellfun(@sum, x, repmat({dim},1,nx), 'UniformOutput', 0); m = sum(cell2mat(ssmp), dim)./sum(nsmp); function [y] = cellvecadd(x, v) % [Y]= CELLVECADD(X, V) - add vector to all rows or columns of each matrix % in cell-array X % check once and for all to save time persistent bsxfun_exists; if isempty(bsxfun_exists); bsxfun_exists=(exist('bsxfun')==5); if ~bsxfun_exists; error('bsxfun not found.'); end end nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellmean'); end if ~iscell(v), v = repmat({v}, nx); end sx1 = cellfun('size', x, 1); sx2 = cellfun('size', x, 2); sv1 = cellfun('size', v, 1); sv2 = cellfun('size', v, 2); if all(sx1==sv1) && all(sv2==1), dim = mat2cell([ones(length(sx2),1) sx2(:)]', repmat(2,nx(1),1), repmat(1,nx(2),1)); elseif all(sx2==sv2) && all(sv1==1), dim = mat2cell([sx1(:) ones(length(sx1),1)]', repmat(2,nx(1),1), repmat(1,nx(2),1)); elseif all(sv1==1) && all(sv2==1), dim = mat2cell([sx1(:) sx2(:)]'', nx(1), nx(2)); else error('inconsistent input'); end y = cellfun(@bsxfun, repmat({@plus}, nx), x, v, 'UniformOutput', 0); %y = cellfun(@vplus, x, v, dim, 'UniformOutput', 0); function [c] = cellcov(x, y, dim, flag) % [C] = CELLCOV(X, DIM) computes the covariance, across all cells in x along % the dimension dim. When there are three inputs, covariance is computed between % all cells in x and y % % X (and Y) should be linear cell-array(s) of matrices for which the size in at % least one of the dimensions should be the same for all cells if nargin<4 && iscell(y) flag = 1; elseif nargin<4 && isnumeric(y) flag = dim; end if nargin<3 && iscell(y) scx1 = cellfun('size', x, 1); scx2 = cellfun('size', x, 2); if all(scx2==scx2(1)), dim = 2; %let second dimension prevail elseif all(scx1==scx1(1)), dim = 1; else error('no dimension to compute covariance for'); end elseif nargin<=3 && isnumeric(y) dim = y; end if isnumeric(y), y = []; end nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellmean'); end if flag, mx = cellmean(x, 2); x = cellvecadd(x, -mx); if ~isempty(y), my = cellmean(y, 2); y = cellvecadd(y, -my); end end nx = max(nx); nsmp = cellfun('size', x, dim); if isempty(y), csmp = cellfun(@covc, x, repmat({dim},1,nx), 'UniformOutput', 0); else csmp = cellfun(@covc, x, y, repmat({dim},1,nx), 'UniformOutput', 0); end nc = size(csmp{1}); c = sum(reshape(cell2mat(csmp), [nc(1) nc(2) nx]), 3)./sum(nsmp); function [c] = covc(x, y, dim) if nargin==2, dim = y; y = x; end if dim==1, c = x'*y; elseif dim==2, c = x*y'; end function [c] = cellcovshift(x, shift, dim, flag) % [C] = CELLCOVSHIFT(X, SHIFT, DIM) computes the covariance, across all cells % in x along the dimension dim. % % X should be linear cell-array(s) of matrices for which the size in at % least one of the dimensions is be the same for all cells if nargin<4, flag = 1; end if nargin<3, dim = find(size(x{1})>1, 1, 'first'); end nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1) || ndims(x{1})>2, error('incorrect input for cellcovshift'); end % shift the time axis y = cellshift(x, shift, dim); % compute covariance c = cellcov(y, dim, flag); function [x] = cellshift(x, shift, dim, maxshift) % CELLSHIFT(X, SHIFT, DIM) if numel(shift)>1 x = x(:)'; y = cell(numel(shift),numel(x)); for k = 1:numel(shift) y(k,:) = cellshift(x, shift(k), dim, max(abs(shift))); end for k = 1:size(y,2) y{1,k} = cell2mat(y(:,k)); for m = 2:size(y,1) y{m,k} = nan; end end x = y(1,:); return; end if nargin<4 maxshift = max(abs(shift)); end if any(abs(shift))>abs(maxshift) error('the value for maxshift should be >= shift'); end if nargin<3 dim = find(size(x{1})>1, 1, 'first'); end maxshift = abs(maxshift); if numel(maxshift)==1, maxshift = maxshift([1 1]); end nx = size(x); if ~iscell(x) || length(nx)>2 || all(nx>1), error('incorrect input for cellshift'); end n = numel(x); nsmp = cellfun('size', x, dim); beg1 = ones(1,n) + shift + maxshift(1); end1 = nsmp + shift - maxshift(2); switch dim case 1 for k = 1:n x{k} = x{k}(beg1(k):end1(k),:); end case 2 for k = 1:n x{k} = x{k}(:,beg1(k):end1(k)); end otherwise error('dimensionality of >2 is not supported'); end
github
philippboehmsturm/antx-master
inside_contour.m
.m
antx-master/xspm8/external/fieldtrip/private/inside_contour.m
1,106
utf_8
37d10e5d9a05c79551aac24c328e34aa
function bool = inside_contour(pos, contour); npos = size(pos,1); ncnt = size(contour,1); x = pos(:,1); y = pos(:,2); minx = min(x); miny = min(y); maxx = max(x); maxy = max(y); bool = true(npos,1); bool(x<minx) = false; bool(y<miny) = false; bool(x>maxx) = false; bool(y>maxy) = false; % the summed angle over the contour is zero if the point is outside, and 2*pi if the point is inside the contour % leave some room for inaccurate f critval = 0.1; % the remaining points have to be investigated with more attention sel = find(bool); for i=1:length(sel) contourx = contour(:,1) - pos(sel(i),1); contoury = contour(:,2) - pos(sel(i),2); angle = atan2(contoury, contourx); % angle = unwrap(angle); angle = my_unwrap(angle); total = sum(diff(angle)); bool(sel(i)) = (abs(total)>critval); end function x = my_unwrap(x) % this is a faster implementation of the MATLAB unwrap function % with hopefully the same functionality d = diff(x); indx = find(abs(d)>pi); for i=indx(:)' if d(i)>0 x((i+1):end) = x((i+1):end) - 2*pi; else x((i+1):end) = x((i+1):end) + 2*pi; end end
github
philippboehmsturm/antx-master
smudge.m
.m
antx-master/xspm8/external/fieldtrip/private/smudge.m
1,949
utf_8
a793adc32ad1bfa0f193bd20c3ca7764
function [datout, S] = smudge(datin, tri, niter, threshold) % SMUDGE(DATIN, TRI) computes a smudged version of the input data datain, % given a triangulation tri. The algorithm is according to what is in % MNE-Suite, documented in chapter 8.3 if nargin<3 || isempty(niter), niter = 1; end if nargin<4 threshold = 0; end for k = 1:niter [tmp, Stmp] = do_smudge(datin, tri, threshold); if k==1, S = Stmp; else S = Stmp*S; end datout = tmp; datin = tmp; end function [datout, S] = do_smudge(datin, tri, threshold) % number of points npnt = numel(datin); % non-zero points nz = find(datin>threshold); % triangles containing 1 or 2 non-zero points nzt = ismember(tri, nz); tnz = sum(nzt, 2)>0 & sum(nzt,2)<3; % points with non-zero neighbours nzn = tri(tnz, :); nzt = nzt(tnz, :); vec1 = zeros(size(nzn,1)*2,1); vec2 = zeros(size(nzn,1)*2,1); for k = 1:size(nzn,1) indx0 = (k-1)*2+(1:2); indx1 = nzn(k, nzt(k,:)); indx2 = nzn(k,~nzt(k,:)); vec1(indx0) = indx1; vec2(indx0) = indx2; end % matrices that define edges which has one of the members 0 % sorted according to the left or the right column respectively vecx = sortrows([vec1 vec2]); % having the non-zero vertex upfront, sorted accordingly vecy = sortrows([vec2 vec1]); % having the zero vertex upfront, sorted accordingly clear vec1 vec2; % in a closed surface the edges occur in doubles vecx = vecx(1:2:end,:); vecy = vecy(1:2:end,:); % vecx now has in the first column the column indices for matrix S % vecx now has in the second column the row indices for matrix S % reconstruct the value that has to be put into the matrix [uval,i1,i2] = unique(vecy(:,1)); tmp = diff([0;vecy(:,1)])>0; nix = diff(find([tmp;1]==1)); nix(end+1:numel(uval)) = 1; [dummy,i1,i2] = unique(vecx(:,2)); val = 1./nix(i2); S = sparse(vecx(:,2),vecx(:,1),val,npnt,npnt); S = S + spdiags(datin(:)>threshold, 0, npnt, npnt); datout = S*datin(:);
github
philippboehmsturm/antx-master
butter.m
.m
antx-master/xspm8/external/fieldtrip/private/butter.m
3,559
utf_8
ad82b4c04911a5ea11fd6bd2cc5fd590
% Copyright (C) 1999 Paul Kienzle % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; If not, see <http://www.gnu.org/licenses/>. % Generate a butterworth filter. % Default is a discrete space (Z) filter. % % [b,a] = butter(n, Wc) % low pass filter with cutoff pi*Wc radians % % [b,a] = butter(n, Wc, 'high') % high pass filter with cutoff pi*Wc radians % % [b,a] = butter(n, [Wl, Wh]) % band pass filter with edges pi*Wl and pi*Wh radians % % [b,a] = butter(n, [Wl, Wh], 'stop') % band reject filter with edges pi*Wl and pi*Wh radians % % [z,p,g] = butter(...) % return filter as zero-pole-gain rather than coefficients of the % numerator and denominator polynomials. % % [...] = butter(...,'s') % return a Laplace space filter, W can be larger than 1. % % [a,b,c,d] = butter(...) % return state-space matrices % % References: % % Proakis & Manolakis (1992). Digital Signal Processing. New York: % Macmillan Publishing Company. % Author: Paul Kienzle <[email protected]> % Modified by: Doug Stewart <[email protected]> Feb, 2003 function [a, b, c, d] = butter (n, W, varargin) if (nargin>4 || nargin<2) || (nargout>4 || nargout<2) usage ('[b, a] or [z, p, g] or [a,b,c,d] = butter (n, W [, "ftype"][,"s"])'); end % interpret the input parameters if (~(length(n)==1 && n == round(n) && n > 0)) error ('butter: filter order n must be a positive integer'); end stop = 0; digital = 1; for i=1:length(varargin) switch varargin{i} case 's', digital = 0; case 'z', digital = 1; case { 'high', 'stop' }, stop = 1; case { 'low', 'pass' }, stop = 0; otherwise, error ('butter: expected [high|stop] or [s|z]'); end end [r, c]=size(W); if (~(length(W)<=2 && (r==1 || c==1))) error ('butter: frequency must be given as w0 or [w0, w1]'); elseif (~(length(W)==1 || length(W) == 2)) error ('butter: only one filter band allowed'); elseif (length(W)==2 && ~(W(1) < W(2))) error ('butter: first band edge must be smaller than second'); end if ( digital && ~all(W >= 0 & W <= 1)) error ('butter: critical frequencies must be in (0 1)'); elseif ( ~digital && ~all(W >= 0 )) error ('butter: critical frequencies must be in (0 inf)'); end % Prewarp to the band edges to s plane if digital T = 2; % sampling frequency of 2 Hz W = 2/T*tan(pi*W/T); end % Generate splane poles for the prototype butterworth filter % source: Kuc C = 1; % default cutoff frequency pole = C*exp(1i*pi*(2*[1:n] + n - 1)/(2*n)); if mod(n,2) == 1, pole((n+1)/2) = -1; end % pure real value at exp(i*pi) zero = []; gain = C^n; % splane frequency transform [zero, pole, gain] = sftrans(zero, pole, gain, W, stop); % Use bilinear transform to convert poles to the z plane if digital [zero, pole, gain] = bilinear(zero, pole, gain, T); end % convert to the correct output form if nargout==2, a = real(gain*poly(zero)); b = real(poly(pole)); elseif nargout==3, a = zero; b = pole; c = gain; else % output ss results [a, b, c, d] = zp2ss (zero, pole, gain); end
github
philippboehmsturm/antx-master
convert_event.m
.m
antx-master/xspm8/external/fieldtrip/private/convert_event.m
7,841
utf_8
e54a2ce9399657ba01d486a361f9d234
function [obj] = convert_event(obj, target, varargin) % CONVERT_EVENT converts between the different representations of events, % which can be % 1) event structure, see FT_READ_EVENT % 2) matrix representation as in trl (Nx3), see FT_DEFINETRIAL % 3) matrix representation as in artifact (Nx2), see FT_ARTIFACT_xxx % 4) boolean vector representation with 1 for samples containing trial/artifact % % Use as % [object] = convert_event(object, target, ....) % % Possible input objects types are % event structure % Nx3 trl matrix, or cell array of multiple trl definitions % Nx2 artifact matrix, or cell array of multiple artifact definitions % boolean vector, or matrix with multiple vectors as rows % % Possible targets are 'event', 'trl', 'artifact', 'boolvec' % % Additional options should be specified in key-value pairs and can be % 'endsample' = % 'typenames' = % % See READ_EVENT, DEFINETRIAL, REJECTARTIFACT, ARTIFACT_xxx % Copyright (C) 2009, Ingrid Nieuwenhuis % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: convert_event.m 7123 2012-12-06 21:21:38Z roboos $ % Check if target is specified correctly if sum(strcmp(target, {'event', 'trl', 'artifact', 'boolvec'})) < 1 error('target has to be ''event'', ''trl'', ''artifact'', or ''boolvec''.') end % Get the options endsample = ft_getopt(varargin, 'endsample'); typenames = ft_getopt(varargin, 'typenames'); % Determine what the input object is if isempty(obj) input_obj = 'empty'; elseif isstruct(obj) input_obj = 'event'; elseif iscell(obj) if isempty(obj{1}) input_obj = 'empty'; elseif size(obj{1},2) == 3 input_obj = 'trl'; elseif size(obj{1},2) == 2 input_obj = 'artifact'; elseif size(obj{1},2) > 3 % could be a strange trl-matrix with multiple columns input_obj = 'trl'; for i = 1:length(obj) if ~isempty(obj{i}) obj{i} = obj{i}(:,1:3); end end else error('incorrect input object, see help for what is allowed.') end elseif islogical(obj) input_obj = 'boolvec'; elseif size(obj,2) == 3 input_obj = 'trl'; elseif size(obj,2) == 2 input_obj = 'artifact'; elseif size(obj,2) > 3 tmp = unique(obj); if isempty(find(tmp>2, 1)) input_obj = 'boolvec'; obj = logical(obj); else %it is at least not boolean but could be a strange %trl-matrix with multiple columns input_obj = 'trl'; obj = obj(:,1:3); end else error('incorrect input object, see help for what is allowed.') end % do conversion if (strcmp(input_obj, 'trl') || strcmp(input_obj, 'artifact') || strcmp(input_obj, 'empty')) && strcmp(target, 'boolvec') if ~isempty(endsample) obj = artifact2artvec(obj,endsample); else obj = artifact2artvec(obj); end elseif strcmp(input_obj, 'boolvec') && strcmp(target,'artifact' ) obj = artvec2artifact(obj); elseif strcmp(input_obj, 'boolvec') && strcmp(target,'trl' ) obj = artvec2artifact(obj); if iscell(obj) for i=1:length(obj) obj{i}(:,3) = 0; end else obj(:,3) = 0; end elseif (strcmp(input_obj, 'trl') || strcmp(input_obj, 'artifact')) && strcmp(target, 'event') obj = artifact2event(obj, typenames); elseif strcmp(input_obj, 'artifact') && strcmp(target,'trl') if iscell(obj) for i=1:length(obj) obj{i}(:,3) = 0; end else obj(:,3) = 0; end elseif strcmp(input_obj, 'trl') && strcmp(target,'artifact') if iscell(obj) for i=1:length(obj) obj{i}(:,3:end) = []; end else obj(:,3:end) = []; end elseif strcmp(input_obj, 'empty') obj = []; else warning('conversion not supported yet') %FIXME end %%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function artvec = artifact2artvec(varargin) % ARTIFACT2ARTVEC makes boolian vector (or matrix when artifact is % cell array of multiple artifact definitions) with 0 for artifact free % sample and 1 for sample containing an artifact according to artifact % specification. Length of vector is (from sample 1) last sample as % defined in the artifact definition, or when datendsample is speciefied % vector is length datendsample. artifact = varargin{1}; if length(varargin) == 1 if ~iscell(artifact) % assume only one artifact is given if isempty(artifact) error('When input object is empty ''endsample'' must be specified to convert into boolvec') else endsample = max(artifact(:,2)); end elseif length(artifact) == 1 if isempty(artifact{1}) error('When input object is empty ''endsample'' must be specified to convert into boolvec') else endsample = max(artifact{1}(:,2)); end else error('when giving multiple artifact definitions, endsample should be specified to assure all output vectors are of the same length') end elseif length(varargin) == 2 endsample = varargin{2}; elseif length(varargin) > 2 error('too many input arguments') end if ~iscell(artifact) artifact = {artifact}; end % make artvec artvec = zeros(length(artifact), endsample); breakflag = 0; for i=1:length(artifact) for j=1:size(artifact{i},1) artbegsample = artifact{i}(j,1); artendsample = artifact{i}(j,2); if artbegsample > endsample warning('artifact definition contains later samples than endsample, these samples are ignored') break elseif artendsample > endsample warning('artifact definition contains later samples than endsample, these samples are ignored') artendsample = endsample; breakflag = 1; end artvec(i, artbegsample:artendsample) = 1; if breakflag break end end end %%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function artifact = artvec2artifact(artvec) % ARTVEC2ARTIFACT makes artifact definition (or cell array of artifact % definitions) from boolian vector (or matrix) with [artbegsample % artendsample]. Assumed is that the artvec starts with sample 1. for i=1:size(artvec,1) tmp = diff([0 artvec(i,:) 0]); artbeg = find(tmp==+1); artend = find(tmp==-1) - 1; artifact{i} = [artbeg' artend']; end if length(artifact) == 1 artifact = artifact{1}; end %%%%%%%%%%%%%%% SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function event = artifact2event(artifact, typenames) % ARTIFACT2EVENT makes event structure from artifact definition (or cell % array of artifact definitions). event.type is always 'artifact', but % incase of cellarays of artifacts is is also possible to hand 'typenames' % with length(artifact) if ~iscell(artifact) artifact = {artifact}; end if ~isempty(typenames) if length(artifact) ~= length(typenames) error('length typenames should be the same as length artifact') end end event = []; for i=1:length(artifact) for j=1:size(artifact{i},1) event(end+1).sample = artifact{i}(j,1); event(end ).duration = artifact{i}(j,2)-artifact{i}(j,1)+1; if ~isempty(typenames) event(end).type = typenames{i}; elseif size(artifact{i},2) == 2 event(end).type = 'artifact'; elseif size(artifact{i},2) == 3 event(end).type = 'trial'; end event(end ).value = []; event(end ).offset = []; end end
github
philippboehmsturm/antx-master
fdr.m
.m
antx-master/xspm8/external/fieldtrip/private/fdr.m
1,987
utf_8
6d3291c124f575d01ad10bf51ec8854a
function [h] = fdr(p, q); % FDR false discovery rate % % Use as % h = fdr(p, q) % % This implements % Genovese CR, Lazar NA, Nichols T. % Thresholding of statistical maps in functional neuroimaging using the false discovery rate. % Neuroimage. 2002 Apr;15(4):870-8. % Copyright (C) 2005, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: fdr.m 7123 2012-12-06 21:21:38Z roboos $ % convert the input into a row vector dim = size(p); p = reshape(p, 1, numel(p)); % sort the observed uncorrected probabilities [ps, indx] = sort(p); % count the number of voxels V = length(p); % compute the threshold probability for each voxel pi = ((1:V)/V) * q / c(V); h = (ps<=pi); % undo the sorting [dum, unsort] = sort(indx); h = h(unsort); % convert the output back into the original format h = reshape(h, dim); function s = c(V) % See Genovese, Lazar and Holmes (2002) page 872, second column, first paragraph if V<1000 % compute it exactly s = sum(1./(1:V)); else % approximate it s = log(V) + 0.57721566490153286060651209008240243104215933593992359880576723488486772677766467093694706329174674951463144724980708248096050401448654283622417399764492353625350033374293733773767394279259525824709491600873520394816567; end
github
philippboehmsturm/antx-master
read_labview_dtlg.m
.m
antx-master/xspm8/external/fieldtrip/private/read_labview_dtlg.m
5,153
utf_8
9fc442c5cf83bbfd05e00c4acea65bed
function [dat] = read_labview_dtlg(filename, datatype); % READ_LABVIEW_DTLG % % Use as % dat = read_labview_dtlg(filename, datatype) % where datatype can be 'int32' or 'int16' % % The output of this function is a structure. % Copyright (C) 2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_labview_dtlg.m 7123 2012-12-06 21:21:38Z roboos $ fid = fopen(filename, 'r', 'ieee-be'); header = fread(fid, 4, 'uint8=>char')'; if ~strcmp(header, 'DTLG') error('unsupported file, header should start with DTLG'); end version = fread(fid, 4, 'char')'; % clear version nd = fread(fid, 1, 'int32'); p = fread(fid, 1, 'int32'); % the following seems to work for files with version [7 0 128 0] % but in files files with version [8 0 128 0] the length of the descriptor is not correct ld = fread(fid, 1, 'int16'); descriptor = fread(fid, ld, 'uint8=>char')'; % ROBOOS: the descriptor should ideally be decoded, since it contains the variable % name, type and size % The first offset block always starts immediately after the data descriptor (at offset p, which should ideally be equal to 16+ld) if nd<=128 % The first offset block contains the offsets for all data sets. % In this case P points to the start of the offset block. fseek(fid, p, 'bof'); offset = fread(fid, 128, 'uint32')'; else % The first offset block contains the offsets for the first 128 data sets. % The entries for the remaining data sets are stored in additional offset blocks. % The locations of those blocks are contained in a block table starting at P. offset = []; fseek(fid, p, 'bof'); additional = fread(fid, 128, 'uint32'); for i=1:sum(additional>0) fseek(fid, additional(i), 'bof'); tmp = fread(fid, 128, 'uint32')'; offset = cat(2, offset, tmp); end clear additional i tmp end % ROBOOS: remove the zeros in the offset array for non-existing datasets offset = offset(1:nd); % ROBOOS: how to determine the data datatype? switch datatype case 'uint32' datasize = 4; case 'int32' datasize = 4; case 'uint16' datasize = 2; case 'int16' datasize = 2; otherwise error('unsupported datatype'); end % If the data sets are n-dimensional arrays, the first n u32 longwords in each data % set contain the array dimensions, imediately followed by the data values. % ROBOOS: how to determine whether they are n-dimensional arrays? % determine the number of dimensions by looking at the first array % assume that all subsequent arrays have the same number of dimensions if nd>1 estimate = (offset(2)-offset(1)); % initial estimate for the number of datasize in the array fseek(fid, offset(1), 'bof'); n = fread(fid, 1, 'int32'); while mod(estimate-4*length(n), (datasize*prod(n)))~=0 % determine the number and size of additional array dimensions n = cat(1, n, fread(fid, 1, 'int32')); if datasize*prod(n)>estimate error('could not determine array size'); end end ndim = length(n); clear estimate n else estimate = filesize(fid)-offset; fseek(fid, offset(1), 'bof'); n = fread(fid, 1, 'int32'); while mod(estimate-4*length(n), (datasize*prod(n)))~=0 % determine the number and size of additional array dimensions n = cat(1, n, fread(fid, 1, 'int32')); if datasize*prod(n)>estimate error('could not determine array size'); end end ndim = length(n); clear estimate n end % read the dimensions and the data from each array for i=1:nd fseek(fid, offset(i), 'bof'); n = fread(fid, ndim, 'int32')'; % Labview uses the C-convention for storing data, and Matlab uses the Fortran convention n = fliplr(n); data{i} = fread(fid, n, datatype); end clear i n ndim fclose(fid); % put all local variables into a structure, this is a bit unusual programming style % the output structure is messy, but contains all relevant information tmp = whos; dat = []; for i=1:length(tmp) if isempty(strmatch(tmp(i).name, {'tmp', 'fid', 'ans', 'handles'})) dat = setfield(dat, tmp(i).name, eval(tmp(i).name)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % local helper function to determine the size of the file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function siz = filesize(fid) fp = ftell(fid); fseek(fid, 0, 'eof'); siz = ftell(fid); fseek(fid, fp, 'bof');
github
philippboehmsturm/antx-master
sphericalSplineInterpolate.m
.m
antx-master/xspm8/external/fieldtrip/private/sphericalSplineInterpolate.m
5,226
utf_8
27ce6fd83adee8c3957c477f73dad771
function [W,Gss,Gds,Hds]=sphericalSplineInterpolate(src,dest,lambda,order,type,tol) %interpolate matrix for spherical interpolation % % W = sphericalSplineInterpolate(src,dest,lambda,order,type,tol) % % Inputs: % src - [3 x N] old electrode positions % dest - [3 x M] new electrode positions % lambda - [float] regularisation parameter for smoothing the estimates (1e-5) % order - [float] order of the polynomial interplotation to use (4) % type - [str] one of; ('spline') % 'spline' - spherical Spline % 'slap' - surface Laplician (aka. CSD) % tol - [float] tolerance for the legendre poly approx (1e-7) % Outputs: % W - [M x N] linear mapping matrix between old and new co-ords % % Based upon the paper: Perrin89 % Copyright 2009- by Jason D.R. Farquhar ([email protected]) % Permission is granted for anyone to copy, use, or modify this % software and accompanying documents, provided this copyright % notice is retained, and note is made of any changes that have been % made. This software and documents are distributed without any % warranty, express or implied. if ( nargin < 3 || isempty(lambda) ) lambda=1e-5; end; if ( nargin < 4 || isempty(order) ) order=4; end; if ( nargin < 5 || isempty(type)) type='spline'; end; if ( nargin < 6 || isempty(tol) ) tol=eps; end; % map the positions onto the sphere (not using repop, by JMH) src = src ./repmat(sqrt(sum(src.^2)), size(src, 1), 1); % src = repop(src,'./',sqrt(sum(src.^2))); dest = dest./repmat(sqrt(sum(dest.^2)), size(dest, 1), 1); % dest = repop(dest,'./',sqrt(sum(dest.^2))); %calculate the cosine of the angle between the new and old electrodes. If %the vectors are on top of each other, the result is 1, if they are %pointing the other way, the result is -1 cosSS = src'*src; % angles between source positions cosDS = dest'*src; % angles between destination positions % Compute the interpolation matrix to tolerance tol [Gss] = interpMx(cosSS,order,tol); % [nSrc x nSrc] [Gds Hds] = interpMx(cosDS,order,tol); % [nDest x nSrc] % Include the regularisation if ( lambda>0 ) Gss = Gss+lambda*eye(size(Gss)); end; % Compute the mapping to the polynomial coefficients space % [nSrc+1 x nSrc+1] % N.B. this can be numerically unstable so use the PINV to solve.. muGss=1;%median(diag(Gss)); % used to improve condition number when inverting. Probably uncessary %C = [ Gss muGss*ones(size(Gss,1),1)]; C = [ Gss muGss*ones(size(Gss,1),1);... muGss*ones(1,size(Gss,2)) 0]; iC = pinv(C); % Compute the mapping from source measurements and positions to destination positions if ( strcmp(lower(type),'spline') ) W = [Gds ones(size(Gds,1),1).*muGss]*iC(:,1:end-1); % [nDest x nSrc] elseif (strcmp(lower(type),'slap')) W = Hds*iC(1:end-1,1:end-1);%(:,1:end-1); % [nDest x nSrc] end return; %-------------------------------------------------------------------------- function [G,H]=interpMx(cosEE,order,tol) % compute the interpolation matrix for this set of point pairs if ( nargin < 3 || isempty(tol) ) tol=1e-10; end; G=zeros(size(cosEE)); H=zeros(size(cosEE)); for i=1:numel(cosEE); x = cosEE(i); n=1; Pns1=1; Pn=x; % seeds for the legendre ploy recurence tmp = ( (2*n+1) * Pn ) / ((n*n+n).^order); G(i) = tmp ; % 1st element in the sum H(i) = (n*n+n)*tmp; % 1st element in the sum oGi=inf; dG=abs(G(i)); oHi=inf; dH=abs(H(i)); for n=2:500; % do the sum Pns2=Pns1; Pns1=Pn; Pn=((2*n-1)*x*Pns1 - (n-1)*Pns2)./n; % legendre poly recurance oGi=G(i); oHi=H(i); tmp = ((2*n+1) * Pn) / ((n*n+n).^order) ; G(i) = G(i) + tmp; % update function estimate, spline interp H(i) = H(i) + (n*n+n)*tmp; % update function estimate, SLAP dG = (abs(oGi-G(i))+dG)/2; dH=(abs(oHi-H(i))+dH)/2; % moving ave gradient est for convergence %fprintf('%d) dG =%g \t dH = %g\n',n,dG,dH);%abs(oGi-G(i)),abs(oHi-H(i))); if ( dG<tol && dH<tol ) break; end; % stop when tol reached end end G= G./(4*pi); H= H./(4*pi); return; %-------------------------------------------------------------------------- function testCase() src=randn(3,100); src(3,:)=abs(src(3,:)); src=repop(src,'./',sqrt(sum(src.^2))); % source points on sphere dest=rand(3,30); dest(3,:)=abs(dest(3,:)); dest=repop(dest,'./',sqrt(sum(dest.^2))); % dest points on sphere clf;scatPlot(src,'b.'); W=sphericalSplineInterpolate(src,dest); W=sphericalSplineInterpolate(src(:,1:70),src); clf;imagesc(W); clf;jplot(src(1:2,1:70),W(70:75,:)'); z=jf_load('eeg/vgrid/nips2007/1-rect230ms','jh','flip_rc_sep'); z=jf_retain(z,'dim','ch','idx',[z.di(1).extra.iseeg]); lambda=0; order=4; chPos=[z.di(1).extra.pos3d]; incIdx=1:size(dest,2)-3; exIdx=setdiff(1:size(dest,2),incIdx); % included + excluded channels W=sphericalSplineInterpolate(chPos(:,incIdx),chPos,lambda,order); % estimate the removed channels clf;imagesc(W); clf;jplot(chPos(:,incIdx),W(exIdx,:)'); % compare estimated with true X=z.X(:,:,2); Xest=W*z.X(incIdx,:,2); clf;mcplot([X(exIdx(1),:);Xest(exIdx(1),:)]') clf;subplot(211);mcplot(X');subplot(212);mcplot(Xest');
github
philippboehmsturm/antx-master
clusterstat.m
.m
antx-master/xspm8/external/fieldtrip/private/clusterstat.m
33,336
utf_8
40434805aa0d746d547a5ffad1b5f987
function [stat, cfg] = clusterstat(cfg, statrnd, statobs, varargin) % SUBFUNCTION for computing cluster statistic for N-D volumetric source data % or for channel-freq-time data % % This function uses % cfg.dim % cfg.inside (only for source data) % cfg.tail = -1, 0, 1 % cfg.multivariate = no, yes % cfg.orderedstats = no, yes % cfg.clusterstatistic = max, maxsize, maxsum, wcm % cfg.clusterthreshold = parametric, nonparametric_individual, nonparametric_common % cfg.clusteralpha % cfg.clustercritval % cfg.wcm_weight % cfg.feedback % Copyright (C) 2005-2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: clusterstat.m 7123 2012-12-06 21:21:38Z roboos $ % set the defaults if ~isfield(cfg,'orderedstats'), cfg.orderedstats = 'no'; end if ~isfield(cfg,'multivariate'), cfg.multivariate = 'no'; end if ~isfield(cfg,'minnbchan'), cfg.minnbchan=0; end % if ~isfield(cfg,'channeighbstructmat'), cfg.channeighbstructmat=[]; end % if ~isfield(cfg,'chancmbneighbstructmat'), cfg.chancmbneighbstructmat=[]; end % if ~isfield(cfg,'chancmbneighbselmat'), cfg.chancmbneighbselmat=[]; end % get issource from varargin, to determine source-data-specific options and allow the proper usage of cfg.neighbours % (cfg.neighbours was previously used in determining wheter source-data was source data or not) set to zero by default % note, this may cause problems when functions call clusterstat without giving issource, as issource was previously % set in clusterstat.m but has now been transfered to the function that calls clusterstat.m (but only implemented in ft_statistics_montecarlo) issource = ft_getopt(varargin, 'issource', false); if cfg.tail~=cfg.clustertail error('cfg.tail and cfg.clustertail should be identical') end % create neighbour structure (but only when not using source data) if isfield(cfg, 'neighbours') && ~issource channeighbstructmat = makechanneighbstructmat(cfg); else channeighbstructmat = 0; end % perform fixinside fix if input data is source data if issource % cfg contains dim and inside that are needed for reshaping the data to a volume, and inside should behave as a index vector cfg = fixinside(cfg, 'index'); end needpos = cfg.tail==0 || cfg.tail== 1; needneg = cfg.tail==0 || cfg.tail==-1; Nsample = size(statrnd,1); Nrand = size(statrnd,2); prb_pos = ones(Nsample, 1); prb_neg = ones(Nsample, 1); postailobs = false(Nsample, 1); % this holds the thresholded values negtailobs = false(Nsample, 1); % this holds the thresholded values postailrnd = false(Nsample,Nrand); % this holds the thresholded values negtailrnd = false(Nsample,Nrand); % this holds the thresholded values Nobspos = 0; % number of positive clusters in observed data Nobsneg = 0; % number of negative clusters in observed data if strcmp(cfg.clusterthreshold, 'parametric') % threshold based on the critical value from parametric distribution siz = size(cfg.clustercritval); if all(siz==1) && cfg.clustertail==0 % it only specifies one critical value, assume that the left and right tail are symmetric around zero negtailcritval = -cfg.clustercritval; postailcritval = cfg.clustercritval; elseif all(siz==1) && cfg.clustertail==-1 % it only specifies one critical value corresponding to the left tail negtailcritval = cfg.clustercritval; postailcritval = +inf * ones(size(negtailcritval)); elseif all(siz==1) && cfg.clustertail==1 % it only specifies one critical value corresponding to the right tail postailcritval = cfg.clustercritval; negtailcritval = -inf * ones(size(postailcritval)); elseif siz(1)==Nsample && siz(2)==1 && cfg.clustertail==0 % it specifies a single critical value for each sample, assume that the left and right tail are symmetric around zero negtailcritval = -cfg.clustercritval; postailcritval = cfg.clustercritval; elseif siz(1)==Nsample && siz(2)==1 && cfg.clustertail==-1 % it specifies a critical value for the left tail % which is different for each sample (samples have a different df) negtailcritval = cfg.clustercritval; postailcritval = +inf * ones(size(negtailcritval)); elseif siz(1)==Nsample && siz(2)==1 && cfg.clustertail==1 % it specifies a critical value for the right tail % which is different for each sample (samples have a different df) postailcritval = cfg.clustercritval; negtailcritval = +inf * ones(size(postailcritval)); elseif siz(1)==Nsample && siz(2)==2 && cfg.clustertail==0 % it specifies a critical value for the left and for the right tail of the distribution % which is different for each sample (samples have a different df) negtailcritval = cfg.clustercritval(:,1); postailcritval = cfg.clustercritval(:,2); elseif prod(siz)==2 && cfg.clustertail==0 % it specifies a critical value for the left and for the right tail of the distribution % which is the same for each sample (samples have the same df) negtailcritval = cfg.clustercritval(1); postailcritval = cfg.clustercritval(2); else error('cannot make sense out of the specified parametric critical values'); end elseif strcmp(cfg.clusterthreshold, 'nonparametric_individual') % threshold based on bootstrap using all other randomizations % each voxel will get an individual threshold [srt, ind] = sort(statrnd,2); if cfg.clustertail==0 % both tails are needed negtailcritval = srt(:,round(( cfg.clusteralpha/2)*size(statrnd,2))); postailcritval = srt(:,round((1-cfg.clusteralpha/2)*size(statrnd,2))); elseif cfg.clustertail==1 % only positive tail is needed postailcritval = srt(:,round((1-cfg.clusteralpha)*size(statrnd,2))); negtailcritval = -inf * ones(size(postailcritval)); elseif cfg.clustertail==1 % only negative tail is needed negtailcritval = srt(:,round(( cfg.clusteralpha)*size(statrnd,2))); postailcritval = +inf * ones(size(negtailcritval)); end elseif strcmp(cfg.clusterthreshold, 'nonparametric_common') % threshold based on bootstrap using all other randomizations % all voxels will get a common threshold [srt, ind] = sort(statrnd(:)); if cfg.clustertail==0 % both tails are needed negtailcritval = srt(round(( cfg.clusteralpha/2)*prod(size(statrnd)))); postailcritval = srt(round((1-cfg.clusteralpha/2)*prod(size(statrnd)))); elseif cfg.clustertail==1 % only positive tail is needed postailcritval = srt(round((1-cfg.clusteralpha)*prod(size(statrnd)))); negtailcritval = -inf * ones(size(postailcritval)); elseif cfg.clustertail==1 % only negative tail is needed negtailcritval = srt(round(( cfg.clusteralpha)*prod(size(statrnd)))); postailcritval = +inf * ones(size(negtailcritval)); end else error('no valid threshold for clustering was given') end % determine clusterthreshold % these should be scalars or column vectors negtailcritval = negtailcritval(:); postailcritval = postailcritval(:); % remember the critical values cfg.clustercritval = [negtailcritval postailcritval]; % test whether the observed and the random statistics exceed the threshold postailobs = (statobs >= postailcritval); negtailobs = (statobs <= negtailcritval); for i=1:Nrand postailrnd(:,i) = (statrnd(:,i) >= postailcritval); negtailrnd(:,i) = (statrnd(:,i) <= negtailcritval); end % first do the clustering on the observed data if needpos, if issource if isfield(cfg, 'origdim'), cfg.dim = cfg.origdim; end %this snippet is to support correct clustering of N-dimensional data, not fully tested yet tmp = zeros(cfg.dim); tmp(cfg.inside) = postailobs; numdims = length(cfg.dim); if numdims == 2 || numdims == 3 % if 2D or 3D data ft_hastoolbox('spm8',1); [posclusobs, posnum] = spm_bwlabel(tmp, 2*numdims); % use spm_bwlabel for 2D/3D data to avoid usage of image toolbox else posclusobs = bwlabeln(tmp, conndef(length(cfg.dim),'min')); % spm_bwlabel yet (feb 2011) supports only 2D/3D data end posclusobs = posclusobs(cfg.inside); else if 0 posclusobs = findcluster(reshape(postailobs, [cfg.dim,1]),cfg.chancmbneighbstructmat,cfg.chancmbneighbselmat,cfg.minnbchan); else posclusobs = findcluster(reshape(postailobs, [cfg.dim,1]),channeighbstructmat,cfg.minnbchan); end posclusobs = posclusobs(:); end Nobspos = max(posclusobs); % number of clusters exceeding the threshold fprintf('found %d positive clusters in observed data\n', Nobspos); end if needneg, if issource tmp = zeros(cfg.dim); tmp(cfg.inside) = negtailobs; numdims = length(cfg.dim); if numdims == 2 || numdims == 3 % if 2D or 3D data ft_hastoolbox('spm8',1); [negclusobs, negnum] = spm_bwlabel(tmp, 2*numdims); % use spm_bwlabel for 2D/3D data to avoid usage of image toolbox else negclusobs = bwlabeln(tmp, conndef(length(cfg.dim),'min')); % spm_bwlabel yet (feb 2011) supports only 2D/3D data end negclusobs = negclusobs(cfg.inside); else if 0 negclusobs = findcluster(reshape(negtailobs, [cfg.dim,1]),cfg.chancmbneighbstructmat,cfg.chancmbneighbselmat,cfg.minnbchan); else negclusobs = findcluster(reshape(negtailobs, [cfg.dim,1]),channeighbstructmat,cfg.minnbchan); end negclusobs = negclusobs(:); end Nobsneg = max(negclusobs); fprintf('found %d negative clusters in observed data\n', Nobsneg); end stat = []; stat.stat = statobs; % catch situation where no clustering of the random data is needed if (Nobspos+Nobsneg)==0 warning('no clusters were found in the observed data'); stat.prob = ones(Nsample, 1); return end % allocate space to hold the randomization distributions of the cluster statistic if strcmp(cfg.multivariate, 'yes') || strcmp(cfg.orderedstats, 'yes') fprintf('allocating space for a %d-multivariate distribution of the positive clusters\n', Nobspos); fprintf('allocating space for a %d-multivariate distribution of the negative clusters\n', Nobsneg); posdistribution = zeros(Nobspos,Nrand); % this holds the multivariate randomization distribution of the positive cluster statistics negdistribution = zeros(Nobsneg,Nrand); % this holds the multivariate randomization distribution of the negative cluster statistics else posdistribution = zeros(1,Nrand); % this holds the statistic of the largest positive cluster in each randomization negdistribution = zeros(1,Nrand); % this holds the statistic of the largest negative cluster in each randomization end % do the clustering on the randomized data ft_progress('init', cfg.feedback, 'computing clusters in randomization'); for i=1:Nrand ft_progress(i/Nrand, 'computing clusters in randomization %d from %d\n', i, Nrand); if needpos, if issource tmp = zeros(cfg.dim); tmp(cfg.inside) = postailrnd(:,i); numdims = length(cfg.dim); if numdims == 2 || numdims == 3 % if 2D or 3D data [posclusrnd, posrndnum] = spm_bwlabel(tmp, 2*numdims); % use spm_bwlabel for 2D/3D data to avoid usage of image toolbox else posclusrnd = bwlabeln(tmp, conndef(length(cfg.dim),'min')); % spm_bwlabel yet (feb 2011) supports only 2D/3D data end posclusrnd = posclusrnd(cfg.inside); else if 0 posclusrnd = findcluster(reshape(postailrnd(:,i), [cfg.dim,1]),cfg.chancmbneighbstructmat,cfg.chancmbneighbselmat,cfg.minnbchan); else posclusrnd = findcluster(reshape(postailrnd(:,i), [cfg.dim,1]),channeighbstructmat,cfg.minnbchan); end posclusrnd = posclusrnd(:); end Nrndpos = max(posclusrnd); % number of clusters exceeding the threshold stat = zeros(1,Nrndpos); % this will hold the statistic for each cluster % fprintf('found %d positive clusters in this randomization\n', Nrndpos); for j = 1:Nrndpos if strcmp(cfg.clusterstatistic, 'max'), stat(j) = max(statrnd(find(posclusrnd==j),i)); elseif strcmp(cfg.clusterstatistic, 'maxsize'), stat(j) = length(find(posclusrnd==j)); elseif strcmp(cfg.clusterstatistic, 'maxsum'), stat(j) = sum(statrnd(find(posclusrnd==j),i)); elseif strcmp(cfg.clusterstatistic, 'wcm'), stat(j) = sum((statrnd(find(posclusrnd==j),i)-postailcritval).^cfg.wcm_weight); else error('unknown clusterstatistic'); end end % for 1:Nrdnpos if strcmp(cfg.multivariate, 'yes') || strcmp(cfg.orderedstats, 'yes') stat = sort(stat, 'descend'); % sort them from most positive to most negative if Nrndpos>Nobspos posdistribution(:,i) = stat(1:Nobspos); % remember the largest N clusters else posdistribution(1:Nrndpos,i) = stat; % remember the largest N clusters end else % univariate -> remember the most extreme cluster if ~isempty(stat), posdistribution(i) = max(stat); end end end % needpos if needneg, if issource tmp = zeros(cfg.dim); tmp(cfg.inside) = negtailrnd(:,i); numdims = length(cfg.dim); if numdims == 2 || numdims == 3 % if 2D or 3D data ft_hastoolbox('spm8',1); [negclusrnd, negrndnum] = spm_bwlabel(tmp, 2*numdims); % use spm_bwlabel for 2D/3D to avoid usage of image toolbox else negclusrnd = bwlabeln(tmp, conndef(length(cfg.dim),'min')); % spm_bwlabel yet (feb 2011) supports only 2D/3D data end negclusrnd = negclusrnd(cfg.inside); else if 0 negclusrnd = findcluster(reshape(negtailrnd(:,i), [cfg.dim,1]),cfg.chancmbneighbstructmat,cfg.chancmbneighbselmat,cfg.minnbchan); else negclusrnd = findcluster(reshape(negtailrnd(:,i), [cfg.dim,1]),channeighbstructmat,cfg.minnbchan); end negclusrnd = negclusrnd(:); end Nrndneg = max(negclusrnd); % number of clusters exceeding the threshold stat = zeros(1,Nrndneg); % this will hold the statistic for each cluster % fprintf('found %d negative clusters in this randomization\n', Nrndneg); for j = 1:Nrndneg if strcmp(cfg.clusterstatistic, 'max'), stat(j) = min(statrnd(find(negclusrnd==j),i)); elseif strcmp(cfg.clusterstatistic, 'maxsize'), stat(j) = -length(find(negclusrnd==j)); % encode the size of a negative cluster as a negative value elseif strcmp(cfg.clusterstatistic, 'maxsum'), stat(j) = sum(statrnd(find(negclusrnd==j),i)); elseif strcmp(cfg.clusterstatistic, 'wcm'), stat(j) = -sum((abs(statrnd(find(negclusrnd==j),i)-negtailcritval)).^cfg.wcm_weight); % encoded as a negative value else error('unknown clusterstatistic'); end end % for 1:Nrndneg if strcmp(cfg.multivariate, 'yes') || strcmp(cfg.orderedstats, 'yes') stat = sort(stat, 'ascend'); % sort them from most negative to most positive if Nrndneg>Nobsneg negdistribution(:,i) = stat(1:Nobsneg); % remember the most extreme clusters, i.e. the most negative else negdistribution(1:Nrndneg,i) = stat; % remember the most extreme clusters, i.e. the most negative end else % univariate -> remember the most extreme cluster, which is the most negative if ~isempty(stat), negdistribution(i) = min(stat); end end end % needneg end % for 1:Nrand ft_progress('close'); % compare the values for the observed clusters with the randomization distribution if needpos, posclusters = []; stat = zeros(1,Nobspos); for j = 1:Nobspos if strcmp(cfg.clusterstatistic, 'max'), stat(j) = max(statobs(find(posclusobs==j))); elseif strcmp(cfg.clusterstatistic, 'maxsize'), stat(j) = length(find(posclusobs==j)); elseif strcmp(cfg.clusterstatistic, 'maxsum'), stat(j) = sum(statobs(find(posclusobs==j))); elseif strcmp(cfg.clusterstatistic, 'wcm'), stat(j) = sum((statobs(find(posclusobs==j))-postailcritval).^cfg.wcm_weight); else error('unknown clusterstatistic'); end end % sort the clusters based on their statistical value [stat, indx] = sort(stat,'descend'); % reorder the cluster indices in the data tmp = zeros(size(posclusobs)); for j=1:Nobspos tmp(find(posclusobs==indx(j))) = j; end posclusobs = tmp; if strcmp(cfg.multivariate, 'yes') % estimate the probability of the mutivariate tail, i.e. one p-value for all clusters prob = 0; for i=1:Nrand % compare all clusters simultaneosuly prob = prob + any(posdistribution(:,i)>stat(:)); end if isequal(cfg.numrandomization, 'all') prob = prob/Nrand; else % the minimum possible p-value should not be 0, but 1/N prob = (prob + 1)/(Nrand + 1); end for j = 1:Nobspos % collect a summary of the cluster properties posclusters(j).prob = prob; posclusters(j).clusterstat = stat(j); end % collect the probabilities in one large array prb_pos(find(posclusobs~=0)) = prob; elseif strcmp(cfg.orderedstats, 'yes') % compare the Nth ovbserved cluster against the randomization distribution of the Nth cluster prob = zeros(1,Nobspos); for j = 1:Nobspos if isequal(cfg.numrandomization, 'all') prob(j) = sum(posdistribution(j,:)>stat(j))/Nrand; else % the minimum possible p-value should not be 0, but 1/N prob(j) = (sum(posdistribution(j,:)>stat(j)) + 1)/(Nrand + 1); end % collect a summary of the cluster properties posclusters(j).prob = prob(j); posclusters(j).clusterstat = stat(j); % collect the probabilities in one large array prb_pos(find(posclusobs==j)) = prob(j); end else % univariate -> each cluster has it's own probability prob = zeros(1,Nobspos); for j = 1:Nobspos if isequal(cfg.numrandomization, 'all') prob(j) = sum(posdistribution>stat(j))/Nrand; else % the minimum possible p-value should not be 0, but 1/N prob(j) = (sum(posdistribution>stat(j)) + 1)/(Nrand + 1); end % collect a summary of the cluster properties posclusters(j).prob = prob(j); posclusters(j).clusterstat = stat(j); % collect the probabilities in one large array prb_pos(find(posclusobs==j)) = prob(j); end end end if needneg, negclusters = []; stat = zeros(1,Nobsneg); for j = 1:Nobsneg if strcmp(cfg.clusterstatistic, 'max'), stat(j) = min(statobs(find(negclusobs==j))); elseif strcmp(cfg.clusterstatistic, 'maxsize'), stat(j) = -length(find(negclusobs==j)); % encode the size of a negative cluster as a negative value elseif strcmp(cfg.clusterstatistic, 'maxsum'), stat(j) = sum(statobs(find(negclusobs==j))); elseif strcmp(cfg.clusterstatistic, 'wcm'), stat(j) = -sum((abs(statobs(find(negclusobs==j))-negtailcritval)).^cfg.wcm_weight); % encoded as a negative value else error('unknown clusterstatistic'); end end % sort the clusters based on their statistical value [stat, indx] = sort(stat,'ascend'); % reorder the cluster indices in the observed data tmp = zeros(size(negclusobs)); for j=1:Nobsneg tmp(find(negclusobs==indx(j))) = j; end negclusobs = tmp; if strcmp(cfg.multivariate, 'yes') % estimate the probability of the mutivariate tail, i.e. one p-value for all clusters prob = 0; for i=1:Nrand % compare all clusters simultaneosuly prob = prob + any(negdistribution(:,i)<stat(:)); end if isequal(cfg.numrandomization, 'all') prob = prob/Nrand; else % the minimum possible p-value should not be 0, but 1/N prob = (prob + 1)/(Nrand + 1); end for j = 1:Nobsneg % collect a summary of the cluster properties negclusters(j).prob = prob; negclusters(j).clusterstat = stat(j); end % collect the probabilities in one large array prb_neg(find(negclusobs~=0)) = prob; elseif strcmp(cfg.orderedstats, 'yes') % compare the Nth ovbserved cluster against the randomization distribution of the Nth cluster prob = zeros(1,Nobsneg); for j = 1:Nobsneg if isequal(cfg.numrandomization, 'all') prob(j) = sum(negdistribution(j,:)<stat(j))/Nrand; else % the minimum possible p-value should not be 0, but 1/N prob(j) = (sum(negdistribution(j,:)<stat(j)) + 1)/(Nrand + 1); end % collect a summary of the cluster properties negclusters(j).prob = prob(j); negclusters(j).clusterstat = stat(j); % collect the probabilities in one large array prb_neg(find(negclusobs==j)) = prob(j); end else % univariate -> each cluster has it's own probability prob = zeros(1,Nobsneg); for j = 1:Nobsneg if isequal(cfg.numrandomization, 'all') prob(j) = sum(negdistribution<stat(j))/Nrand; else % the minimum possible p-value should not be 0, but 1/N prob(j) = (sum(negdistribution<stat(j)) + 1)/(Nrand + 1); end % collect a summary of the cluster properties negclusters(j).prob = prob(j); negclusters(j).clusterstat = stat(j); % collect the probabilities in one large array prb_neg(find(negclusobs==j)) = prob(j); end end end if cfg.tail==0 % consider both tails prob = min(prb_neg, prb_pos); % this is the probability for the most unlikely tail elseif cfg.tail==1 % only consider the positive tail prob = prb_pos; elseif cfg.tail==-1 % only consider the negative tail prob = prb_neg; end % collect the remaining details in the output structure stat.prob = prob; if needpos, stat.posclusters = posclusters; stat.posclusterslabelmat = posclusobs; stat.posdistribution = posdistribution; end if needneg, stat.negclusters = negclusters; stat.negclusterslabelmat = negclusobs; stat.negdistribution = negdistribution; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % BEGIN SUBFUNCTION MAKECHANNEIGHBSTRUCTMAT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function channeighbstructmat = makechanneighbstructmat(cfg); % MAKECHANNEIGHBSTRUCTMAT makes the makes the matrix containing the channel % neighbourhood structure. % because clusterstat has no access to the actual data (containing data.label), this workaround is required % cfg.neighbours is cleared here because it is not done where avgoverchan is effectuated (it should actually be changed there) if strcmp(cfg.avgoverchan, 'no') nchan=length(cfg.channel); elseif strcmp(cfg.avgoverchan, 'yes') nchan = 1; cfg.neighbours = []; end channeighbstructmat = false(nchan,nchan); for chan=1:length(cfg.neighbours) [seld] = match_str(cfg.channel, cfg.neighbours(chan).label); [seln] = match_str(cfg.channel, cfg.neighbours(chan).neighblabel); if isempty(seld) % this channel was not present in the data continue; else % add the neighbours of this channel to the matrix channeighbstructmat(seld, seln) = true; end end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % BEGIN SUBFUNCTION MAKECHANCMBNEIGHBMATS %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [chancmbneighbstructmat, chancmbneighbselmat] = makechancmbneighbmats(channeighbstructmat,labelcmb,label,orderedchancmbs,original); % compute CHANCMBNEIGHBSTRUCTMAT and CHANCMBNEIGHBSELMAT, which will be % used for clustering channel combinations. nchan=length(label); nchansqr=nchan^2; % Construct an array labelcmbnrs from labelcmb by replacing the label pairs % in labelcmb by numbers that correspond to the order of the labels in label. nchancmb = size(labelcmb,1); labelcmbnrs=zeros(nchancmb,2); for chanindx=1:nchan [chansel1] = match_str(labelcmb(:,1),label(chanindx)); labelcmbnrs(chansel1,1)=chanindx; [chansel2] = match_str(labelcmb(:,2),label(chanindx)); labelcmbnrs(chansel2,2)=chanindx; end; % Calculate the row and column indices (which are identical) of the % channel combinations that are present in the data. chancmbindcs=zeros(nchancmb,1); for indx=1:nchancmb chancmbindcs(indx)=(labelcmbnrs(indx,1)-1)*nchan + labelcmbnrs(indx,2); end; % put all elements on the diagonal of CHANNEIGHBSTRUCTMAT equal to one channeighbstructmat=channeighbstructmat | logical(eye(nchan)); % Compute CHANCMBNEIGHBSTRUCTMAT % First compute the complete CHANCMBNEIGHBSTRUCTMAT (containing all % ORDERED channel combinations that can be formed with all channels present in % the data) and later select and reorder the channel combinations actually % present in data). In the complete CHANCMBNEIGHBSTRUCTMAT, the row and the % column pairs are ordered lexicographically. chancmbneighbstructmat = false(nchansqr); if original % two channel pairs are neighbours if their first elements are % neighbours chancmbneighbstructmat = logical(kron(channeighbstructmat,ones(nchan))); % or if their second elements are neighbours chancmbneighbstructmat = chancmbneighbstructmat | logical(kron(ones(nchan),channeighbstructmat)); else % version that consumes less memory for chanindx=1:nchan % two channel pairs are neighbours if their first elements are neighbours % or if their second elements are neighbours chancmbneighbstructmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) = ... logical(kron(channeighbstructmat(:,chanindx),ones(nchan))) | ... logical(kron(ones(nchan,1),channeighbstructmat)); end; end; if ~orderedchancmbs if original % or if the first element of the row channel pair is a neighbour of the % second element of the column channel pair chancmbneighbstructmat = chancmbneighbstructmat | logical(repmat(kron(channeighbstructmat,ones(nchan,1)), [1 nchan])); % or if the first element of the column channel pair is a neighbour of the % second element of the row channel pair chancmbneighbstructmat = chancmbneighbstructmat | logical(repmat(kron(channeighbstructmat,ones(1,nchan)),[nchan 1])); else for chanindx=1:nchan % two channel pairs are neighbours if % the first element of the row channel pair is a neighbour of the % second element of the column channel pair % or if the first element of the column channel pair is a neighbour of the % second element of the row channel pair chancmbneighbstructmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) = ... chancmbneighbstructmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) | ... logical(kron(channeighbstructmat,ones(nchan,1))) | ... logical(repmat(kron(channeighbstructmat(:,chanindx),ones(1,nchan)),[nchan 1])); end; end; end; % reorder and select the entries in chancmbneighbstructmat such that they correspond to labelcmb. chancmbneighbstructmat = sparse(chancmbneighbstructmat); chancmbneighbstructmat = chancmbneighbstructmat(chancmbindcs,chancmbindcs); % compute CHANCMBNEIGHBSELMAT % CHANCMBNEIGHBSELMAT identifies so-called parallel pairs. A channel pair % is parallel if (a) all four sensors are different and (b) all elements (of the first % and the second pair) are neighbours of an element of the other pair. % if orderedpairs is true, then condition (b) is as follows: the first % elements of the two pairs are neighbours, and the second elements of the % two pairs are neighbours. % put all elements on the diagonal of CHANNEIGHBSTRUCTMAT equal to zero channeighbstructmat = logical(channeighbstructmat.*(ones(nchan)-diag(ones(nchan,1)))); chancmbneighbselmat = false(nchansqr); if orderedchancmbs if original % if the first element of the row pair is a neighbour of the % first element of the column pair chancmbneighbselmat = logical(kron(channeighbstructmat,ones(nchan))); % and the second element of the row pair is a neighbour of the % second element of the column pair chancmbneighbselmat = chancmbneighbselmat & logical(kron(ones(nchan),channeighbstructmat)); else % version that consumes less memory for chanindx=1:nchan % if the first element of the row pair is a neighbour of the % first element of the column pair % and the second element of the row pair is a neighbour of the % second element of the column pair chancmbneighbselmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) = ... logical(kron(channeighbstructmat(:,chanindx),ones(nchan))) & logical(kron(ones(nchan,1),channeighbstructmat)); end; end; else % unordered channel combinations if original % if the first element of the row pair is a neighbour of one of the % two elements of the column pair chancmbneighbselmat = logical(kron(channeighbstructmat,ones(nchan))) | logical(repmat(kron(channeighbstructmat,ones(nchan,1)), [1 nchan])); % and the second element of the row pair is a neighbour of one of the % two elements of the column pair chancmbneighbselmat = chancmbneighbselmat & (logical(kron(ones(nchan),channeighbstructmat)) | ... logical(repmat(kron(channeighbstructmat,ones(1,nchan)), [nchan 1]))); else % version that consumes less memory for chanindx=1:nchan % if the first element of the row pair is a neighbour of one of the % two elements of the column pair % and the second element of the row pair is a neighbour of one of the % two elements of the column pair chancmbneighbselmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) = ... (logical(kron(channeighbstructmat(:,chanindx),ones(nchan))) | logical(kron(channeighbstructmat,ones(nchan,1)))) ... & (logical(kron(ones(nchan,1),channeighbstructmat)) | ... logical(repmat(kron(channeighbstructmat(:,chanindx),ones(1,nchan)), [nchan 1]))); end; end; end; if original % remove all pairs of channel combinations that have one channel in common. % common channel in the first elements of the two pairs. chancmbneighbselmat = chancmbneighbselmat & kron(~eye(nchan),ones(nchan)); % common channel in the second elements of the two pairs. chancmbneighbselmat = chancmbneighbselmat & kron(ones(nchan),~eye(nchan)); % common channel in the first element of the row pair and the second % element of the column pair. tempselmat=logical(zeros(nchansqr)); tempselmat(:)= ~repmat([repmat([ones(nchan,1); zeros(nchansqr,1)],[(nchan-1) 1]); ones(nchan,1)],[nchan 1]); chancmbneighbselmat = chancmbneighbselmat & tempselmat; % common channel in the second element of the row pair and the first % element of the column pair. chancmbneighbselmat = chancmbneighbselmat & tempselmat'; else noteye=~eye(nchan); tempselmat=logical(zeros(nchansqr,nchan)); tempselmat(:)= ~[repmat([ones(nchan,1); zeros(nchansqr,1)],[(nchan-1) 1]); ones(nchan,1)]; for chanindx=1:nchan % remove all pairs of channel combinations that have one channel in common. % common channel in the first elements of the two pairs. % common channel in the second elements of the two pairs. % common channel in the first element of the row pair and the second % element of the column pair. chancmbneighbselmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) = ... chancmbneighbselmat(:,((chanindx-1)*nchan + 1):(chanindx*nchan)) ... & logical(kron(noteye(:,chanindx),ones(nchan))) ... & logical(kron(ones(nchan,1),noteye)) ... & tempselmat; end; for chanindx=1:nchan % remove all pairs of channel combinations that have one % common channel in the second element of the row pair and the first % element of the column pair. chancmbneighbselmat(((chanindx-1)*nchan + 1):(chanindx*nchan),:) = ... chancmbneighbselmat(((chanindx-1)*nchan + 1):(chanindx*nchan),:) & tempselmat'; end; end; % reorder and select the entries in chancmbneighbselmat such that they correspond to labelcmb. chancmbneighbselmat = sparse(chancmbneighbselmat); chancmbneighbselmat = chancmbneighbselmat(chancmbindcs,chancmbindcs); % put all elements below and on the diagonal equal to zero nchancmbindcs = length(chancmbindcs); for chancmbindx=1:nchancmbindcs selvec=[true(chancmbindx-1,1);false(nchancmbindcs-chancmbindx+1,1)]; chancmbneighbstructmat(:,chancmbindx) = chancmbneighbstructmat(:,chancmbindx) & selvec; chancmbneighbselmat(:,chancmbindx) = chancmbneighbselmat(:,chancmbindx) & selvec; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION convert Nx2 cell array with channel combinations into Nx1 cell array with labels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function label = cmb2label(labelcmb); label = {}; for i=1:size(labelcmb) label{i,1} = [labelcmb{i,1} '&' labelcmb{i,2}]; end
github
philippboehmsturm/antx-master
ft_chantype.m
.m
antx-master/xspm8/external/fieldtrip/fileio/ft_chantype.m
22,382
utf_8
c6505953f3663b6a747e7cc7089a5629
function type = ft_chantype(input, desired) % FT_CHANTYPE determines for each individual channel what type of data it % represents, e.g. a planar gradiometer, axial gradiometer, magnetometer, % trigger channel, etc. If you want to know what the acquisition system is % (e.g. ctf151 or neuromag306), you should not use this function but % FT_SENSTYPE instead. % % Use as % type = ft_chantype(hdr) % type = ft_chantype(sens) % type = ft_chantype(label) % or as % type = ft_chantype(hdr, desired) % type = ft_chantype(sens, desired) % type = ft_chantype(label, desired) % % If the desired unit is not specified as second input argument, this % function returns a Nchan*1 cell-array with a string describing the type % of each channel. % % If the desired unit is specified as second input argument, this function % returns a Nchan*1 boolean vector with "true" for the channels of the % desired type and "false" for the ones that do not match. % % The specification of the channel types depends on the acquisition system, % for example the ctf275 system includes the following type of channels: % meggrad, refmag, refgrad, adc, trigger, eeg, headloc, headloc_gof. % % See also FT_READ_HEADER, FT_SENSTYPE, FT_CHANUNIT % Copyright (C) 2008-2011, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_chantype.m 7215 2012-12-17 19:33:22Z roboos $ % this is to avoid a recursion loop persistent recursion if isempty(recursion) recursion = false; end % determine the type of input, this is handled similarly as in FT_CHANUNIT isheader = isa(input, 'struct') && isfield(input, 'label') && isfield(input, 'Fs'); isgrad = isa(input, 'struct') && isfield(input, 'pnt') && isfield(input, 'ori'); isgrad = (isa(input, 'struct') && isfield(input, 'coilpos')) || isgrad; isgrad = (isa(input, 'struct') && isfield(input, 'chanpos')) || isgrad; islabel = isa(input, 'cell') && isa(input{1}, 'char'); hdr = input; grad = input; label = input; if isheader label = hdr.label; numchan = length(hdr.label); if isfield(hdr, 'grad') grad = hdr.grad; [i1, i2] = match_str(label, grad.label); % ensure that the grad.label order matches the hdr.label order grad.label = grad.label(i2); % reorder the channel labels if isfield(hdr.grad, 'tra') grad.tra = grad.tra(i2,:); % reorder the rows from the tra matrix end end elseif isgrad label = grad.label; numchan = length(label); elseif islabel numchan = length(label); else error('the input that was provided to this function cannot be deciphered'); end % start with unknown type for all channels type = repmat({'unknown'}, numchan, 1); if ft_senstype(input, 'unknown') % don't bother doing all subsequent checks to determine the type of sensor array elseif ft_senstype(input, 'neuromag') && isheader % channames-KI is the channel kind, 1=meg, 202=eog, 2=eeg, 3=trigger (I am not sure, but have inferred this from a single test file) % chaninfo-TY is the Coil type (0=magnetometer, 1=planar gradiometer) if isfield(hdr, 'orig') && isfield(hdr.orig, 'channames') for sel=find(hdr.orig.channames.KI(:)==202)' type{sel} = 'eog'; end for sel=find(hdr.orig.channames.KI(:)==2)' type{sel} = 'eeg'; end for sel=find(hdr.orig.channames.KI(:)==3)' type{sel} = 'digital trigger'; end % determine the MEG channel subtype selmeg=find(hdr.orig.channames.KI(:)==1)'; for i=1:length(selmeg) if hdr.orig.chaninfo.TY(i)==0 type{selmeg(i)} = 'megmag'; elseif hdr.orig.chaninfo.TY(i)==1 type{selmeg(i)} = 'megplanar'; end end elseif isfield(hdr, 'orig') && isfield(hdr.orig, 'chs') && isfield(hdr.orig.chs, 'coil_type') % all the chs.kinds and chs.coil_types are obtained from the MNE manual, p.210-211 for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==2)' %planar gradiometers type(sel) = {'megplanar'}; %Neuromag-122 planar gradiometer end for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==3012)' %planar gradiometers type(sel) = {'megplanar'}; %Type T1 planar grad end for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==3013)' %planar gradiometers type(sel) = {'megplanar'}; %Type T2 planar grad end for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==3014)' %planar gradiometers type(sel) = {'megplanar'}; %Type T3 planar grad end for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==3022)' %magnetometers type(sel) = {'megmag'}; %Type T1 magenetometer end for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==3023)' %magnetometers type(sel) = {'megmag'}; %Type T2 magenetometer end for sel=find([hdr.orig.chs.kind]==1 & [hdr.orig.chs.coil_type]==3024)' %magnetometers type(sel) = {'megmag'}; %Type T3 magenetometer end for sel=find([hdr.orig.chs.kind]==301)' %MEG reference channel, located far from head type(sel) = {'ref'}; end for sel=find([hdr.orig.chs.kind]==2)' %EEG channels type(sel) = {'eeg'}; end for sel=find([hdr.orig.chs.kind]==201)' %MCG channels type(sel) = {'mcg'}; end for sel=find([hdr.orig.chs.kind]==3)' %Stim channels if any([hdr.orig.chs(sel).logno] == 101) %new systems: 101 (and 102, if enabled) are digital; %low numbers are 'pseudo-analog' (if enabled) type(sel([hdr.orig.chs(sel).logno] == 101)) = {'digital trigger'}; type(sel([hdr.orig.chs(sel).logno] == 102)) = {'digital trigger'}; type(sel([hdr.orig.chs(sel).logno] <= 32)) = {'analog trigger'}; others = [hdr.orig.chs(sel).logno] > 32 & [hdr.orig.chs(sel).logno] ~= 101 & ... [hdr.orig.chs(sel).logno] ~= 102; type(sel(others)) = {'other trigger'}; elseif any([hdr.orig.chs(sel).logno] == 14) %older systems: STI 014/015/016 are digital; %lower numbers 'pseudo-analog'(if enabled) type(sel([hdr.orig.chs(sel).logno] == 14)) = {'digital trigger'}; type(sel([hdr.orig.chs(sel).logno] == 15)) = {'digital trigger'}; type(sel([hdr.orig.chs(sel).logno] == 16)) = {'digital trigger'}; type(sel([hdr.orig.chs(sel).logno] <= 13)) = {'analog trigger'}; others = [hdr.orig.chs(sel).logno] > 16; type(sel(others)) = {'other trigger'}; else warning('There does not seem to be a suitable trigger channel.'); type(sel) = {'other trigger'}; end end for sel=find([hdr.orig.chs.kind]==202)' %EOG type(sel) = {'eog'}; end for sel=find([hdr.orig.chs.kind]==302)' %EMG type(sel) = {'emg'}; end for sel=find([hdr.orig.chs.kind]==402)' %ECG type(sel) = {'ecg'}; end for sel=find([hdr.orig.chs.kind]==502)' %MISC type(sel) = {'misc'}; end for sel=find([hdr.orig.chs.kind]==602)' %Resp type(sel) = {'respiration'}; end end elseif ft_senstype(input, 'neuromag122') % the name can be something like "MEG 001" or "MEG001" or "MEG 0113" or "MEG0113" % i.e. with two or three digits and with or without a space sel = myregexp('^MEG', label); type(sel) = {'megplanar'}; elseif ft_senstype(input, 'neuromag306') && isgrad % there should be 204 planar gradiometers and 102 axial magnetometers if isfield(grad, 'tra') tmp = sum(abs(grad.tra),2); sel = (tmp==median(tmp)); type(sel) = {'megplanar'}; sel = (tmp~=median(tmp)); type(sel) = {'megmag'}; end elseif ft_senstype(input, 'ctf') && isheader % According to one source of information meg channels are 5, refmag 0, % refgrad 1, adcs 18, trigger 11, eeg 9. % % According to another source of information it is as follows % refMagnetometers: 0 % refGradiometers: 1 % meg_sens: 5 % eeg_sens: 9 % adc: 10 % stim_ref: 11 % video_time: 12 % sam: 15 % virtual_channels: 16 % sclk_ref: 17 % start with an empty one origSensType = []; if isfield(hdr, 'orig') if isfield(hdr.orig, 'sensType') && isfield(hdr.orig, 'Chan') % the header was read using the open-source matlab code that originates from CTF and that was modified by the FCDC origSensType = hdr.orig.sensType; elseif isfield(hdr.orig, 'res4') && isfield(hdr.orig.res4, 'senres') % the header was read using the CTF p-files, i.e. readCTFds origSensType = [hdr.orig.res4.senres.sensorTypeIndex]; elseif isfield(hdr.orig, 'sensor') && isfield(hdr.orig.sensor, 'info') % the header was read using the CTF importer from the NIH and Daren Weber origSensType = [hdr.orig.sensor.info.index]; end end if isempty(origSensType) warning('could not determine channel type from the CTF header'); end for sel=find(origSensType(:)==5)' type{sel} = 'meggrad'; end for sel=find(origSensType(:)==0)' type{sel} = 'refmag'; end for sel=find(origSensType(:)==1)' type{sel} = 'refgrad'; end for sel=find(origSensType(:)==18)' type{sel} = 'adc'; end for sel=find(origSensType(:)==11)' type{sel} = 'trigger'; end for sel=find(origSensType(:)==9)' type{sel} = 'eeg'; end for sel=find(origSensType(:)==29)' type{sel} = 'reserved'; % these are "reserved for future use", but relate to head localization end for sel=find(origSensType(:)==13)' type{sel} = 'headloc'; % these represent the x, y, z position of the head coils end for sel=find(origSensType(:)==28)' type{sel} = 'headloc_gof'; % these represent the goodness of fit for the head coils end % for sel=find(origSensType(:)==23)' % type{sel} = 'SPLxxxx'; % I have no idea what these are % end elseif ft_senstype(input, 'ctf') && isgrad % in principle it is possible to look at the number of coils, but here the channels are identified based on their name sel = myregexp('^M[ZLR][A-Z][0-9][0-9]$', grad.label); type(sel) = {'meggrad'}; % normal gradiometer channels sel = myregexp('^S[LR][0-9][0-9]$', grad.label); type(sel) = {'meggrad'}; % normal gradiometer channels in the 64 channel CTF system sel = myregexp('^B[GPQR][0-9]$', grad.label); type(sel) = {'refmag'}; % reference magnetometers sel = myregexp('^[GPQR][0-9][0-9]$', grad.label); type(sel) = {'refgrad'}; % reference gradiometers elseif ft_senstype(input, 'ctf') && islabel % the channels have to be identified based on their name alone sel = myregexp('^M[ZLR][A-Z][0-9][0-9]$', label); type(sel) = {'meggrad'}; % normal gradiometer channels sel = myregexp('^S[LR][0-9][0-9]$', label); type(sel) = {'meggrad'}; % normal gradiometer channels in the 64 channel CTF system sel = myregexp('^B[GPR][0-9]$', label); type(sel) = {'refmag'}; % reference magnetometers sel = myregexp('^[GPQR][0-9][0-9]$', label); type(sel) = {'refgrad'}; % reference gradiometers elseif ft_senstype(input, 'bti') % all 4D-BTi MEG channels start with "A" % all 4D-BTi reference channels start with M or G % all 4D-BTi EEG channels start with E type(strncmp('A', label, 1)) = {'meg'}; type(strncmp('M', label, 1)) = {'refmag'}; type(strncmp('G', label, 1)) = {'refgrad'}; if isgrad && isfield(grad, 'tra') gradtype = repmat({'unknown'}, size(grad.label)); gradtype(strncmp('A', grad.label, 1)) = {'meg'}; gradtype(strncmp('M', grad.label, 1)) = {'refmag'}; gradtype(strncmp('G', grad.label, 1)) = {'refgrad'}; % look at the number of coils of the meg channels selchan = find(strcmp('meg', gradtype)); for k = 1:length(selchan) ncoils = length(find(grad.tra(selchan(k),:)==1)); if ncoils==1, gradtype{selchan(k)} = 'megmag'; elseif ncoils==2, gradtype{selchan(k)} = 'meggrad'; end end [selchan, selgrad] = match_str(label, grad.label); type(selchan) = gradtype(selgrad); end % This is to allow setting additional channel types based on the names if isheader && issubfield(hdr, 'orig.channel_data.chan_label') tmplabel = {hdr.orig.channel_data.chan_label}; tmplabel = tmplabel(:); else tmplabel = label; % might work end sel = strmatch('unknown', type, 'exact'); if ~isempty(sel) type(sel)= ft_chantype(tmplabel(sel)); sel = strmatch('unknown', type, 'exact'); if ~isempty(sel) type(sel(strncmp('E', label(sel), 1))) = {'eeg'}; end end elseif ft_senstype(input, 'itab') && isheader origtype = [input.orig.ch.type]; type(origtype==0) = {'unknown'}; type(origtype==1) = {'ele'}; type(origtype==2) = {'mag'}; % might be magnetometer or gradiometer, look at the number of coils type(origtype==4) = {'ele ref'}; type(origtype==8) = {'mag ref'}; type(origtype==16) = {'aux'}; type(origtype==32) = {'param'}; type(origtype==64) = {'digit'}; type(origtype==128) = {'flag'}; % these are the channels that are visible to fieldtrip chansel = 1:input.orig.nchan; type = type(chansel); elseif ft_senstype(input, 'yokogawa') && isheader % This is to recognize Yokogawa channel types from the original header % This is from the original documentation NullChannel = 0; MagnetoMeter = 1; AxialGradioMeter = 2; PlannerGradioMeter = 3; RefferenceChannelMark = hex2dec('0100'); RefferenceMagnetoMeter = bitor( RefferenceChannelMark, MagnetoMeter ); RefferenceAxialGradioMeter = bitor( RefferenceChannelMark, AxialGradioMeter ); RefferencePlannerGradioMeter = bitor( RefferenceChannelMark, PlannerGradioMeter); TriggerChannel = -1; EegChannel = -2; EcgChannel = -3; EtcChannel = -4; if ft_hastoolbox('yokogawa_meg_reader') % shorten names ch_info = hdr.orig.channel_info.channel; type_orig = [ch_info.type]; sel = (type_orig == NullChannel); type(sel) = {'null'}; sel = (type_orig == MagnetoMeter); type(sel) = {'megmag'}; sel = (type_orig == AxialGradioMeter); type(sel) = {'meggrad'}; sel = (type_orig == PlannerGradioMeter); type(sel) = {'megplanar'}; sel = (type_orig == RefferenceMagnetoMeter); type(sel) = {'refmag'}; sel = (type_orig == RefferenceAxialGradioMeter); type(sel) = {'refgrad'}; sel = (type_orig == RefferencePlannerGradioMeter); type(sel) = {'refplanar'}; sel = (type_orig == TriggerChannel); type(sel) = {'trigger'}; sel = (type_orig == EegChannel); type(sel) = {'eeg'}; sel = (type_orig == EcgChannel); type(sel) = {'ecg'}; sel = (type_orig == EtcChannel); type(sel) = {'etc'}; elseif ft_hastoolbox('yokogawa') sel = (hdr.orig.channel_info(:, 2) == NullChannel); type(sel) = {'null'}; sel = (hdr.orig.channel_info(:, 2) == MagnetoMeter); type(sel) = {'megmag'}; sel = (hdr.orig.channel_info(:, 2) == AxialGradioMeter); type(sel) = {'meggrad'}; sel = (hdr.orig.channel_info(:, 2) == PlannerGradioMeter); type(sel) = {'megplanar'}; sel = (hdr.orig.channel_info(:, 2) == RefferenceMagnetoMeter); type(sel) = {'refmag'}; sel = (hdr.orig.channel_info(:, 2) == RefferenceAxialGradioMeter); type(sel) = {'refgrad'}; sel = (hdr.orig.channel_info(:, 2) == RefferencePlannerGradioMeter); type(sel) = {'refplanar'}; sel = (hdr.orig.channel_info(:, 2) == TriggerChannel); type(sel) = {'trigger'}; sel = (hdr.orig.channel_info(:, 2) == EegChannel); type(sel) = {'eeg'}; sel = (hdr.orig.channel_info(:, 2) == EcgChannel); type(sel) = {'ecg'}; sel = (hdr.orig.channel_info(:, 2) == EtcChannel); type(sel) = {'etc'}; end elseif ft_senstype(input, 'yokogawa') && isgrad % all channels in the gradiometer definition are meg % type(1:end) = {'meg'}; % channels are identified based on their name: only magnetic as isgrad==1 sel = myregexp('^M[0-9][0-9][0-9]$', grad.label); type(sel) = {'megmag'}; sel = myregexp('^AG[0-9][0-9][0-9]$', grad.label); type(sel) = {'meggrad'}; sel = myregexp('^PG[0-9][0-9][0-9]$', grad.label); type(sel) = {'megplanar'}; sel = myregexp('^RM[0-9][0-9][0-9]$', grad.label); type(sel) = {'refmag'}; sel = myregexp('^RAG[0-9][0-9][0-9]$', grad.label); type(sel) = {'refgrad'}; sel = myregexp('^RPG[0-9][0-9][0-9]$', grad.label); type(sel) = {'refplanar'}; elseif ft_senstype(input, 'yokogawa') && islabel % the yokogawa channel labels are a mess, so autodetection is not possible % type(1:end) = {'meg'}; sel = myregexp('[0-9][0-9][0-9]$', label); type(sel) = {'null'}; sel = myregexp('^M[0-9][0-9][0-9]$', label); type(sel) = {'megmag'}; sel = myregexp('^AG[0-9][0-9][0-9]$', label); type(sel) = {'meggrad'}; sel = myregexp('^PG[0-9][0-9][0-9]$', label); type(sel) = {'megplanar'}; sel = myregexp('^RM[0-9][0-9][0-9]$', label); type(sel) = {'refmag'}; sel = myregexp('^RAG[0-9][0-9][0-9]$', label); type(sel) = {'refgrad'}; sel = myregexp('^RPG[0-9][0-9][0-9]$', label); type(sel) = {'refplanar'}; sel = myregexp('^TRIG[0-9][0-9][0-9]$', label); type(sel) = {'trigger'}; sel = myregexp('^EEG[0-9][0-9][0-9]$', label); type(sel) = {'eeg'}; sel = myregexp('^ECG[0-9][0-9][0-9]$', label); type(sel) = {'ecg'}; sel = myregexp('^ETC[0-9][0-9][0-9]$', label); type(sel) = {'etc'}; elseif ft_senstype(input, 'itab') && isheader sel = ([hdr.orig.ch.type]==0); type(sel) = {'unknown'}; sel = ([hdr.orig.ch.type]==1); type(sel) = {'unknown'}; sel = ([hdr.orig.ch.type]==2); type(sel) = {'megmag'}; sel = ([hdr.orig.ch.type]==8); type(sel) = {'megref'}; sel = ([hdr.orig.ch.type]==16); type(sel) = {'aux'}; sel = ([hdr.orig.ch.type]==64); type(sel) = {'digital'}; % not all channels are actually processed by fieldtrip, so only return % the types fopr the ones that read_header and read_data return type = type(hdr.orig.chansel); elseif ft_senstype(input, 'itab') && isgrad % the channels have to be identified based on their name alone sel = myregexp('^MAG_[0-9][0-9][0-9]$', label); type(sel) = {'megmag'}; sel = myregexp('^MAG_[0-9][0-9]$', label); % for the itab28 system type(sel) = {'megmag'}; sel = myregexp('^MAG_[0-9]$', label); % for the itab28 system type(sel) = {'megmag'}; sel = myregexp('^REF_[0-9][0-9][0-9]$', label); type(sel) = {'megref'}; sel = myregexp('^AUX.*$', label); type(sel) = {'aux'}; elseif ft_senstype(input, 'itab') && islabel % the channels have to be identified based on their name alone sel = myregexp('^MAG_[0-9][0-9][0-9]$', label); type(sel) = {'megmag'}; sel = myregexp('^REF_[0-9][0-9][0-9]$', label); type(sel) = {'megref'}; sel = myregexp('^AUX.*$', label); type(sel) = {'aux'}; elseif ft_senstype(input, 'eeg') && islabel % use an external helper function to define the list with EEG channel names type(match_str(label, ft_senslabel(ft_senstype(label)))) = {'eeg'}; elseif ft_senstype(input, 'eeg') && isheader % use an external helper function to define the list with EEG channel names type(match_str(hdr.label, ft_senslabel(ft_senstype(hdr)))) = {'eeg'}; elseif ft_senstype(input, 'plexon') && isheader % this is a complete header that was read from a Plexon *.nex file using read_plexon_nex for i=1:numchan switch hdr.orig.VarHeader(i).Type case 0 type{i} = 'spike'; case 1 type{i} = 'event'; case 2 type{i} = 'interval'; % Interval variables? case 3 type{i} = 'waveform'; case 4 type{i} = 'population'; % Population variables ? case 5 type{i} = 'analog'; otherwise % keep the default 'unknown' type end end end % ft_senstype % if possible, set additional types based on channel labels label2type = { {'ecg', 'ekg'}; {'emg'}; {'eog', 'heog', 'veog'}; {'lfp'}; {'eeg'}; }; for i = 1:numel(label2type) for j = 1:numel(label2type{i}) type(intersect(strmatch(label2type{i}{j}, lower(label)), strmatch('unknown', type, 'exact'))) = label2type{i}(1); end end if all(strcmp(type, 'unknown')) && ~recursion % try whether only lowercase channel labels makes a difference if islabel recursion = true; type = ft_chantype(lower(input)); recursion = false; elseif isfield(input, 'label') input.label = lower(input.label); recursion = true; type = ft_chantype(input); recursion = false; end end if all(strcmp(type, 'unknown')) && ~recursion % try whether only uppercase channel labels makes a difference if islabel recursion = true; type = ft_chantype(upper(input)); recursion = false; elseif isfield(input, 'label') input.label = upper(input.label); recursion = true; type = ft_chantype(input); recursion = false; end end if nargin>1 % return a boolean vector if isequal(desired, 'meg') || isequal(desired, 'ref') % only compare the first three characters, i.e. meggrad or megmag should match type = strncmp(desired, type, 3); else type = strcmp(desired, type); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function match = myregexp(pat, list) match = false(size(list)); for i=1:numel(list) match(i) = ~isempty(regexp(list{i}, pat, 'once')); end
github
philippboehmsturm/antx-master
ft_read_event.m
.m
antx-master/xspm8/external/fieldtrip/fileio/ft_read_event.m
66,708
utf_8
4935be6afe902a8f429fc10ecc1b06ac
function [event] = ft_read_event(filename, varargin) % FT_READ_EVENT reads all events from an EEG/MEG dataset and returns % them in a well defined structure. It is a wrapper around different % EEG/MEG file importers, directly supported formats are CTF, Neuromag, % EEP, BrainVision, Neuroscan and Neuralynx. % % Use as % [event] = ft_read_event(filename, ...) % % Additional options should be specified in key-value pairs and can be % 'dataformat' string % 'headerformat' string % 'eventformat' string % 'header' structure, see FT_READ_HEADER % 'detectflank' string, can be 'up', 'down', 'both' or 'auto' (default is system specific) % 'trigshift' integer, number of samples to shift from flank to detect trigger value (default = 0) % 'trigindx' list with channel numbers for the trigger detection, only for Yokogawa (default is automatic) % 'threshold' threshold for analog trigger channels (default is system specific) % 'blocking' wait for the selected number of events (default = 'no') % 'timeout' amount of time in seconds to wait when blocking (default = 5) % % Furthermore, you can specify optional arguments as key-value pairs % for filtering the events, e.g. to select only events of a specific % type, of a specific value, or events between a specific begin and % end sample. This event filtering is especially usefull for real-time % processing. See FT_FILTER_EVENT for more details. % % Some data formats have trigger channels that are sampled continuously with % the same rate as the electrophysiological data. The default is to detect % only the up-going TTL flanks. The trigger events will correspond with the % first sample where the TTL value is up. This behaviour can be changed % using the 'detectflank' option, which also allows for detecting the % down-going flank or both. In case of detecting the down-going flank, the % sample number of the event will correspond with the first sample at which % the TTF went down, and the value will correspond to the TTL value just % prior to going down. % % This function returns an event structure with the following fields % event.type = string % event.sample = expressed in samples, the first sample of a recording is 1 % event.value = number or string % event.offset = expressed in samples % event.duration = expressed in samples % event.timestamp = expressed in timestamp units, which vary over systems (optional) % % The event type and sample fields are always defined, other fields can be empty, % depending on the type of event file. Events are sorted by the sample on % which they occur. After reading the event structure, you can use the % following tricks to extract information about those events in which you % are interested. % % Determine the different event types % unique({event.type}) % % Get the index of all trial events % find(strcmp('trial', {event.type})) % % Make a vector with all triggers that occurred on the backpanel % [event(find(strcmp('backpanel trigger', {event.type}))).value] % % Find the events that occurred in trial 26 % t=26; samples_trials = [event(find(strcmp('trial', {event.type}))).sample]; % find([event.sample]>samples_trials(t) & [event.sample]<samples_trials(t+1)) % % The list of supported file formats can be found in FT_READ_HEADER. % % See also FT_READ_HEADER, FT_READ_DATA, FT_WRITE_EVENT, FT_FILTER_EVENT % Copyright (C) 2004-2012 Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_read_event.m 7350 2013-01-18 05:03:58Z josdie $ global event_queue % for fcdc_global persistent sock % for fcdc_tcp persistent db_blob % for fcdc_mysql if isempty(db_blob) db_blob = 0; end if iscell(filename) % use recursion to read from multiple event sources event = []; for i=1:numel(filename) tmp = ft_read_event(filename{i}, varargin{:}); event = appendevent(event(:), tmp(:)); end return end % optionally get the data from the URL and make a temporary local copy filename = fetch_url(filename); % get the options eventformat = ft_getopt(varargin, 'eventformat'); if isempty(eventformat) % only do the autodetection if the format was not specified eventformat = ft_filetype(filename); end hdr = ft_getopt(varargin, 'header'); detectflank = ft_getopt(varargin, 'detectflank', 'up'); % up, down or both trigshift = ft_getopt(varargin, 'trigshift'); % default is assigned in subfunction trigindx = ft_getopt(varargin, 'trigindx'); % this allows to override the automatic trigger channel detection and is useful for Yokogawa headerformat = ft_getopt(varargin, 'headerformat'); dataformat = ft_getopt(varargin, 'dataformat'); threshold = ft_getopt(varargin, 'threshold'); % this is used for analog channels % this allows to read only events in a certain range, supported for selected data formats only flt_type = ft_getopt(varargin, 'type'); flt_value = ft_getopt(varargin, 'value'); flt_minsample = ft_getopt(varargin, 'minsample'); flt_maxsample = ft_getopt(varargin, 'maxsample'); flt_mintimestamp = ft_getopt(varargin, 'mintimestamp'); flt_maxtimestamp = ft_getopt(varargin, 'maxtimestamp'); flt_minnumber = ft_getopt(varargin, 'minnumber'); flt_maxnumber = ft_getopt(varargin, 'maxnumber'); % thie allows blocking reads to avoid having to poll many times for online processing blocking = ft_getopt(varargin, 'blocking', false); % true or false timeout = ft_getopt(varargin, 'timeout', 5); % seconds % convert from 'yes'/'no' into boolean blocking = istrue(blocking); if any(strcmp(eventformat, {'brainvision_eeg', 'brainvision_dat'})) [p, f] = fileparts(filename); filename = fullfile(p, [f '.vhdr']); eventformat = 'brainvision_vhdr'; end if strcmp(eventformat, 'brainvision_vhdr') % read the headerfile belonging to the dataset and try to determine the corresponding markerfile eventformat = 'brainvision_vmrk'; hdr = read_brainvision_vhdr(filename); % replace the filename with the filename of the markerfile if ~isfield(hdr, 'MarkerFile') || isempty(hdr.MarkerFile) filename = []; else [p, f] = fileparts(filename); filename = fullfile(p, hdr.MarkerFile); end end % start with an empty event structure event = []; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the events with the low-level reading function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch eventformat case 'fcdc_global' event = event_queue; case {'4d' '4d_pdf', '4d_m4d', '4d_xyz'} if isempty(hdr) hdr = ft_read_header(filename, 'headerformat', eventformat); end % read the trigger channel and do flank detection trgindx = match_str(hdr.label, 'TRIGGER'); if isfield(hdr, 'orig') && isfield(hdr.orig, 'config_data') && strcmp(hdr.orig.config_data.site_name, 'Glasgow'), trigger = read_trigger(filename, 'header', hdr, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trgindx, 'detectflank', detectflank, 'trigshift', trigshift,'fix4dglasgow',1, 'dataformat', '4d'); else trigger = read_trigger(filename, 'header', hdr, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trgindx, 'detectflank', detectflank, 'trigshift', trigshift,'fix4dglasgow',0, 'dataformat', '4d'); end event = appendevent(event, trigger); respindx = match_str(hdr.label, 'RESPONSE'); if ~isempty(respindx) response = read_trigger(filename, 'header', hdr, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', respindx, 'detectflank', detectflank, 'trigshift', trigshift, 'dataformat', '4d'); event = appendevent(event, response); end case 'bci2000_dat' % this requires the load_bcidat mex file to be present on the path ft_hastoolbox('BCI2000', 1); if isempty(hdr) hdr = ft_read_header(filename); end if isfield(hdr.orig, 'signal') && isfield(hdr.orig, 'states') % assume that the complete data is stored in the header, this speeds up subsequent read operations signal = hdr.orig.signal; states = hdr.orig.states; parameters = hdr.orig.parameters; total_samples = hdr.orig.total_samples; else [signal, states, parameters, total_samples] = load_bcidat(filename); end list = fieldnames(states); % loop over all states and detect the flanks, the following code was taken from read_trigger for i=1:length(list) channel = list{i}; trig = double(getfield(states, channel)); pad = trig(1); trigshift = 0; begsample = 1; switch detectflank case 'up' % convert the trigger into an event with a value at a specific sample for j=find(diff([pad trig(:)'])>0) event(end+1).type = channel; event(end ).sample = j + begsample - 1; % assign the sample at which the trigger has gone down event(end ).value = trig(j+trigshift); % assign the trigger value just _after_ going up end case 'down' % convert the trigger into an event with a value at a specific sample for j=find(diff([pad trig(:)'])<0) event(end+1).type = channel; event(end ).sample = j + begsample - 1; % assign the sample at which the trigger has gone down event(end ).value = trig(j-1-trigshift); % assign the trigger value just _before_ going down end case 'both' % convert the trigger into an event with a value at a specific sample for j=find(diff([pad trig(:)'])>0) event(end+1).type = [channel '_up']; % distinguish between up and down flank event(end ).sample = j + begsample - 1; % assign the sample at which the trigger has gone down event(end ).value = trig(j+trigshift); % assign the trigger value just _after_ going up end % convert the trigger into an event with a value at a specific sample for j=find(diff([pad trig(:)'])<0) event(end+1).type = [channel '_down']; % distinguish between up and down flank event(end ).sample = j + begsample - 1; % assign the sample at which the trigger has gone down event(end ).value = trig(j-1-trigshift); % assign the trigger value just _before_ going down end otherwise error('incorrect specification of ''detectflank'''); end end case {'besa_avr', 'besa_swf'} if isempty(hdr) hdr = ft_read_header(filename); end event(end+1).type = 'average'; event(end ).sample = 1; event(end ).duration = hdr.nSamples; event(end ).offset = -hdr.nSamplesPre; event(end ).value = []; case {'biosemi_bdf', 'bham_bdf'} % read the header, required to determine the stimulus channels and trial specification if isempty(hdr) hdr = ft_read_header(filename); end % specify the range to search for triggers, default is the complete file if ~isempty(flt_minsample) begsample = flt_minsample; else begsample = 1; end if ~isempty(flt_maxsample) endsample = flt_maxsample; else endsample = hdr.nSamples*hdr.nTrials; end if ~strcmp(detectflank, 'up') if strcmp(detectflank, 'both') warning('only up-going flanks are supported for Biosemi'); detectflank = 'up'; else error('only up-going flanks are supported for Biosemi'); % FIXME the next section on trigger detection should be merged with the % READ_CTF_TRIGGER (which also does masking with bit-patterns) into the % READ_TRIGGER function end end % find the STATUS channel and read the values from it schan = find(strcmpi(hdr.label,'STATUS')); sdata = ft_read_data(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', begsample, 'endsample', endsample, 'chanindx', schan); try % find indices of negative numbers bit24i = find(sdata < 0); % make number positive and preserve bits 0-22 sdata(bit24i) = bitcmp(abs(sdata(bit24i))-1,24); % re-insert the sign bit on its original location, i.e. bit24 sdata(bit24i) = sdata(bit24i)+(2^(24-1)); % typecast the data to ensure that the status channel is represented in 32 bits sdata = uint32(sdata); catch % convert to 32-bit integer representation and only preserve the lowest 24 bits sdata = bitand(int32(sdata), 2^24-1); end byte1 = 2^8 - 1; byte2 = 2^16 - 1 - byte1; byte3 = 2^24 - 1 - byte1 - byte2; % get the respective status and trigger bits trigger = bitand(sdata, bitor(byte1, byte2)); % contained in the lower two bytes epoch = int8(bitget(sdata, 16+1)); cmrange = int8(bitget(sdata, 20+1)); battery = int8(bitget(sdata, 22+1)); % determine when the respective status bits go up or down flank_trigger = diff([0 trigger]); flank_epoch = diff([0 epoch ]); flank_cmrange = diff([0 cmrange]); flank_battery = diff([0 battery]); for i=find(flank_trigger>0) event(end+1).type = 'STATUS'; event(end ).sample = i + begsample - 1; event(end ).value = double(trigger(i)); end for i=find(flank_epoch==1) event(end+1).type = 'Epoch'; event(end ).sample = i; end for i=find(flank_cmrange==1) event(end+1).type = 'CM_in_range'; event(end ).sample = i; end for i=find(flank_cmrange==-1) event(end+1).type = 'CM_out_of_range'; event(end ).sample = i; end for i=find(flank_battery==1) event(end+1).type = 'Battery_low'; event(end ).sample = i; end for i=find(flank_battery==-1) event(end+1).type = 'Battery_ok'; event(end ).sample = i; end case {'biosig', 'gdf'} % FIXME it would be nice to figure out how sopen/sread return events % for all possible fileformats that can be processed with biosig % % This section of code is opaque with respect to the gdf file being a % single file or the first out of a sequence with postfix _1, _2, ... % because it uses private/read_trigger which again uses ft_read_data if isempty(hdr) hdr = ft_read_header(filename); end % the following applies to Biosemi data that is stored in the gdf format statusindx = find(strcmp(hdr.label, 'STATUS')); if length(statusindx)==1 % represent the rising flanks in the STATUS channel as events event = read_trigger(filename, 'header', hdr, 'chanindx', statusindx, ... 'detectflank', 'up', 'fixbiosemi', true, 'begsample', flt_minsample, 'endsample', flt_maxsample); else warning('BIOSIG does not have a consistent event representation, skipping events') event = []; end case 'brainvision_vmrk' fid=fopen(filename,'rt'); if fid==-1, error('cannot open BrainVision marker file') end line = []; while ischar(line) || isempty(line) line = fgetl(fid); if ~isempty(line) && ~(isnumeric(line) && line==-1) if strncmpi(line, 'Mk', 2) % this line contains a marker tok = tokenize(line, '=', 0); % do not squeeze repetitions of the seperator if length(tok)~=2 warning('skipping unexpected formatted line in BrainVision marker file'); else % the line looks like "MkXXX=YYY", which is ok % the interesting part now is in the YYY, i.e. the second token tok = tokenize(tok{2}, ',', 0); % do not squeeze repetitions of the seperator if isempty(tok{1}) tok{1} = []; end if isempty(tok{2}) tok{2} = []; end event(end+1).type = tok{1}; event(end ).value = tok{2}; event(end ).sample = str2num(tok{3}); event(end ).duration = str2num(tok{4}); end end end end fclose(fid); case 'ced_son' % check that the required low-level toolbox is available ft_hastoolbox('neuroshare', 1); orig = read_ced_son(filename,'readevents','yes'); event = struct('type', {orig.events.type},... 'sample', {orig.events.sample},... 'value', {orig.events.value},... 'offset', {orig.events.offset},... 'duration', {orig.events.duration}); case 'ced_spike6mat' if isempty(hdr) hdr = ft_read_header(filename); end chanindx = []; for i = 1:numel(hdr.orig) if ~any(isfield(hdr.orig{i}, {'units', 'scale'})) chanindx = [chanindx i]; end end if ~isempty(chanindx) trigger = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', chanindx, 'detectflank', detectflank); event = appendevent(event, trigger); end case {'ctf_ds', 'ctf_meg4', 'ctf_res4', 'ctf_old'} % obtain the dataset name if ft_filetype(filename, 'ctf_meg4') || ft_filetype(filename, 'ctf_res4') filename = fileparts(filename); end [path, name, ext] = fileparts(filename); headerfile = fullfile(path, [name ext], [name '.res4']); datafile = fullfile(path, [name ext], [name '.meg4']); classfile = fullfile(path, [name ext], 'ClassFile.cls'); markerfile = fullfile(path, [name ext], 'MarkerFile.mrk'); % in case ctf_old was specified as eventformat, the other reading functions should also know about that if strcmp(eventformat, 'ctf_old') dataformat = 'ctf_old'; headerformat = 'ctf_old'; end % read the header, required to determine the stimulus channels and trial specification if isempty(hdr) hdr = ft_read_header(headerfile, 'headerformat', headerformat); end try % read the trigger codes from the STIM channel, usefull for (pseudo) continuous data % this splits the trigger channel into the lowers and highest 16 bits, % corresponding with the front and back panel of the electronics cabinet at the Donders Centre [backpanel, frontpanel] = read_ctf_trigger(filename); for i=find(backpanel(:)') event(end+1).type = 'backpanel trigger'; event(end ).sample = i; event(end ).value = backpanel(i); end for i=find(frontpanel(:)') event(end+1).type = 'frontpanel trigger'; event(end ).sample = i; event(end ).value = frontpanel(i); end end % determine the trigger channels from the header if isfield(hdr, 'orig') && isfield(hdr.orig, 'sensType') origSensType = hdr.orig.sensType; elseif isfield(hdr, 'orig') && isfield(hdr.orig, 'res4') origSensType = [hdr.orig.res4.senres.sensorTypeIndex]; else origSensType = []; end % meg channels are 5, refmag 0, refgrad 1, adcs 18, trigger 11, eeg 9 trigchanindx = find(origSensType==11); if ~isempty(trigchanindx) % read the trigger channel and do flank detection trigger = read_trigger(filename, 'header', hdr, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trigchanindx, 'dataformat', dataformat, 'detectflank', detectflank, 'trigshift', trigshift, 'fixctf', 1); event = appendevent(event, trigger); end % read the classification file and make an event for each classified trial [condNumbers,condLabels] = read_ctf_cls(classfile); if ~isempty(condNumbers) Ncond = length(condLabels); for i=1:Ncond for j=1:length(condNumbers{i}) event(end+1).type = 'classification'; event(end ).value = condLabels{i}; event(end ).sample = (condNumbers{i}(j)-1)*hdr.nSamples + 1; event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; end end end if exist(markerfile,'file') % read the marker file and make an event for each marker % this depends on the readmarkerfile function that I got from Tom Holroyd % I have not tested this myself extensively, since at the FCDC we % don't use the marker files mrk = readmarkerfile(filename); for i=1:mrk.number_markers for j=1:mrk.number_samples(i) % determine the location of the marker, expressed in samples trialnum = mrk.trial_times{i}(j,1); synctime = mrk.trial_times{i}(j,2); begsample = (trialnum-1)*hdr.nSamples + 1; % of the trial, relative to the start of the datafile endsample = (trialnum )*hdr.nSamples; % of the trial, relative to the start of the datafile offset = round(synctime*hdr.Fs); % this is the offset (in samples) relative to time t=0 for this trial offset = offset + hdr.nSamplesPre; % and time t=0 corrsponds with the nSamplesPre'th sample % store this marker as an event event(end+1).type = mrk.marker_names{i}; event(end ).value = []; event(end ).sample = begsample + offset; event(end ).duration = 0; event(end ).offset = offset; end end end case 'ctf_shm' % contact Robert Oostenveld if you are interested in real-time acquisition on the CTF system % read the events from shared memory event = read_shm_event(filename, varargin{:}); case 'edf' % EDF itself does not contain events, but EDF+ does define an annotation channel if isempty(hdr) hdr = ft_read_header(filename); end if issubfield(hdr, 'orig.annotation') && ~isempty(hdr.orig.annotation) % read the data of the annotation channel as 16 bit evt = read_edf(filename, hdr); % undo the faulty calibration evt = (evt - hdr.orig.Off(hdr.orig.annotation)) ./ hdr.orig.Cal(hdr.orig.annotation); % convert the 16 bit format into the seperate bytes evt = typecast(int16(evt), 'uint8'); % construct the Time-stamped Annotations Lists (TAL) tal = tokenize(evt, char(0), true); event = []; for i=1:length(tal) tok = tokenize(tal{i}, char(20)); time = str2double(char(tok{1})); % there can be multiple annotations per time, the last cell is always empty for j=2:length(tok)-1 anot = char(tok{j}); % represent the annotation as event event(end+1).type = 'annotation'; event(end ).value = anot; event(end ).sample = round(time*hdr.Fs) + 1; event(end ).duration = 0; event(end ).offset = 0; end end else event = []; end case 'eeglab_set' if isempty(hdr) hdr = ft_read_header(filename); end event = read_eeglabevent(filename, 'header', hdr); case 'eeglab_erp' if isempty(hdr) hdr = ft_read_header(filename); end event = read_erplabevent(filename, 'header', hdr); case 'spmeeg_mat' if isempty(hdr) hdr = ft_read_header(filename); end event = read_spmeeg_event(filename, 'header', hdr); case 'eep_avr' % check that the required low-level toolbox is available ft_hastoolbox('eeprobe', 1); % the headerfile and datafile are the same if isempty(hdr) hdr = ft_read_header(filename); end event(end+1).type = 'average'; event(end ).sample = 1; event(end ).duration = hdr.nSamples; event(end ).offset = -hdr.nSamplesPre; event(end ).value = []; case 'eep_cnt' % check that the required low-level toolbox is available ft_hastoolbox('eeprobe', 1); % try to read external trigger file in EEP format trgfile = [filename(1:(end-3)), 'trg']; if exist(trgfile, 'file') if isempty(hdr) hdr = ft_read_header(filename); end tmp = read_eep_trg(trgfile); % translate the EEProbe trigger codes to events for i=1:length(tmp) event(i).type = 'trigger'; event(i).sample = round((tmp(i).time/1000) * hdr.Fs) + 1; % convert from ms to samples event(i).value = tmp(i).code; event(i).offset = 0; event(i).duration = 0; end else warning('no triggerfile was found'); end case 'egi_egis' if isempty(hdr) hdr = ft_read_header(filename); end fhdr = hdr.orig.fhdr; chdr = hdr.orig.chdr; ename = hdr.orig.ename; cnames = hdr.orig.cnames; fcom = hdr.orig.fcom; ftext = hdr.orig.ftext; eventCount=0; for cel=1:fhdr(18) for trial=1:chdr(cel,2) eventCount=eventCount+1; event(eventCount).type = 'trial'; event(eventCount).sample = (eventCount-1)*hdr.nSamples + 1; event(eventCount).offset = -hdr.nSamplesPre; event(eventCount).duration = hdr.nSamples; event(eventCount).value = cnames{cel}; end end case 'egi_egia' if isempty(hdr) hdr = ft_read_header(filename); end fhdr = hdr.orig.fhdr; chdr = hdr.orig.chdr; ename = hdr.orig.ename; cnames = hdr.orig.cnames; fcom = hdr.orig.fcom; ftext = hdr.orig.ftext; eventCount=0; for cel=1:fhdr(18) for subject=1:chdr(cel,2) eventCount=eventCount+1; event(eventCount).type = 'trial'; event(eventCount).sample = (eventCount-1)*hdr.nSamples + 1; event(eventCount).offset = -hdr.nSamplesPre; event(eventCount).duration = hdr.nSamples; event(eventCount).value = ['Sub' sprintf('%03d',subject) cnames{cel}]; end end case 'egi_sbin' if ~exist('segHdr','var') [EventCodes, segHdr, eventData] = read_sbin_events(filename); end if ~exist('header_array','var') [header_array, CateNames, CatLengths, preBaseline] = read_sbin_header(filename); end if isempty(hdr) hdr = ft_read_header(filename,'headerformat','egi_sbin'); end version = header_array(1); unsegmented = ~mod(version, 2); eventCount=0; if unsegmented [evType,sampNum] = find(eventData); for k = 1:length(evType) event(k).sample = sampNum(k); event(k).offset = []; event(k).duration = 0; event(k).type = 'trigger'; event(k).value = char(EventCodes(evType(k),:)); end else for theEvent=1:size(eventData,1) for segment=1:hdr.nTrials if any(eventData(theEvent,((segment-1)*hdr.nSamples +1):segment*hdr.nSamples)) eventCount=eventCount+1; event(eventCount).sample = min(find(eventData(theEvent,((segment-1)*hdr.nSamples +1):segment*hdr.nSamples))) +(segment-1)*hdr.nSamples; event(eventCount).offset = -hdr.nSamplesPre; event(eventCount).duration = length(find(eventData(theEvent,((segment-1)*hdr.nSamples +1):segment*hdr.nSamples )>0))-1; event(eventCount).type = 'trigger'; event(eventCount).value = char(EventCodes(theEvent,:)); end end end end if ~unsegmented for segment=1:hdr.nTrials % cell information eventCount=eventCount+1; event(eventCount).type = 'trial'; event(eventCount).sample = (segment-1)*hdr.nSamples + 1; event(eventCount).offset = -hdr.nSamplesPre; event(eventCount).duration = hdr.nSamples; event(eventCount).value = char([CateNames{segHdr(segment,1)}(1:CatLengths(segHdr(segment,1)))]); end end; case {'egi_mff_v1' 'egi_mff'} % this is currently the default % The following represents the code that was written by Ingrid, Robert % and Giovanni to get started with the EGI mff dataset format. It might % not support all details of the file formats. % An alternative implementation has been provided by EGI, this is % released as fieldtrip/external/egi_mff and referred further down in % this function as 'egi_mff_v2'. if isempty(hdr) % use the corresponding code to read the header hdr = ft_read_header(filename, 'headerformat', eventformat); end if ~usejava('jvm') error('the xml2struct requires MATLAB to be running with the Java virtual machine (JVM)'); % an alternative implementation which does not require the JVM but runs much slower is % available from http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0 end % get event info from xml files warning('off', 'MATLAB:REGEXP:deprecated') % due to some small code xml2struct xmlfiles = dir( fullfile(filename, '*.xml')); disp('reading xml files to obtain event info... This might take a while if many events/triggers are present') if isempty(xmlfiles) xml=struct([]); else xml=[]; end; for i = 1:numel(xmlfiles) if strcmpi(xmlfiles(i).name(1:6), 'Events') fieldname = xmlfiles(i).name(1:end-4); filename_xml = fullfile(filename, xmlfiles(i).name); xml.(fieldname) = xml2struct(filename_xml); end end warning('on', 'MATLAB:REGEXP:deprecated') % construct info needed for FieldTrip Event eventNames = fieldnames(xml); begTime = hdr.orig.xml.info.recordTime; begTime(11) = ' '; begTime(end-5:end) = []; begSDV = datenum(begTime); % find out if there are epochs in this dataset if isfield(hdr.orig.xml,'epoch') && length(hdr.orig.xml.epoch) > 1 Msamp2offset = zeros(2,size(hdr.orig.epochdef,1),1+max(hdr.orig.epochdef(:,2)-hdr.orig.epochdef(:,1))); Msamp2offset(:) = NaN; for iEpoch = 1:size(hdr.orig.epochdef,1) nSampEpoch = hdr.orig.epochdef(iEpoch,2)-hdr.orig.epochdef(iEpoch,1)+1; Msamp2offset(1,iEpoch,1:nSampEpoch) = hdr.orig.epochdef(iEpoch,1):hdr.orig.epochdef(iEpoch,2); %sample number in samples Msamp2offset(2,iEpoch,1:nSampEpoch) = hdr.orig.epochdef(iEpoch,3):hdr.orig.epochdef(iEpoch,3)+nSampEpoch-1; %offset in samples end end % construct event according to FieldTrip rules eventCount = 0; for iXml = 1:length(eventNames) for iEvent = 1:length(xml.(eventNames{iXml})) eventTime = xml.(eventNames{iXml})(iEvent).event.beginTime; eventTime(11) = ' '; eventTime(end-5:end) = []; if strcmp('-',eventTime(21)) % event out of range (before recording started): do nothing. else eventSDV = datenum(eventTime); eventOffset = round((eventSDV - begSDV)*24*60*60*hdr.Fs); %in samples, relative to start of recording if eventOffset < 0 % event out of range (before recording started): do nothing else eventCount = eventCount+1; % calculate eventSample, relative to start of epoch if isfield(hdr.orig.xml,'epoch') && length(hdr.orig.xml.epoch) > 1 for iEpoch = 1:size(hdr.orig.epochdef,1) [dum,dum2] = intersect(squeeze(Msamp2offset(2,iEpoch,:)), eventOffset); if ~isempty(dum2) EpochNum = iEpoch; SampIndex = dum2; end end eventSample = Msamp2offset(1,EpochNum,SampIndex); else eventSample = eventOffset+1; end event(eventCount).type = eventNames{iXml}(8:end); event(eventCount).sample = eventSample; event(eventCount).offset = 0; event(eventCount).duration = str2double(xml.(eventNames{iXml})(iEvent).event.duration)./1000000000*hdr.Fs; event(eventCount).value = xml.(eventNames{iXml})(iEvent).event.code; end %if that takes care of non "-" events that are still out of range end %if that takes care of "-" events, which are out of range end %iEvent end case 'egi_mff_v2' % ensure that the EGI toolbox is on the path ft_hastoolbox('egi_mff', 1); if isunix && filename(1)~=filesep % add the full path to the dataset directory filename = fullfile(pwd, filename); else % FIXME I don't know how this is supposed to work on Windows computers % with the drive letter in front of the path end % pass the header along to speed it up, it will be read on the fly in case it is empty event = read_mff_event(filename, hdr); % clean up the fields in the event structure fn = fieldnames(event); fn = setdiff(fn, {'type', 'sample', 'value', 'offset', 'duration', 'timestamp'}); for i=1:length(fn) event = rmfield(event, fn{i}); end case 'eyelink_asc' if isempty(hdr) hdr = ft_read_header(filename); end if isfield(hdr.orig, 'input') % this is inefficient, since it keeps the complete data in memory % but it does speed up subsequent read operations without the user % having to care about it asc = hdr.orig; else asc = read_eyelink_asc(filename); end timestamp = [asc.input(:).timestamp]; value = [asc.input(:).value]; % note that in this dataformat the first input trigger can be before % the start of the data acquisition for i=1:length(timestamp) event(end+1).type = 'INPUT'; event(end ).sample = (timestamp(i)-hdr.FirstTimeStamp)/hdr.TimeStampPerSample + 1; event(end ).timestamp = timestamp(i); event(end ).value = value(i); event(end ).duration = 1; event(end ).offset = 0; end case 'fcdc_buffer' % read from a networked buffer for realtime analysis [host, port] = filetype_check_uri(filename); % SK: the following was intended to speed up, but does not work % the buffer server will try to return exact indices, even % if the intend here is to filter based on a maximum range. % We could change the definition of GET_EVT to comply % with filtering, but that might break other existing code. %if isempty(flt_minnumber) && isempty(flt_maxnumber) % evtsel = []; %else % evtsel = [0 2^32-1]; % if ~isempty(flt_minnumber) % evtsel(1) = flt_minnumber-1; % end % if ~isempty(flt_maxnumber) % evtsel(2) = flt_maxnumber-1; % end %end if blocking && isempty(flt_minnumber) && isempty(flt_maxnumber) warning('disabling blocking because no selection was specified'); blocking = false; end if blocking nsamples = -1; % disable waiting for samples if isempty(flt_minnumber) nevents = flt_maxnumber; elseif isempty(flt_maxnumber) nevents = flt_minnumber; else nevents = max(flt_minnumber, flt_maxnumber); end available = buffer_wait_dat([nsamples nevents timeout*1000], host, port); if available.nevents<nevents error('buffer timed out while waiting for %d events', nevents); end end try event = buffer('get_evt', [], host, port); catch if strfind(lasterr, 'the buffer returned an error') % this happens if the buffer contains no events % which in itself is not a problem and should not result in an error event = []; else rethrow(lasterr); end end case 'fcdc_buffer_offline' [path, file, ext] = fileparts(filename); if isempty(hdr) headerfile = fullfile(path, 'header'); hdr = read_buffer_offline_header(headerfile); end eventfile = fullfile(path, 'events'); event = read_buffer_offline_events(eventfile, hdr); case 'fcdc_matbin' % this is multiplexed data in a *.bin file, accompanied by a matlab file containing the header and event [path, file, ext] = fileparts(filename); filename = fullfile(path, [file '.mat']); % read the events from the Matlab file tmp = load(filename, 'event'); event = tmp.event; case 'fcdc_fifo' fifo = filetype_check_uri(filename); if ~exist(fifo,'file') warning('the FIFO %s does not exist; attempting to create it', fifo); fid = fopen(fifo, 'r'); system(sprintf('mkfifo -m 0666 %s',fifo)); end msg = fread(fid, inf, 'uint8'); fclose(fid); try event = mxDeserialize(uint8(msg)); catch warning(lasterr); end case 'fcdc_tcp' % requires tcp/udp/ip-toolbox ft_hastoolbox('TCP_UDP_IP', 1); [host, port] = filetype_check_uri(filename); if isempty(sock) sock=pnet('tcpsocket',port); end con = pnet(sock, 'tcplisten'); if con~=-1 try pnet(con,'setreadtimeout',10); % read packet msg=pnet(con,'readline'); %,1000,'uint8','network'); if ~isempty(msg) event = mxDeserialize(uint8(str2num(msg))); end % catch % warning(lasterr); end pnet(con,'close'); end con = []; case 'fcdc_udp' % requires tcp/udp/ip-toolbox ft_hastoolbox('TCP_UDP_IP', 1); [host, port] = filetype_check_uri(filename); try % read from localhost udp=pnet('udpsocket',port); % Wait/Read udp packet to read buffer len=pnet(udp,'readpacket'); if len>0, % if packet larger then 1 byte then read maximum of 1000 doubles in network byte order msg=pnet(udp,'read',1000,'uint8'); if ~isempty(msg) event = mxDeserialize(uint8(msg)); end end catch warning(lasterr); end % On break or error close connection pnet(udp,'close'); case 'fcdc_serial' % this code is moved to a seperate file event = read_serial_event(filename); case 'fcdc_mysql' % check that the required low-level toolbox is available ft_hastoolbox('mysql', 1); % read from a MySQL server listening somewhere else on the network db_open(filename); if db_blob event = db_select_blob('fieldtrip.event', 'msg'); else event = db_select('fieldtrip.event', {'type', 'value', 'sample', 'offset', 'duration'}); end case 'gtec_mat' if isempty(hdr) hdr = ft_read_header(filename); end if isempty(trigindx) % these are probably trigger channels trigindx = match_str(hdr.label, {'Display', 'Target'}); end % use a helper function to read the trigger channels and detect the flanks % pass all the other users options to the read_trigger function event = read_trigger(filename, 'header', hdr, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trigindx, 'dataformat', dataformat, 'detectflank', detectflank, 'trigshift', trigshift); case {'itab_raw' 'itab_mhd'} if isempty(hdr) hdr = ft_read_header(filename); end for i=1:hdr.orig.nsmpl event(end+1).type = 'trigger'; event(end ).value = hdr.orig.smpl(i).type; event(end ).sample = hdr.orig.smpl(i).start + 1; event(end ).duration = hdr.orig.smpl(i).ntptot; event(end ).offset = -hdr.orig.smpl(i).ntppre; % number of samples prior to the trigger end if isempty(event) warning('no events found in the event table, reading the trigger channel(s)'); trigsel = find(ft_chantype(hdr, 'flag')); trigger = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trigsel, 'detectflank', detectflank, 'trigshift', trigshift); event = appendevent(event, trigger); end case 'matlab' % read the events from a normal Matlab file tmp = load(filename, 'event'); event = tmp.event; case 'micromed_trc' if isempty(hdr) hdr = ft_read_header(filename); end if isfield(hdr, 'orig') && isfield(hdr.orig, 'Trigger_Area') && isfield(hdr.orig, 'Tigger_Area_Length') if ~isempty(trigindx) trigger = read_trigger(filename, 'header', hdr, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', trigindx, 'detectflank', detectflank, 'trigshift', trigshift,'dataformat', 'micromed_trc'); event = appendevent(event, trigger); else % routine that reads analog triggers in case no index is specified event = read_micromed_event(filename); end else error('Not a correct event format') end case {'mpi_ds', 'mpi_dap'} if isempty(hdr) hdr = ft_read_header(filename); end % determine the DAP files that compromise this dataset if isdir(filename) ls = dir(filename); dapfile = {}; for i=1:length(ls) if ~isempty(regexp(ls(i).name, '.dap$', 'once' )) dapfile{end+1} = fullfile(filename, ls(i).name); end end dapfile = sort(dapfile); elseif iscell(filename) dapfile = filename; else dapfile = {filename}; end % assume that each DAP file is accompanied by a dat file % read the trigger values from the separate dat files trg = []; for i=1:length(dapfile) datfile = [dapfile{i}(1:(end-4)) '.dat']; trg = cat(1, trg, textread(datfile, '', 'headerlines', 1)); end % construct a event structure, one 'trialcode' event per trial for i=1:length(trg) event(i).type = 'trialcode'; % string event(i).sample = (i-1)*hdr.nSamples + 1; % expressed in samples, first sample of file is 1 event(i).value = trg(i); % number or string event(i).offset = 0; % expressed in samples event(i).duration = hdr.nSamples; % expressed in samples end case {'babysquid_fif' 'babysquid_eve'} if strcmp(eventformat, 'babysquid_fif') % ensure that we are reading the *.eve file [p, f, x] = fileparts(filename); filename = fullfile(p, [f '.eve']); end % see http://bugzilla.fcdonders.nl/show_bug.cgi?id=1914 for details [smp, tim, val, typ] = read_babysquid_eve(filename); if ~isempty(smp) smp = num2cell(smp); val = num2cell(val); typ = cellfun(@num2str, num2cell(typ), 'UniformOutput', false); offset = num2cell(zeros(size(smp))); % convert to a structure array event = struct('type', typ, 'value', val, 'sample', smp, 'offset', offset); else event = []; end case {'neuromag_fif' 'neuromag_mne' 'neuromag_mex'} if strcmp(eventformat, 'neuromag_fif') % the default is to use the MNE reader for fif files eventformat = 'neuromag_mne'; end if strcmp(eventformat, 'neuromag_mex') % check that the required low-level toolbox is available ft_hastoolbox('meg-pd', 1); if isempty(headerformat), headerformat = eventformat; end if isempty(dataformat), dataformat = eventformat; end elseif strcmp(eventformat, 'neuromag_mne') % check that the required low-level toolbox is available ft_hastoolbox('mne', 1); if isempty(headerformat), headerformat = eventformat; end if isempty(dataformat), dataformat = eventformat; end end if isempty(hdr) hdr = ft_read_header(filename, 'headerformat', headerformat); end % note below we've had to include some chunks of code that are only % called if the file is an averaged file, or if the file is continuous. % These are defined in hdr by read_header for neuromag_mne, but do not % exist for neuromag_fif, hence we run the code anyway if the fields do % not exist (this is what happened previously anyway). if strcmp(eventformat, 'neuromag_mex') iscontinuous = 1; isaverage = 0; isepoched = 0; elseif strcmp(eventformat, 'neuromag_mne') iscontinuous = hdr.orig.iscontinuous; isaverage = hdr.orig.isaverage; isepoched = hdr.orig.isepoched; end if iscontinuous analogindx = find(strcmp(ft_chantype(hdr), 'analog trigger')); binaryindx = find(strcmp(ft_chantype(hdr), 'digital trigger')); if isempty(binaryindx)&&isempty(analogindx) % included in case of problems with older systems and MNE reader: % use a predefined set of channel names binary = {'STI 014', 'STI 015', 'STI 016'}; binaryindx = match_str(hdr.label, binary); end if ~isempty(binaryindx) trigger = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', binaryindx, 'detectflank', detectflank, 'trigshift', trigshift, 'fixneuromag', 0); event = appendevent(event, trigger); end if ~isempty(analogindx) % add the triggers to the event structure based on trigger channels with the name "STI xxx" % there are some issues with noise on these analog trigger % channels, on older systems only % read the trigger channel and do flank detection trigger = read_trigger(filename, 'header', hdr, 'dataformat', dataformat, 'begsample', flt_minsample, 'endsample', flt_maxsample, 'chanindx', analogindx, 'detectflank', detectflank, 'trigshift', trigshift, 'fixneuromag', 1); event = appendevent(event, trigger); end elseif isaverage % the length of each average can be variable nsamples = zeros(1, length(hdr.orig.evoked)); for i=1:length(hdr.orig.evoked) nsamples(i) = size(hdr.orig.evoked(i).epochs, 2); end begsample = cumsum([1 nsamples]); for i=1:length(hdr.orig.evoked) event(end+1).type = 'average'; event(end ).sample = begsample(i); event(end ).value = hdr.orig.evoked(i).comment; % this is a descriptive string event(end ).offset = hdr.orig.evoked(i).first; event(end ).duration = hdr.orig.evoked(i).last - hdr.orig.evoked(i).first + 1; end elseif isepoched error('Support for epoched *.fif data is not yet implemented.') end case {'neuralynx_ttl' 'neuralynx_bin' 'neuralynx_dma' 'neuralynx_sdma'} if isempty(hdr) hdr = ft_read_header(filename); end % specify the range to search for triggers, default is the complete file if ~isempty(flt_minsample) begsample = flt_minsample; else begsample = 1; end if ~isempty(flt_maxsample) endsample = flt_maxsample; else endsample = hdr.nSamples*hdr.nTrials; end if strcmp(eventformat, 'neuralynx_dma') % read the Parallel_in channel from the DMA log file ttl = read_neuralynx_dma(filename, begsample, endsample, 'ttl'); elseif strcmp(eventformat, 'neuralynx_sdma') % determine the seperate files with the trigger and timestamp information [p, f, x] = fileparts(filename); ttlfile = fullfile(filename, [f '.ttl.bin']); tslfile = fullfile(filename, [f '.tsl.bin']); tshfile = fullfile(filename, [f '.tsh.bin']); if ~exist(ttlfile) && ~exist(tslfile) && ~exist(tshfile) % perhaps it is an old splitted dma dataset? ttlfile = fullfile(filename, [f '.ttl']); tslfile = fullfile(filename, [f '.tsl']); tshfile = fullfile(filename, [f '.tsh']); end if ~exist(ttlfile) && ~exist(tslfile) && ~exist(tshfile) % these files must be present in a splitted dma dataset error('could not locate the individual ttl, tsl and tsh files'); end % read the trigger values from the seperate file ttl = read_neuralynx_bin(ttlfile, begsample, endsample); elseif strcmp(eventformat, 'neuralynx_ttl') % determine the optional files with timestamp information tslfile = [filename(1:(end-4)) '.tsl']; tshfile = [filename(1:(end-4)) '.tsh']; % read the triggers from a seperate *.ttl file ttl = read_neuralynx_ttl(filename, begsample, endsample); elseif strcmp(eventformat, 'neuralynx_bin') % determine the optional files with timestamp information tslfile = [filename(1:(end-8)) '.tsl.bin']; tshfile = [filename(1:(end-8)) '.tsh.bin']; % read the triggers from a seperate *.ttl.bin file ttl = read_neuralynx_bin(filename, begsample, endsample); end ttl = int32(ttl / (2^16)); % parallel port provides int32, but word resolution is int16. Shift the bits and typecast to signed integer. d1 = (diff(ttl)~=0); % determine the flanks, which can be multiple samples long (this looses one sample) d2 = (diff(d1)==1); % determine the onset of the flanks (this looses one sample) smp = find(d2)+2; % find the onset of the flanks, add the two samples again val = ttl(smp+5); % look some samples further for the trigger value, to avoid the flank clear d1 d2 ttl ind = find(val~=0); % look for triggers tith a non-zero value, this avoids downgoing flanks going to zero smp = smp(ind); % discard triggers with a value of zero val = val(ind); % discard triggers with a value of zero if ~isempty(smp) % try reading the timestamps if strcmp(eventformat, 'neuralynx_dma') tsl = read_neuralynx_dma(filename, 1, max(smp), 'tsl'); tsl = typecast(tsl(smp), 'uint32'); tsh = read_neuralynx_dma(filename, 1, max(smp), 'tsh'); tsh = typecast(tsh(smp), 'uint32'); ts = timestamp_neuralynx(tsl, tsh); elseif exist(tslfile) && exist(tshfile) tsl = read_neuralynx_bin(tslfile, 1, max(smp)); tsl = tsl(smp); tsh = read_neuralynx_bin(tshfile, 1, max(smp)); tsh = tsh(smp); ts = timestamp_neuralynx(tsl, tsh); else ts = []; end % reformat the values as cell array, since the struct function can work with those type = repmat({'trigger'},size(smp)); value = num2cell(val); sample = num2cell(smp + begsample - 1); duration = repmat({[]},size(smp)); offset = repmat({[]},size(smp)); if ~isempty(ts) timestamp = reshape(num2cell(ts),size(smp)); else timestamp = repmat({[]},size(smp)); end % convert it into a structure array, this can be done in one go event = struct('type', type, 'value', value, 'sample', sample, 'timestamp', timestamp, 'offset', offset, 'duration', duration); clear type value sample timestamp offset duration end if (strcmp(eventformat, 'neuralynx_bin') || strcmp(eventformat, 'neuralynx_ttl')) && isfield(hdr, 'FirstTimeStamp') % the header was obtained from an external dataset which could be at a different sampling rate % use the timestamps to redetermine the sample numbers fprintf('using sample number of the downsampled file to reposition the TTL events\n'); % convert the timestamps into samples, keeping in mind the FirstTimeStamp and TimeStampPerSample smp = round(double(ts - uint64(hdr.FirstTimeStamp))./hdr.TimeStampPerSample + 1); for i=1:length(event) % update the sample number event(i).sample = smp(i); end end case 'neuralynx_ds' % read the header of the dataset if isempty(hdr) hdr = ft_read_header(filename); end % the event file is contained in the dataset directory if exist(fullfile(filename, 'Events.Nev')) filename = fullfile(filename, 'Events.Nev'); elseif exist(fullfile(filename, 'Events.nev')) filename = fullfile(filename, 'Events.nev'); elseif exist(fullfile(filename, 'events.Nev')) filename = fullfile(filename, 'events.Nev'); elseif exist(fullfile(filename, 'events.nev')) filename = fullfile(filename, 'events.nev'); end % read the events, apply filter is applicable nev = read_neuralynx_nev(filename, 'type', flt_type, 'value', flt_value, 'mintimestamp', flt_mintimestamp, 'maxtimestamp', flt_maxtimestamp, 'minnumber', flt_minnumber, 'maxnumber', flt_maxnumber); % the following code should only be executed if there are events, % otherwise there will be an error subtracting an uint64 from an [] if ~isempty(nev) % now get the values as cell array, since the struct function can work with those value = {nev.TTLValue}; timestamp = {nev.TimeStamp}; number = {nev.EventNumber}; type = repmat({'trigger'},size(value)); duration = repmat({[]},size(value)); offset = repmat({[]},size(value)); sample = num2cell(round(double(cell2mat(timestamp) - hdr.FirstTimeStamp)/hdr.TimeStampPerSample + 1)); % convert it into a structure array event = struct('type', type, 'value', value, 'sample', sample, 'timestamp', timestamp, 'duration', duration, 'offset', offset, 'number', number); end case 'neuralynx_cds' % this is a combined Neuralynx dataset with seperate subdirectories for the LFP, MUA and spike channels dirlist = dir(filename); %haslfp = any(filetype_check_extension({dirlist.name}, 'lfp')); %hasmua = any(filetype_check_extension({dirlist.name}, 'mua')); %hasspike = any(filetype_check_extension({dirlist.name}, 'spike')); %hastsl = any(filetype_check_extension({dirlist.name}, 'tsl')); % seperate file with original TimeStampLow %hastsh = any(filetype_check_extension({dirlist.name}, 'tsh')); % seperate file with original TimeStampHi hasttl = any(filetype_check_extension({dirlist.name}, 'ttl')); % seperate file with original Parallel_in hasnev = any(filetype_check_extension({dirlist.name}, 'nev')); % original Events.Nev file hasmat = 0; if hasttl eventfile = fullfile(filename, dirlist(find(filetype_check_extension({dirlist.name}, 'ttl'))).name); % read the header from the combined dataset if isempty(hdr) hdr = ft_read_header(filename); end % read the events from the *.ttl file event = ft_read_event(eventfile); % convert the sample numbers from the dma or ttl file to the downsampled dataset % assume that the *.ttl file is sampled at 32556Hz and is aligned with the rest of the data for i=1:length(event) event(i).sample = round((event(i).sample-1) * hdr.Fs/32556 + 1); end % elseif hasnev % FIXME, do something here % elseif hasmat % FIXME, do something here else error('no event file found'); end % The sample number is missingin the code below, since it is not available % without looking in the continuously sampled data files. Therefore % sorting the events (later in this function) based on the sample number % fails and no events can be returned. % % case 'neuralynx_nev' % [nev] = read_neuralynx_nev(filename); % % select only the events with a TTL value % ttl = [nev.TTLValue]; % sel = find(ttl~=0); % % now get the values as cell array, since teh struct function can work with those % value = {nev(sel).TTLValue}; % timestamp = {nev(sel).TimeStamp}; % event = struct('value', value, 'timestamp', timestamp); % for i=1:length(event) % % assign the other fixed elements % event(i).type = 'trigger'; % event(i).offset = []; % event(i).duration = []; % event(i).sample = []; % end case {'neuroprax_eeg', 'neuroprax_mrk'} tmp = np_readmarker (filename, 0, inf, 'samples'); event = []; for i = 1:numel(tmp.marker) if isempty(tmp.marker{i}) break; end event = [event struct('type', tmp.markernames(i),... 'sample', num2cell(tmp.marker{i}),... 'value', {tmp.markertyp(i)})]; end case 'nexstim_nxe' event = read_nexstim_event(filename); case 'nimh_cortex' if isempty(hdr) hdr = ft_read_header(filename); end cortex = hdr.orig.trial; for i=1:length(cortex) % add one 'trial' event for every trial and add the trigger events event(end+1).type = 'trial'; event(end ).sample = nan; event(end ).duration = nan; event(end ).offset = nan; event(end ).value = i; % use the trial number as value for j=1:length(cortex(i).event) event(end+1).type = 'trigger'; event(end ).sample = nan; event(end ).duration = nan; event(end ).offset = nan; event(end ).value = cortex(i).event(j); end end case 'ns_avg' if isempty(hdr) hdr = ft_read_header(filename); end event(end+1).type = 'average'; event(end ).sample = 1; event(end ).duration = hdr.nSamples; event(end ).offset = -hdr.nSamplesPre; event(end ).value = []; case {'ns_cnt', 'ns_cnt16', 'ns_cnt32'} % read the header, the original header includes the event table if isempty(hdr) hdr = ft_read_header(filename, 'headerformat', eventformat); end % translate the event table into known FieldTrip event types for i=1:numel(hdr.orig.event) event(end+1).type = 'trigger'; event(end ).sample = hdr.orig.event(i).offset + 1; % +1 was in EEGLAB pop_loadcnt event(end ).value = hdr.orig.event(i).stimtype; event(end ).offset = 0; event(end ).duration = 0; % the code above assumes that all events are stimulus triggers % howevere, there are also interesting events possible, such as responses if hdr.orig.event(i).stimtype~=0 event(end+1).type = 'stimtype'; event(end ).sample = hdr.orig.event(i).offset + 1; % +1 was in EEGLAB pop_loadcnt event(end ).value = hdr.orig.event(i).stimtype; event(end ).offset = 0; event(end ).duration = 0; elseif hdr.orig.event(i).keypad_accept~=0 event(end+1).type = 'keypad_accept'; event(end ).sample = hdr.orig.event(i).offset + 1; % +1 was in EEGLAB pop_loadcnt event(end ).value = hdr.orig.event(i).keypad_accept; event(end ).offset = 0; event(end ).duration = 0; end end case 'ns_eeg' if isempty(hdr) hdr = ft_read_header(filename); end for i=1:hdr.nTrials % the *.eeg file has a fixed trigger value for each trial % furthermore each trial has additional fields like accept, correct, response and rt tmp = read_ns_eeg(filename, i); % create an event with the trigger value event(end+1).type = 'trial'; event(end ).sample = (i-1)*hdr.nSamples + 1; event(end ).value = tmp.sweep.type; % trigger value event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; % create an event with the boolean accept/reject code event(end+1).type = 'accept'; event(end ).sample = (i-1)*hdr.nSamples + 1; event(end ).value = tmp.sweep.accept; % boolean value indicating accept/reject event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; % create an event with the boolean accept/reject code event(end+1).type = 'correct'; event(end ).sample = (i-1)*hdr.nSamples + 1; event(end ).value = tmp.sweep.correct; % boolean value event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; % create an event with the boolean accept/reject code event(end+1).type = 'response'; event(end ).sample = (i-1)*hdr.nSamples + 1; event(end ).value = tmp.sweep.response; % probably a boolean value event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; % create an event with the boolean accept/reject code event(end+1).type = 'rt'; event(end ).sample = (i-1)*hdr.nSamples + 1; event(end ).value = tmp.sweep.rt; % time in seconds event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; end case 'plexon_nex' event = read_nex_event(filename); case {'yokogawa_ave', 'yokogawa_con', 'yokogawa_raw'} % check that the required low-level toolbox is available if ~ft_hastoolbox('yokogawa', 0); ft_hastoolbox('yokogawa_meg_reader', 1); end % the user should be able to specify the analog threshold % the user should be able to specify the trigger channels % the user should be able to specify the flank, but the code falls back to 'auto' as default if isempty(detectflank) detectflank = 'auto'; end event = read_yokogawa_event(filename, 'detectflank', detectflank, 'trigindx', trigindx, 'threshold', threshold); case 'nmc_archive_k' event = read_nmc_archive_k_event(filename); case 'netmeg' warning('reading of events for the netmeg format is not yet supported'); event = []; case 'neuroshare' % NOTE: still under development % check that the required neuroshare toolbox is available ft_hastoolbox('neuroshare', 1); tmp = read_neuroshare(filename, 'readevent', 'yes'); for i=1:length(tmp.event.timestamp) event(i).type = tmp.hdr.eventinfo(i).EventType; event(i).value = tmp.event.data(i); event(i).timestamp = tmp.event.timestamp(i); event(i).sample = tmp.event.sample(i); end case 'dataq_wdq' if isempty(hdr) hdr = ft_read_header(filename, 'headerformat', 'dataq_wdq'); end trigger = read_wdq_data(filename, hdr.orig, 'lowbits'); [ix, iy] = find(trigger>1); %it seems as if the value of 1 is meaningless for i=1:numel(ix) event(i).type = num2str(ix(i)); event(i).value = trigger(ix(i),iy(i)); event(i).sample = iy(i); end case 'bucn_nirs' event = read_bucn_nirsevent(filename); otherwise warning('FieldTrip:ft_read_event:unsupported_event_format','unsupported event format (%s)', eventformat); event = []; end if ~isempty(hdr) && hdr.nTrials>1 && (isempty(event) || ~any(strcmp({event.type}, 'trial'))) % the data suggests multiple trials and trial events have not yet been defined % make an event for each trial according to the file header for i=1:hdr.nTrials event(end+1).type = 'trial'; event(end ).sample = (i-1)*hdr.nSamples + 1; event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; event(end ).value = []; end end if ~isempty(event) % make sure that all required elements are present if ~isfield(event, 'type'), error('type field not defined for each event'); end if ~isfield(event, 'sample'), error('sample field not defined for each event'); end if ~isfield(event, 'value'), for i=1:length(event), event(i).value = []; end; end if ~isfield(event, 'offset'), for i=1:length(event), event(i).offset = []; end; end if ~isfield(event, 'duration'), for i=1:length(event), event(i).duration = []; end; end end % make sure that all numeric values are double if ~isempty(event) for i=1:length(event) if isnumeric(event(i).value) event(i).value = double(event(i).value); end event(i).sample = double(event(i).sample); event(i).offset = double(event(i).offset); event(i).duration = double(event(i).duration); end end if ~isempty(event) % sort the events on the sample on which they occur % this has the side effect that events without a sample number are discarded [dum, indx] = sort([event.sample]); event = event(indx); % else % warning('no events found in %s', filename); end % apply the optional filters event = ft_filter_event(event, varargin{:}); if isempty(event) % ensure that it has the correct fields, even if it is empty event = struct('type', {}, 'value', {}, 'sample', {}, 'offset', {}, 'duration', {}); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % poll implementation for backwards compatibility with ft buffer version 1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function available = buffer_wait_dat(selection, host, port) % selection(1) nsamples % selection(2) nevents % selection(3) timeout in msec % check if backwards compatibilty mode is required try % the WAIT_DAT request waits until it has more samples or events selection(1) = selection(1)-1; selection(2) = selection(2)-1; % the following should work for buffer version 2 available = buffer('WAIT_DAT', selection, host, port); catch % the error means that the buffer is version 1, which does not support the WAIT_DAT request % the wait_dat can be implemented by polling the buffer nsamples = selection(1); nevents = selection(2); timeout = selection(3)/1000; % in seconds stopwatch = tic; % results are retrieved in the order written to the buffer orig = buffer('GET_HDR', [], host, port); if timeout > 0 % wait maximal timeout seconds until more than nsamples samples or nevents events have been received while toc(stopwatch)<timeout if nsamples == -1 && nevents == -1, break, end if nsamples ~= -1 && orig.nsamples >= nsamples, break, end if nevents ~= -1 && orig.nevents >= nevents, break, end orig = buffer('GET_HDR', [], host, port); pause(0.001); end else % no reason to wait end available.nsamples = orig.nsamples; available.nevents = orig.nevents; end % try buffer v1 or v2
github
philippboehmsturm/antx-master
ft_read_header.m
.m
antx-master/xspm8/external/fieldtrip/fileio/ft_read_header.m
72,943
utf_8
21175eb77cfb3d7992b08521a46b5a36
function [hdr] = ft_read_header(filename, varargin) % FT_READ_HEADER reads header information from a variety of EEG, MEG and LFP % files and represents the header information in a common data-independent % format. The supported formats are listed below. % % Use as % hdr = ft_read_header(filename, ...) % % Additional options should be specified in key-value pairs and can be % 'headerformat' string % 'fallback' can be empty or 'biosig' (default = []) % 'coordsys' string, 'head' or 'dewar' (default = 'head') % % This returns a header structure with the following elements % hdr.Fs sampling frequency % hdr.nChans number of channels % hdr.nSamples number of samples per trial % hdr.nSamplesPre number of pre-trigger samples in each trial % hdr.nTrials number of trials % hdr.label Nx1 cell-array with the label of each channel % hdr.chantype Nx1 cell-array with the channel type, see FT_CHANTYPE % hdr.chanunit Nx1 cell-array with the physical units, see FT_CHANUNIT % % For continuously recorded data, nSamplesPre=0 and nTrials=1. % % For some data formats that are recorded on animal electrophysiology % systems (e.g. Neuralynx, Plexon), the following optional fields are % returned, which allows for relating the timing of spike and LFP data % hdr.FirstTimeStamp number, 32 bit or 64 bit unsigned integer % hdr.TimeStampPerSample double % % Depending on the file format, additional header information can be % returned in the hdr.orig subfield. % % The following MEG dataformats are supported % CTF - VSM MedTech (*.ds, *.res4, *.meg4) % Neuromag - Elekta (*.fif) % BTi - 4D Neuroimaging (*.m4d, *.pdf, *.xyz) % Yokogawa (*.ave, *.con, *.raw) % NetMEG (*.nc) % ITAB - Chieti (*.mhd) % % The following EEG dataformats are supported % ANT - Advanced Neuro Technology, EEProbe (*.avr, *.eeg, *.cnt) % BCI2000 (*.dat) % Biosemi (*.bdf) % BrainVision (*.eeg, *.seg, *.dat, *.vhdr, *.vmrk) % CED - Cambridge Electronic Design (*.smr) % EGI - Electrical Geodesics, Inc. (*.egis, *.ave, *.gave, *.ses, *.raw, *.sbin, *.mff) % GTec (*.mat) % Generic data formats (*.edf, *.gdf) % Megis/BESA (*.avr, *.swf) % NeuroScan (*.eeg, *.cnt, *.avg) % Nexstim (*.nxe) % % The following spike and LFP dataformats are supported (with some limitations) % Neuralynx (*.ncs, *.nse, *.nts, *.nev, DMA log files) % Plextor (*.nex, *.plx, *.ddt) % CED - Cambridge Electronic Design (*.smr) % MPI - Max Planck Institute (*.dap) % neurosim_spikes % neurosim_signals, Neurosim_ds % % The following NIRS dataformats are supported % BUCN (*.txt) % % See also FT_READ_DATA, FT_READ_EVENT, FT_WRITE_DATA, FT_WRITE_EVENT, % FT_CHANTYPE, FT_CHANUNIT % Copyright (C) 2003-2012 Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_read_header.m 7353 2013-01-18 05:14:26Z josdie $ % TODO channel renaming should be made a general option (see bham_bdf) persistent cacheheader % for caching the full header persistent cachechunk % for caching the res4 chunk when doing realtime analysis on the CTF scanner persistent db_blob % for fcdc_mysql if isempty(db_blob) db_blob = false; end % optionally get the data from the URL and make a temporary local copy filename = fetch_url(filename); % test whether the file or directory exists if ~strcmp(ft_filetype(filename), 'fcdc_buffer') && ~strcmp(ft_filetype(filename), 'ctf_shm') && ~strcmp(ft_filetype(filename), 'fcdc_mysql') && ~exist(filename, 'file') error('FILEIO:InvalidFileName', 'file or directory ''%s'' does not exist', filename); end % get the options retry = ft_getopt(varargin, 'retry', false); % the default is not to retry reading the header headerformat = ft_getopt(varargin, 'headerformat'); coordsys = ft_getopt(varargin, 'coordsys', 'head'); % this is used for CTF, it can be head or dewar if isempty(headerformat) % only do the autodetection if the format was not specified headerformat = ft_filetype(filename); end % The checkUniqueLabels flag is used for the realtime buffer in case % it contains fMRI data. It prevents 1000000 voxel names to be checked % for uniqueness. fMRI users will probably never use channel names % for anything. % The skipInitialCheck flag is used to speed up the read operation from % the realtime buffer in general. if strcmp(headerformat, 'fcdc_buffer') % skip the rest of the initial checks to increase the speed for realtime operation checkUniqueLabels = false; % the cache and fallback option should always be false for realtime processing cache = false; fallback = false; else checkUniqueLabels = true; % the cache and fallback option are according to the user's specification cache = ft_getopt(varargin, 'cache'); fallback = ft_getopt(varargin, 'fallback'); if isempty(cache), if strcmp(headerformat, 'bci2000_dat') || strcmp(headerformat, 'eyelink_asc') || strcmp(headerformat, 'gtec_mat') || strcmp(headerformat, 'biosig') cache = true; else cache = false; end end % ensure that the headerfile and datafile are defined, which are sometimes different than the name of the dataset [filename, headerfile, datafile] = dataset2files(filename, headerformat); if ~strcmp(filename, headerfile) && ~ft_filetype(filename, 'ctf_ds') && ~ft_filetype(filename, 'fcdc_buffer_offline') && ~ft_filetype(filename, 'fcdc_matbin') filename = headerfile; % this function should read the headerfile, not the dataset headerformat = ft_filetype(filename); % update the filetype end end % if skip initial check % start with an empty header hdr = []; % implement the caching in a data-format independent way if cache && exist(headerfile, 'file') && ~isempty(cacheheader) % try to get the header from cache details = dir(headerfile); if isequal(details, cacheheader.details) % the header file has not been updated, fetch it from the cache % fprintf('got header from cache\n'); hdr = rmfield(cacheheader, 'details'); switch ft_filetype(datafile) case {'ctf_ds' 'ctf_meg4' 'ctf_old' 'read_ctf_res4'} % for realtime analysis EOF chasing the res4 does not correctly % estimate the number of samples, so we compute it on the fly sz = 0; files = dir([filename '/*.*meg4']); for j=1:numel(files) sz = sz + files(j).bytes; end hdr.nTrials = floor((sz - 8) / (hdr.nChans*4) / hdr.nSamples); end return; end % if the details correspond end % if cache % the support for head/dewar coordinates is still limited if strcmp(coordsys, 'dewar') && ~any(strcmp(headerformat, {'fcdc_buffer', 'ctf_ds', 'ctf_meg4', 'ctf_res4'})) error('dewar coordinates are sofar only supported for CTF data'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the data with the low-level reading function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% switch headerformat case '4d' orig = read_4d_hdr(datafile); hdr.Fs = orig.header_data.SampleFrequency; hdr.nChans = orig.header_data.TotalChannels; hdr.nSamples = orig.header_data.SlicesPerEpoch; hdr.nSamplesPre = round(orig.header_data.FirstLatency*orig.header_data.SampleFrequency); hdr.nTrials = orig.header_data.TotalEpochs; %hdr.label = {orig.channel_data(:).chan_label}'; hdr.label = orig.Channel; [hdr.grad, elec] = bti2grad(orig); if ~isempty(elec), hdr.elec = elec; end % remember original header details hdr.orig = orig; case {'4d_pdf', '4d_m4d', '4d_xyz'} orig = read_bti_m4d(filename); hdr.Fs = orig.SampleFrequency; hdr.nChans = orig.TotalChannels; hdr.nSamples = orig.SlicesPerEpoch; hdr.nSamplesPre = round(orig.FirstLatency*orig.SampleFrequency); hdr.nTrials = orig.TotalEpochs; hdr.label = orig.ChannelOrder(:); [hdr.grad, elec] = bti2grad(orig); if ~isempty(elec), hdr.elec = elec; end % remember original header details hdr.orig = orig; case 'bci2000_dat' % this requires the load_bcidat mex file to be present on the path ft_hastoolbox('BCI2000', 1); % this is inefficient, since it reads the complete data [signal, states, parameters, total_samples] = load_bcidat(filename); % convert into a FieldTrip-like header hdr = []; hdr.nChans = size(signal,2); hdr.nSamples = total_samples; hdr.nSamplesPre = 0; % it is continuous hdr.nTrials = 1; % it is continuous hdr.Fs = parameters.SamplingRate.NumericValue; % there are some differences in the fields that are present in the % *.dat files, probably due to different BCI2000 versions if isfield(parameters, 'ChannelNames') && isfield(parameters.ChannelNames, 'Value') && ~isempty(parameters.ChannelNames.Value) hdr.label = parameters.ChannelNames.Value; elseif isfield(parameters, 'ChannelNames') && isfield(parameters.ChannelNames, 'Values') && ~isempty(parameters.ChannelNames.Values) hdr.label = parameters.ChannelNames.Values; else % give this warning only once warning_once('creating fake channel names'); for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end end % remember the original header details hdr.orig.parameters = parameters; % also remember the complete data upon request if cache hdr.orig.signal = signal; hdr.orig.states = states; hdr.orig.total_samples = total_samples; end case 'besa_avr' orig = read_besa_avr(filename); hdr.Fs = 1000/orig.di; hdr.nChans = size(orig.data,1); hdr.nSamples = size(orig.data,2); hdr.nSamplesPre = -(hdr.Fs * orig.tsb/1000); % convert from ms to samples hdr.nTrials = 1; if isfield(orig, 'label') && iscell(orig.label) hdr.label = orig.label; elseif isfield(orig, 'label') && ischar(orig.label) hdr.label = tokenize(orig.label, ' '); else % give this warning only once warning_once('creating fake channel names'); for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end end case 'besa_swf' orig = read_besa_swf(filename); hdr.Fs = 1000/orig.di; hdr.nChans = size(orig.data,1); hdr.nSamples = size(orig.data,2); hdr.nSamplesPre = -(hdr.Fs * orig.tsb/1000); % convert from ms to samples hdr.nTrials = 1; hdr.label = orig.label; case {'biosig'} % this requires the biosig toolbox ft_hastoolbox('BIOSIG', 1); hdr = read_biosig_header(filename); case {'gdf'} % this requires the biosig toolbox ft_hastoolbox('BIOSIG', 1); % In the case that the gdf files are written by one of the FieldTrip % realtime applications, such as biosig2ft, the gdf recording can be % split over multiple 1GB files. The sequence of files is then % filename.gdf <- this is the one that should be specified as the filename/dataset % filename_1.gdf % filename_2.gdf % ... [p, f, x] = fileparts(filename); if exist(sprintf('%s_%d%s', fullfile(p, f), 1, x), 'file') % there are multiple files, count the number of additional files (excluding the first one) count = 0; while exist(sprintf('%s_%d%s', fullfile(p, f), count+1, x), 'file') count = count+1; end hdr = read_biosig_header(filename); for i=1:count hdr(i+1) = read_biosig_header(sprintf('%s_%d%s', fullfile(p, f), i, x)); % do some sanity checks if hdr(i+1).nChans~=hdr(1).nChans error('multiple GDF files detected that should be appended, but the channel count is inconsistent'); elseif hdr(i+1).Fs~=hdr(1).Fs error('multiple GDF files detected that should be appended, but the sampling frequency is inconsistent'); elseif ~isequal(hdr(i+1).label, hdr(1).label) error('multiple GDF files detected that should be appended, but the channel names are inconsistent'); end end % for count % combine all headers into one combinedhdr = []; combinedhdr.Fs = hdr(1).Fs; combinedhdr.nChans = hdr(1).nChans; combinedhdr.nSamples = sum([hdr.nSamples].*[hdr.nTrials]); combinedhdr.nSamplesPre = 0; combinedhdr.nTrials = 1; combinedhdr.label = hdr(1).label; combinedhdr.orig = hdr; % include all individual file details hdr = combinedhdr; else % there is only a single file hdr = read_biosig_header(filename); % the GDF format is always continuous hdr.nSamples = hdr.nSamples * hdr.nTrials; hdr.nTrials = 1; hdr.nSamplesPre = 0; end % if single or multiple gdf files case {'biosemi_bdf', 'bham_bdf'} hdr = read_biosemi_bdf(filename); if any(diff(hdr.orig.SampleRate)) error('channels with different sampling rate not supported'); end if ft_filetype(filename, 'bham_bdf') % TODO channel renaming should be made a general option % this is for the Biosemi system used at the University of Birmingham labelold = { 'A1' 'A2' 'A3' 'A4' 'A5' 'A6' 'A7' 'A8' 'A9' 'A10' 'A11' 'A12' 'A13' 'A14' 'A15' 'A16' 'A17' 'A18' 'A19' 'A20' 'A21' 'A22' 'A23' 'A24' 'A25' 'A26' 'A27' 'A28' 'A29' 'A30' 'A31' 'A32' 'B1' 'B2' 'B3' 'B4' 'B5' 'B6' 'B7' 'B8' 'B9' 'B10' 'B11' 'B12' 'B13' 'B14' 'B15' 'B16' 'B17' 'B18' 'B19' 'B20' 'B21' 'B22' 'B23' 'B24' 'B25' 'B26' 'B27' 'B28' 'B29' 'B30' 'B31' 'B32' 'C1' 'C2' 'C3' 'C4' 'C5' 'C6' 'C7' 'C8' 'C9' 'C10' 'C11' 'C12' 'C13' 'C14' 'C15' 'C16' 'C17' 'C18' 'C19' 'C20' 'C21' 'C22' 'C23' 'C24' 'C25' 'C26' 'C27' 'C28' 'C29' 'C30' 'C31' 'C32' 'D1' 'D2' 'D3' 'D4' 'D5' 'D6' 'D7' 'D8' 'D9' 'D10' 'D11' 'D12' 'D13' 'D14' 'D15' 'D16' 'D17' 'D18' 'D19' 'D20' 'D21' 'D22' 'D23' 'D24' 'D25' 'D26' 'D27' 'D28' 'D29' 'D30' 'D31' 'D32' 'EXG1' 'EXG2' 'EXG3' 'EXG4' 'EXG5' 'EXG6' 'EXG7' 'EXG8' 'Status'}; labelnew = { 'P9' 'PPO9h' 'PO7' 'PPO5h' 'PPO3h' 'PO5h' 'POO9h' 'PO9' 'I1' 'OI1h' 'O1' 'POO1' 'PO3h' 'PPO1h' 'PPO2h' 'POz' 'Oz' 'Iz' 'I2' 'OI2h' 'O2' 'POO2' 'PO4h' 'PPO4h' 'PO6h' 'POO10h' 'PO10' 'PO8' 'PPO6h' 'PPO10h' 'P10' 'P8' 'TPP9h' 'TP7' 'TTP7h' 'CP5' 'TPP7h' 'P7' 'P5' 'CPP5h' 'CCP5h' 'CP3' 'P3' 'CPP3h' 'CCP3h' 'CP1' 'P1' 'Pz' 'CPP1h' 'CPz' 'CPP2h' 'P2' 'CPP4h' 'CP2' 'CCP4h' 'CP4' 'P4' 'P6' 'CPP6h' 'CCP6h' 'CP6' 'TPP8h' 'TP8' 'TPP10h' 'T7' 'FTT7h' 'FT7' 'FC5' 'FCC5h' 'C5' 'C3' 'FCC3h' 'FC3' 'FC1' 'C1' 'CCP1h' 'Cz' 'FCC1h' 'FCz' 'FFC1h' 'Fz' 'FFC2h' 'FC2' 'FCC2h' 'CCP2h' 'C2' 'C4' 'FCC4h' 'FC4' 'FC6' 'FCC6h' 'C6' 'TTP8h' 'T8' 'FTT8h' 'FT8' 'FT9' 'FFT9h' 'F7' 'FFT7h' 'FFC5h' 'F5' 'AFF7h' 'AF7' 'AF5h' 'AFF5h' 'F3' 'FFC3h' 'F1' 'AF3h' 'Fp1' 'Fpz' 'Fp2' 'AFz' 'AF4h' 'F2' 'FFC4h' 'F4' 'AFF6h' 'AF6h' 'AF8' 'AFF8h' 'F6' 'FFC6h' 'FFT8h' 'F8' 'FFT10h' 'FT10'}; % rename the channel labels for i=1:length(labelnew) chan = strcmp(labelold(i), hdr.label); hdr.label(chan) = labelnew(chan); end end case {'biosemi_old'} % this uses the openbdf and readbdf functions that were copied from EEGLAB orig = openbdf(filename); if any(orig.Head.SampleRate~=orig.Head.SampleRate(1)) error('channels with different sampling rate not supported'); end hdr.Fs = orig.Head.SampleRate(1); hdr.nChans = orig.Head.NS; hdr.label = cellstr(orig.Head.Label); % it is continuous data, therefore append all records in one trial hdr.nSamples = orig.Head.NRec * orig.Head.Dur * orig.Head.SampleRate(1); hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.orig = orig; % close the file between seperate read operations fclose(orig.Head.FILE.FID); case {'brainvision_vhdr', 'brainvision_seg', 'brainvision_eeg', 'brainvision_dat'} orig = read_brainvision_vhdr(filename); hdr.Fs = orig.Fs; hdr.nChans = orig.NumberOfChannels; hdr.label = orig.label; hdr.nSamples = orig.nSamples; hdr.nSamplesPre = orig.nSamplesPre; hdr.nTrials = orig.nTrials; hdr.orig = orig; case 'ced_son' % check that the required low-level toolbox is available ft_hastoolbox('neuroshare', 1); % use the reading function supplied by Gijs van Elswijk orig = read_ced_son(filename,'readevents','no','readdata','no'); orig = orig.header; % In Spike2, channels can have different sampling rates, units, length % etc. etc. Here, channels need to have to same properties. if length(unique([orig.samplerate]))>1, error('channels with different sampling rates are not supported'); else hdr.Fs = orig(1).samplerate; end; hdr.nChans = length(orig); % nsamples of the channel with least samples hdr.nSamples = min([orig.nsamples]); hdr.nSamplesPre = 0; % only continuous data supported if sum(strcmpi({orig.mode},'continuous')) < hdr.nChans, error('not all channels contain continuous data'); else hdr.nTrials = 1; end; hdr.label = {orig.label}; case 'combined_ds' hdr = read_combined_ds(filename); case {'ctf_ds', 'ctf_meg4', 'ctf_res4'} % check the presence of the required low-level toolbox ft_hastoolbox('ctf', 1); orig = readCTFds(filename); if isempty(orig) % this is to deal with data from the 64 channel system and the error % readCTFds: .meg4 file header=MEG4CPT Valid header options: MEG41CP MEG42CP error('could not read CTF with this implementation, please try again with the ''ctf_old'' file format'); end hdr.Fs = orig.res4.sample_rate; hdr.nChans = orig.res4.no_channels; hdr.nSamples = orig.res4.no_samples; hdr.nSamplesPre = orig.res4.preTrigPts; hdr.nTrials = orig.res4.no_trials; hdr.label = cellstr(orig.res4.chanNames); for i=1:numel(hdr.label) % remove the site-specific numbers from each channel name, e.g. 'MZC01-1706' becomes 'MZC01' hdr.label{i} = strtok(hdr.label{i}, '-'); end % read the balance coefficients, these are used to compute the synthetic gradients coeftype = cellstr(char(orig.res4.scrr(:).coefType)); try [alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig,'NONE', 'T'); orig.BalanceCoefs.none.alphaMEG = alphaMEG; orig.BalanceCoefs.none.MEGlist = MEGlist; orig.BalanceCoefs.none.Refindex = Refindex; catch warning('cannot read balancing coefficients for NONE'); end if any(~cellfun(@isempty,strfind(coeftype, 'G1BR'))) try [alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig,'G1BR', 'T'); orig.BalanceCoefs.G1BR.alphaMEG = alphaMEG; orig.BalanceCoefs.G1BR.MEGlist = MEGlist; orig.BalanceCoefs.G1BR.Refindex = Refindex; catch warning('cannot read balancing coefficients for G1BR'); end end if any(~cellfun(@isempty,strfind(coeftype, 'G2BR'))) try [alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig, 'G2BR', 'T'); orig.BalanceCoefs.G2BR.alphaMEG = alphaMEG; orig.BalanceCoefs.G2BR.MEGlist = MEGlist; orig.BalanceCoefs.G2BR.Refindex = Refindex; catch warning('cannot read balancing coefficients for G2BR'); end end if any(~cellfun(@isempty,strfind(coeftype, 'G3BR'))) try [alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig, 'G3BR', 'T'); orig.BalanceCoefs.G3BR.alphaMEG = alphaMEG; orig.BalanceCoefs.G3BR.MEGlist = MEGlist; orig.BalanceCoefs.G3BR.Refindex = Refindex; catch warning('cannot read balancing coefficients for G3BR'); end end if any(~cellfun(@isempty,strfind(coeftype, 'G3AR'))) try [alphaMEG,MEGlist,Refindex] = getCTFBalanceCoefs(orig, 'G3AR', 'T'); orig.BalanceCoefs.G3AR.alphaMEG = alphaMEG; orig.BalanceCoefs.G3AR.MEGlist = MEGlist; orig.BalanceCoefs.G3AR.Refindex = Refindex; catch % May not want a warning here if these are not commonly used. % Already get a (fprintf) warning from getCTFBalanceCoefs.m % warning('cannot read balancing coefficients for G3AR'); end end % add a gradiometer structure for forward and inverse modelling try hdr.grad = ctf2grad(orig, strcmp(coordsys, 'dewar')); catch % this fails if the res4 file is not correctly closed, e.g. during realtime processing tmp = lasterror; disp(tmp.message); warning('could not construct gradiometer definition from the header'); end % for realtime analysis EOF chasing the res4 does not correctly % estimate the number of samples, so we compute it on the fly from the % meg4 file sizes. sz = 0; files = dir([filename '/*.*meg4']); for j=1:numel(files) sz = sz + files(j).bytes; end hdr.nTrials = floor((sz - 8) / (hdr.nChans*4) / hdr.nSamples); % add the original header details hdr.orig = orig; case {'ctf_old', 'read_ctf_res4'} % read it using the open-source matlab code that originates from CTF and that was modified by the FCDC orig = read_ctf_res4(headerfile); hdr.Fs = orig.Fs; hdr.nChans = orig.nChans; hdr.nSamples = orig.nSamples; hdr.nSamplesPre = orig.nSamplesPre; hdr.nTrials = orig.nTrials; hdr.label = orig.label; % add a gradiometer structure for forward and inverse modelling try hdr.grad = ctf2grad(orig); catch % this fails if the res4 file is not correctly closed, e.g. during realtime processing tmp = lasterror; disp(tmp.message); warning('could not construct gradiometer definition from the header'); end % add the original header details hdr.orig = orig; case 'ctf_read_res4' % check that the required low-level toolbos ix available ft_hastoolbox('eegsf', 1); % read it using the CTF importer from the NIH and Daren Weber orig = ctf_read_res4(fileparts(headerfile), 0); % convert the header into a structure that FieldTrip understands hdr = []; hdr.Fs = orig.setup.sample_rate; hdr.nChans = length(orig.sensor.info); hdr.nSamples = orig.setup.number_samples; hdr.nSamplesPre = orig.setup.pretrigger_samples; hdr.nTrials = orig.setup.number_trials; for i=1:length(orig.sensor.info) hdr.label{i} = orig.sensor.info(i).label; end hdr.label = hdr.label(:); % add a gradiometer structure for forward and inverse modelling try hdr.grad = ctf2grad(orig); catch % this fails if the res4 file is not correctly closed, e.g. during realtime processing tmp = lasterror; disp(tmp.message); warning('could not construct gradiometer definition from the header'); end % add the original header details hdr.orig = orig; case 'ctf_shm' % read the header information from shared memory hdr = read_shm_header(filename); case 'dataq_wdq' orig = read_wdq_header(filename); hdr = []; hdr.Fs = orig.fsample; hdr.nChans = orig.nchan; hdr.nSamples = orig.nbytesdat/(2*hdr.nChans); hdr.nSamplesPre = 0; hdr.nTrials = 1; for k = 1:hdr.nChans if isfield(orig.chanhdr(k), 'annot') && ~isempty(orig.chanhdr(k).annot) hdr.label{k,1} = orig.chanhdr(k).annot; else hdr.label{k,1} = orig.chanhdr(k).label; end end % add the original header details hdr.orig = orig; case {'deymed_ini' 'deymed_dat'} % the header is stored in a *.ini file orig = read_deymed_ini(headerfile); hdr = []; hdr.Fs = orig.Fs; hdr.nChans = orig.nChans; hdr.nSamples = orig.nSamples; hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.label = orig.label(:); hdr.orig = orig; % remember the original details case 'edf' % this reader is largely similar to the bdf reader hdr = read_edf(filename); case 'eep_avr' % check that the required low-level toolbox is available ft_hastoolbox('eeprobe', 1); % read the whole average and keep only header info (it is a bit silly, but the easiest to do here) hdr = read_eep_avr(filename); hdr.Fs = hdr.rate; hdr.nChans = size(hdr.data,1); hdr.nSamples = size(hdr.data,2); hdr.nSamplesPre = hdr.xmin*hdr.rate/1000; hdr.nTrials = 1; % it can always be interpreted as continuous data % remove the data and variance if present hdr = rmfield(hdr, 'data'); try, hdr = rmfield(hdr, 'variance'); end case 'eeglab_set' hdr = read_eeglabheader(filename); case 'eeglab_erp' hdr = read_erplabheader(filename); case 'eyelink_asc' asc = read_eyelink_asc(filename); hdr.nChans = size(asc.dat,1); hdr.nSamples = size(asc.dat,2); hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.FirstTimeStamp = asc.dat(1,1); hdr.TimeStampPerSample = mean(diff(asc.dat(1,:))); hdr.Fs = 1000/hdr.TimeStampPerSample; % these timestamps are in miliseconds % give this warning only once warning_once('creating fake channel names'); for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end % remember the original header details hdr.orig.header = asc.header; % remember all header and data details upon request if cache hdr.orig = asc; end case 'spmeeg_mat' hdr = read_spmeeg_header(filename); case 'ced_spike6mat' hdr = read_spike6mat_header(filename); case 'eep_cnt' % check that the required low-level toolbox is available ft_hastoolbox('eeprobe', 1); % read the first sample from the continous data, which will also return the header hdr = read_eep_cnt(filename, 1, 1); hdr.Fs = hdr.rate; hdr.nSamples = hdr.nsample; hdr.nSamplesPre = 0; hdr.nChans = hdr.nchan; hdr.nTrials = 1; % it can always be interpreted as continuous data case 'egi_egia' [fhdr,chdr,ename,cnames,fcom,ftext] = read_egis_header(filename); [p, f, x] = fileparts(filename); if any(chdr(:,4)-chdr(1,4)) error('Sample rate not the same for all cells.'); end; hdr.Fs = chdr(1,4); %making assumption that sample rate is same for all cells hdr.nChans = fhdr(19); for i = 1:hdr.nChans % this should be consistent with ft_senslabel hdr.label{i,1} = ['E' num2str(i)]; end; %since NetStation does not properly set the fhdr(11) field, use the number of subjects from the chdr instead hdr.nTrials = chdr(1,2)*fhdr(18); %number of trials is numSubjects * numCells hdr.nSamplesPre = ceil(fhdr(14)/(1000/hdr.Fs)); if any(chdr(:,3)-chdr(1,3)) error('Number of samples not the same for all cells.'); end; hdr.nSamples = chdr(1,3); %making assumption that number of samples is same for all cells % remember the original header details hdr.orig.fhdr = fhdr; hdr.orig.chdr = chdr; hdr.orig.ename = ename; hdr.orig.cnames = cnames; hdr.orig.fcom = fcom; hdr.orig.ftext = ftext; case 'egi_egis' [fhdr,chdr,ename,cnames,fcom,ftext] = read_egis_header(filename); [p, f, x] = fileparts(filename); if any(chdr(:,4)-chdr(1,4)) error('Sample rate not the same for all cells.'); end; hdr.Fs = chdr(1,4); %making assumption that sample rate is same for all cells hdr.nChans = fhdr(19); for i = 1:hdr.nChans % this should be consistent with ft_senslabel hdr.label{i,1} = ['E' num2str(i)]; end; hdr.nTrials = sum(chdr(:,2)); hdr.nSamplesPre = ceil(fhdr(14)/(1000/hdr.Fs)); % assuming that a utility was used to insert the correct baseline % duration into the header since it is normally absent. This slot is % actually allocated to the age of the subject, although NetStation % does not use it when generating an EGIS session file. if any(chdr(:,3)-chdr(1,3)) error('Number of samples not the same for all cells.'); end; hdr.nSamples = chdr(1,3); %making assumption that number of samples is same for all cells % remember the original header details hdr.orig.fhdr = fhdr; hdr.orig.chdr = chdr; hdr.orig.ename = ename; hdr.orig.cnames = cnames; hdr.orig.fcom = fcom; hdr.orig.ftext = ftext; case 'egi_sbin' % segmented type only [header_array, CateNames, CatLengths, preBaseline] = read_sbin_header(filename); [p, f, x] = fileparts(filename); hdr.Fs = header_array(9); hdr.nChans = header_array(10); for i = 1:hdr.nChans % this should be consistent with ft_senslabel hdr.label{i,1} = ['E' num2str(i)]; end; hdr.nTrials = header_array(15); hdr.nSamplesPre = preBaseline; hdr.nSamples = header_array(16); % making assumption that number of samples is same for all cells % remember the original header details hdr.orig.header_array = header_array; hdr.orig.CateNames = CateNames; hdr.orig.CatLengths = CatLengths; case {'egi_mff_v1' 'egi_mff'} % this is currently the default % The following represents the code that was written by Ingrid, Robert % and Giovanni to get started with the EGI mff dataset format. It might % not support all details of the file formats. % An alternative implementation has been provided by EGI, this is % released as fieldtrip/external/egi_mff and referred further down in % this function as 'egi_mff_v2'. if ~usejava('jvm') error('the xml2struct requires MATLAB to be running with the Java virtual machine (JVM)'); % an alternative implementation which does not require the JVM but runs much slower is % available from http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0 end % get header info from .bin files binfiles = dir(fullfile(filename, 'signal*.bin')); if isempty(binfiles) error('could not find any signal.bin in mff directory') end orig = []; for iSig = 1:length(binfiles) signalname = binfiles(iSig).name; fullsignalname = fullfile(filename, signalname); orig.signal(iSig).blockhdr = read_mff_bin(fullsignalname); end % get hdr info from xml files warning('off', 'MATLAB:REGEXP:deprecated') % due to some small code xml2struct xmlfiles = dir( fullfile(filename, '*.xml')); disp('reading xml files to obtain header info...') for i = 1:numel(xmlfiles) if strcmpi(xmlfiles(i).name(1:2), '._') % Mac sometimes creates this useless files, don't use them elseif strcmpi(xmlfiles(i).name(1:6), 'Events') % don't read in events here, can take a lot of time, and we can do that in ft_read_event else fieldname = xmlfiles(i).name(1:end-4); filename_xml = fullfile(filename, xmlfiles(i).name); orig.xml.(fieldname) = xml2struct(filename_xml); end end warning('on', 'MATLAB:REGEXP:deprecated') %make hdr according to FieldTrip rules hdr = []; Fs = zeros(length(orig.signal),1); nChans = zeros(length(orig.signal),1); nSamples = zeros(length(orig.signal),1); for iSig = 1:length(orig.signal) Fs(iSig) = orig.signal(iSig).blockhdr(1).fsample(1); nChans(iSig) = orig.signal(iSig).blockhdr(1).nsignals; % the number of samples per block can be different nSamples_Block = zeros(length(orig.signal(iSig).blockhdr),1); for iBlock = 1:length(orig.signal(iSig).blockhdr) nSamples_Block(iBlock) = orig.signal(iSig).blockhdr(iBlock).nsamples(1); end nSamples(iSig) = sum(nSamples_Block); end if length(unique(Fs)) > 1 || length(unique(nSamples)) > 1 error('Fs and nSamples should be the same in all signals') end hdr.Fs = Fs(1); hdr.nChans = sum(nChans); hdr.nSamplesPre = 0; hdr.nSamples = nSamples(1); hdr.nTrials = 1; %-get channel labels for signal 1 (main net), otherwise create them if isfield(orig.xml, 'sensorLayout') % asuming that signal1 is hdEEG sensornet, and channels are in xml file sensorLayout for iSens = 1:numel(orig.xml.sensorLayout.sensors) if ~isempty(orig.xml.sensorLayout.sensors(iSens).sensor.name) && ~(isstruct(orig.xml.sensorLayout.sensors(iSens).sensor.name) && numel(fieldnames(orig.xml.sensorLayout.sensors(iSens).sensor.name))==0) %only get name when channel is EEG (type 0), or REF (type 1), %rest are non interesting channels like place holders and COM and should not be added. if strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '0') || strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '1') % get the sensor name from the datafile hdr.label{iSens} = orig.xml.sensorLayout.sensors(iSens).sensor.name; end elseif strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '0') % EEG chan % this should be consistent with ft_senslabel hdr.label{iSens} = ['E' num2str(orig.xml.sensorLayout.sensors(iSens).sensor.number)]; elseif strcmp(orig.xml.sensorLayout.sensors(iSens).sensor.type, '1') % REF chan % ingnie: I now choose REF as name for REF channel since our discussion see bug 1407. Arbitrary choice... hdr.label{iSens} = ['REF' num2str(iSens)]; else % non interesting channels like place holders and COM end end %check if the amount of lables corresponds with nChannels in signal 1 if length(hdr.label) == nChans(1) %good elseif length(hdr.label) > orig.signal(1).blockhdr(1).nsignals warning('found more lables in xml.sensorLayout than channels in signal 1, thus can not use info in sensorLayout, creating labels on the fly') for iSens = 1:orig.signal(1).blockhdr(1).nsignals % this should be consistent with ft_senslabel hdr.label{iSens} = ['E' num2str(iSens)]; end else warning('found less lables in xml.sensorLayout than channels in signal 1, thus can not use info in sensorLayout, creating labels on the fly') for iSens = 1:orig.signal(1).blockhdr(1).nsignals % this should be consistent with ft_senslabel hdr.label{iSens} = ['E' num2str(iSens)]; end end % get lables for other signals if length(orig.signal) == 2 if isfield(orig.xml, 'pnsSet') % signal2 is PIB box, and lables are in xml file pnsSet nbEEGchan = length(hdr.label); for iSens = 1:numel(orig.xml.pnsSet.sensors) hdr.label{nbEEGchan+iSens} = num2str(orig.xml.pnsSet.sensors(iSens).sensor.name); end if length(hdr.label) == orig.signal(2).blockhdr(1).nsignals + orig.signal(2).blockhdr(1).nsignals % good elseif length(hdr.label) < orig.signal(1).blockhdr(1).nsignals + orig.signal(2).blockhdr(1).nsignals warning('found less lables in xml.pnsSet than channels in signal 2, labeling with s2_unknownN instead') for iSens = length(hdr.label)+1 : orig.signal(1).blockhdr(1).nsignals + orig.signal(2).blockhdr(1).nsignals hdr.label{iSens} = ['s2_unknown', num2str(iSens)]; end else warning('found more lables in xml.pnsSet than channels in signal 2, thus can not use info in pnsSet, and labeling with s2_eN instead') for iSens = orig.signal(1).blockhdr(1).nsignals+1 : orig.signal(1).blockhdr(1).nsignals + orig.signal(2).blockhdr(1).nsignals hdr.label{iSens} = ['s2_E', num2str(iSens)]; end end else % signal2 is not PIBbox warning('creating channel labels for signal 2 on the fly') for iSens = 1:orig.signal(2).blockhdr(1).nsignals hdr.label{end+1} = ['s2_E', num2str(iSens)]; end end elseif length(orig.signal) > 2 % loop over signals and label channels accordingly warning('creating channel labels for signal 2 to signal N on the fly') for iSig = 2:length(orig.signal) for iSens = 1:orig.signal(iSig).blockhdr(1).nsignals if iSig == 1 && iSens == 1 hdr.label{1} = ['s',num2str(iSig),'_E', num2str(iSens)]; else hdr.label{end+1} = ['s',num2str(iSig),'_E', num2str(iSens)]; end end end end else % no xml.sensorLayout present warning('no sensorLayout found in xml files, creating channel labels on the fly') for iSig = 1:length(orig.signal) for iSens = 1:orig.signal(iSig).blockhdr(1).nsignals if iSig == 1 && iSens == 1 hdr.label{1} = ['s',num2str(iSig),'_E', num2str(iSens)]; else hdr.label{end+1} = ['s',num2str(iSig),'_E', num2str(iSens)]; end end end end % check if multiple epochs are present if isfield(orig.xml,'epoch') && length(orig.xml.epoch) > 1 % add info to header about which sample correspond to which epochs, becasue this is quite hard for user to get... epochdef = zeros(length(orig.xml.epoch),3); for iEpoch = 1:length(orig.xml.epoch) if iEpoch == 1 epochdef(iEpoch,1) = round(str2double(orig.xml.epoch(iEpoch).epoch.beginTime)./1000./hdr.Fs)+1; epochdef(iEpoch,2) = round(str2double(orig.xml.epoch(iEpoch).epoch.endTime)./1000./hdr.Fs); epochdef(iEpoch,3) = round(str2double(orig.xml.epoch(iEpoch).epoch.beginTime)./1000./hdr.Fs); %offset corresponds to timing else NbSampEpoch = round(str2double(orig.xml.epoch(iEpoch).epoch.endTime)./1000./hdr.Fs - str2double(orig.xml.epoch(iEpoch).epoch.beginTime)./1000./hdr.Fs); epochdef(iEpoch,1) = epochdef(iEpoch-1,2) + 1; epochdef(iEpoch,2) = epochdef(iEpoch-1,2) + NbSampEpoch; epochdef(iEpoch,3) = round(str2double(orig.xml.epoch(iEpoch).epoch.beginTime)./1000./hdr.Fs); %offset corresponds to timing end end warning('the data contains multiple epochs with possibly discontinuous boundaries. Added ''epochdef'' to hdr.orig defining begin and end sample of each epoch. See hdr.orig.xml.epoch for epoch details, use ft_read_header to obtain header or look in data.dhr.') % sanity check if epochdef(end,2) ~= hdr.nSamples error('number of samples in all epochs do not add up to total number of samples') end orig.epochdef = epochdef; end hdr.orig = orig; case 'egi_mff_v2' % ensure that the EGI_MFF toolbox is on the path ft_hastoolbox('egi_mff', 1); % ensure that the JVM is running and the jar file is on the path mff_setup; if isunix && filename(1)~=filesep % add the full path to the dataset directory filename = fullfile(pwd, filename); else % FIXME I don't know how this is supposed to work on Windows computers % with the drive letter in front of the path end hdr = read_mff_header(filename); case 'fcdc_buffer' % read from a networked buffer for realtime analysis [host, port] = filetype_check_uri(filename); if retry orig = []; while isempty(orig) try % try reading the header, catch the error and retry orig = buffer('get_hdr', [], host, port); catch warning('could not read header from %s, retrying in 1 second', filename); pause(1); end end % while else % try reading the header only once, give error if it fails orig = buffer('get_hdr', [], host, port); end % if retry hdr.Fs = orig.fsample; hdr.nChans = orig.nchans; hdr.nSamples = orig.nsamples; hdr.nSamplesPre = 0; % since continuous hdr.nTrials = 1; % since continuous hdr.orig = []; % this will contain the chunks (if present) % add the contents of attached RES4 chunk after decoding to Matlab structure if isfield(orig, 'ctf_res4') if isempty(cachechunk) % this only needs to be decoded once cachechunk = decode_res4(orig.ctf_res4); end % copy the gradiometer details hdr.grad = cachechunk.grad; hdr.orig = cachechunk.orig; if isfield(orig, 'channel_names') % get the same selection of channels from the two chunks [selbuf, selres4] = match_str(orig.channel_names, cachechunk.label); if length(selres4)<length(orig.channel_names) error('the res4 chunk did not contain all channels') end % copy some of the channel details hdr.label = cachechunk.label(selres4); hdr.chantype = cachechunk.chantype(selres4); hdr.chanunit = cachechunk.chanunit(selres4); % add the channel names chunk as well hdr.orig.channel_names = orig.channel_names; end % add the raw chunk as well hdr.orig.ctf_res4 = orig.ctf_res4; end % add the contents of attached NIFTI-1 chunk after decoding to Matlab structure if isfield(orig, 'nifti_1') hdr.nifti_1 = decode_nifti1(orig.nifti_1); % add the raw chunk as well hdr.orig.nifti_1 = orig.nifti_1; end % add the contents of attached SiemensAP chunk after decoding to Matlab structure if isfield(orig, 'siemensap') && exist('sap2matlab')==3 % only run this if MEX file is present hdr.siemensap = sap2matlab(orig.siemensap); % add the raw chunk as well hdr.orig.siemensap = orig.siemensap; end if ~isfield(hdr, 'label') % prevent overwriting the labels that we might have gotten from a RES4 chunk if isfield(orig, 'channel_names') hdr.label = orig.channel_names; else hdr.label = cell(hdr.nChans,1); if hdr.nChans < 2000 % don't do this for fMRI etc. warning_once('creating fake channel names'); % give this warning only once for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end else warning_once('skipping fake channel names'); % give this warning only once checkUniqueLabels = false; end end end hdr.orig.bufsize = orig.bufsize; case 'fcdc_buffer_offline' [hdr, nameFlag] = read_buffer_offline_header(headerfile); switch nameFlag case 0 % no labels generated (fMRI etc) checkUniqueLabels = false; % no need to check these case 1 % has generated fake channels % give this warning only once warning_once('creating fake channel names'); checkUniqueLabels = false; % no need to check these case 2 % got labels from chunk, check those checkUniqueLabels = true; end case 'fcdc_matbin' % this is multiplexed data in a *.bin file, accompanied by a matlab file containing the header load(headerfile, 'hdr'); case 'fcdc_mysql' % check that the required low-level toolbox is available ft_hastoolbox('mysql', 1); % read from a MySQL server listening somewhere else on the network db_open(filename); if db_blob hdr = db_select_blob('fieldtrip.header', 'msg', 1); else hdr = db_select('fieldtrip.header', {'nChans', 'nSamples', 'nSamplesPre', 'Fs', 'label'}, 1); hdr.label = mxDeserialize(hdr.label); end case 'gtec_mat' % this is a simple MATLAB format, it contains a log and a names variable tmp = load(headerfile); log = tmp.log; names = tmp.names; hdr.label = cellstr(names); hdr.nChans = size(log,1); hdr.nSamples = size(log,2); hdr.nSamplesPre = 0; hdr.nTrials = 1; % assume continuous data, not epoched % compute the sampling frequency from the time channel sel = strcmp(hdr.label, 'Time'); time = log(sel,:); hdr.Fs = 1./(time(2)-time(1)); % also remember the complete data upon request if cache hdr.orig.log = log; hdr.orig.names = names; end case {'itab_raw' 'itab_mhd'} % read the full header information frtom the binary header structure header_info = read_itab_mhd(headerfile); % these are the channels that are visible to fieldtrip chansel = 1:header_info.nchan; % convert the header information into a fieldtrip compatible format hdr.nChans = length(chansel); hdr.label = {header_info.ch(chansel).label}; hdr.label = hdr.label(:); % should be column vector hdr.Fs = header_info.smpfq; % it will always be continuous data hdr.nSamples = header_info.ntpdata; hdr.nSamplesPre = 0; % it is a single continuous trial hdr.nTrials = 1; % it is a single continuous trial % keep the original details AND the list of channels as used by fieldtrip hdr.orig = header_info; hdr.orig.chansel = chansel; % add the gradiometer definition hdr.grad = itab2grad(header_info); case 'micromed_trc' orig = read_micromed_trc(filename); hdr = []; hdr.Fs = orig.Rate_Min; % FIXME is this correct? hdr.nChans = orig.Num_Chan; hdr.nSamples = orig.Num_Samples; hdr.nSamplesPre = 0; % continuous hdr.nTrials = 1; % continuous hdr.label = cell(1,hdr.nChans); % give this warning only once warning('creating fake channel names'); for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end % this should be a column vector hdr.label = hdr.label(:); % remember the original header details hdr.orig = orig; case {'mpi_ds', 'mpi_dap'} hdr = read_mpi_ds(filename); case 'netmeg' ft_hastoolbox('netcdf', 1); % this will read all NetCDF data from the file and subsequently convert % each of the three elements into a more easy to parse MATLAB structure s = netcdf(filename); for i=1:numel(s.AttArray) fname = fixname(s.AttArray(i).Str); fval = s.AttArray(i).Val; if ischar(fval) fval = fval(fval~=0); % remove the \0 characters fval = strtrim(fval); % remove insignificant whitespace end Att.(fname) = fval; end for i=1:numel(s.VarArray) fname = fixname(s.VarArray(i).Str); fval = s.VarArray(i).Data; if ischar(fval) fval = fval(fval~=0); % remove the \0 characters fval = strtrim(fval); % remove insignificant whitespace end Var.(fname) = fval; end for i=1:numel(s.DimArray) fname = fixname(s.DimArray(i).Str); fval = s.DimArray(i).Dim; if ischar(fval) fval = fval(fval~=0); % remove the \0 characters fval = strtrim(fval); % remove insignificant whitespace end Dim.(fname) = fval; end % convert the relevant fields into teh default header structure hdr.Fs = 1000/Var.samplinginterval; hdr.nChans = length(Var.channelstatus); hdr.nSamples = Var.numsamples; hdr.nSamplesPre = 0; hdr.nTrials = size(Var.waveforms, 1); hdr.chanunit = cellstr(reshape(Var.channelunits, hdr.nChans, 2)); hdr.chantype = cellstr(reshape(lower(Var.channeltypes), hdr.nChans, 3)); warning_once('creating fake channel names'); hdr.label = cell(hdr.nChans, 1); for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end % remember the original details of the file % note that this also includes the data % this is large, but can be reused elsewhere hdr.orig.Att = Att; hdr.orig.Var = Var; hdr.orig.Dim = Dim; % construct the gradiometer structure from the complete header information hdr.grad = netmeg2grad(hdr); case 'neuralynx_dma' hdr = read_neuralynx_dma(filename); case 'neuralynx_sdma' hdr = read_neuralynx_sdma(filename); case 'neuralynx_ncs' ncs = read_neuralynx_ncs(filename, 1, 0); [p, f, x] = fileparts(filename); hdr.Fs = ncs.hdr.SamplingFrequency; hdr.label = {f}; hdr.nChans = 1; hdr.nTrials = 1; hdr.nSamplesPre = 0; hdr.nSamples = ncs.NRecords * 512; hdr.orig = ncs.hdr; FirstTimeStamp = ncs.hdr.FirstTimeStamp; % this is the first timestamp of the first block LastTimeStamp = ncs.hdr.LastTimeStamp; % this is the first timestamp of the last block, i.e. not the timestamp of the last sample hdr.TimeStampPerSample = double(LastTimeStamp - FirstTimeStamp) ./ ((ncs.NRecords-1)*512); hdr.FirstTimeStamp = FirstTimeStamp; case 'neuralynx_nse' nse = read_neuralynx_nse(filename, 1, 0); [p, f, x] = fileparts(filename); hdr.Fs = nse.hdr.SamplingFrequency; hdr.label = {f}; hdr.nChans = 1; hdr.nTrials = nse.NRecords; % each record contains one waveform hdr.nSamples = 32; % there are 32 samples in each waveform hdr.nSamplesPre = 0; hdr.orig = nse.hdr; % FIXME add hdr.FirstTimeStamp and hdr.TimeStampPerSample case {'neuralynx_ttl', 'neuralynx_tsl', 'neuralynx_tsh'} % these are hardcoded, they contain an 8-byte header and int32 values for a single channel % FIXME this should be done similar as neuralynx_bin, i.e. move the hdr into the function hdr = []; hdr.Fs = 32556; hdr.nChans = 1; hdr.nSamples = (filesize(filename)-8)/4; hdr.nSamplesPre = 1; hdr.nTrials = 1; hdr.label = {headerformat((end-3):end)}; case 'neuralynx_bin' hdr = read_neuralynx_bin(filename); case 'neuralynx_ds' hdr = read_neuralynx_ds(filename); case 'neuralynx_cds' hdr = read_neuralynx_cds(filename); case 'nexstim_nxe' hdr = read_nexstim_nxe(filename); case {'neuromag_fif' 'neuromag_mne' 'babysquid_fif'} % check that the required low-level toolbox is available ft_hastoolbox('mne', 1); orig = fiff_read_meas_info(filename); % convert to fieldtrip format header hdr.label = orig.ch_names(:); hdr.nChans = orig.nchan; hdr.Fs = orig.sfreq; % add a gradiometer structure for forward and inverse modelling try [hdr.grad, elec] = mne2grad(orig); if ~isempty(elec) hdr.elec = elec; end catch disp(lasterr); end iscontinuous = 0; isaverage = 0; isepoched = 0; % FIXME don't know how to determine this, or whether epoched .fif data exists! if isempty(fiff_find_evoked(filename)) % true if file contains no evoked responses iscontinuous = 1; else isaverage = 1; end if iscontinuous try % we only use 1 input argument here to allow backward % compatibility up to MNE 2.6.x: raw = fiff_setup_read_raw(filename); catch % the "catch me" syntax is broken on MATLAB74, this fixes it me = lasterror; % there is an error - we try to use MNE 2.7.x (if present) to % determine if the cause is maxshielding: try allow_maxshield = true; raw = fiff_setup_read_raw(filename,allow_maxshield); catch %unknown problem, or MNE version 2.6.x or less: rethrow(me); end % no error message from fiff_setup_read_raw? Then maxshield % was applied, but maxfilter wasn't, so return this error: error(['Maxshield data has not had maxfilter applied to it - cannot be read by fieldtrip. ' ... 'Apply Neuromag maxfilter before converting to fieldtrip format.']); end hdr.nSamples = raw.last_samp - raw.first_samp + 1; % number of samples per trial hdr.nSamplesPre = 0; % otherwise conflicts will occur in read_data hdr.nTrials = 1; orig.raw = raw; % keep all the details elseif isaverage evoked_data = fiff_read_evoked_all(filename); vartriallength = any(diff([evoked_data.evoked.first])) || any(diff([evoked_data.evoked.last])); if vartriallength % there are trials averages with variable durations in the file warning('EVOKED FILE with VARIABLE TRIAL LENGTH! - check data have been processed accurately'); hdr.nSamples = 0; for i=1:length(evoked_data.evoked) hdr.nSamples = hdr.nSamples + size(evoked_data.evoked(i).epochs, 2); end % represent it as a continuous file with a single trial % all trial average details will be available through read_event hdr.nSamplesPre = 0; hdr.nTrials = 1; orig.evoked = evoked_data.evoked; % this is used by read_data to get the actual data, i.e. to prevent re-reading orig.info = evoked_data.info; % keep all the details orig.vartriallength = 1; else % represent it as a file with multiple trials, each trial has the same length % all trial average details will be available through read_event hdr.nSamples = evoked_data.evoked(1).last - evoked_data.evoked(1).first + 1; hdr.nSamplesPre = -evoked_data.evoked(1).first; % represented as negative number in fif file hdr.nTrials = length(evoked_data.evoked); orig.evoked = evoked_data.evoked; % this is used by read_data to get the actual data, i.e. to prevent re-reading orig.info = evoked_data.info; % keep all the details orig.vartriallength = 0; end elseif isepoched error('Support for epoched *.fif data is not yet implemented.') end % remember the original header details hdr.orig = orig; % these are useful to know in read_event hdr.orig.isaverage = isaverage; hdr.orig.iscontinuous = iscontinuous; hdr.orig.isepoched = isepoched; case 'neuromag_mex' % check that the required low-level toolbox is available ft_hastoolbox('meg-pd', 1); rawdata('any',filename); rawdata('goto', 0); megmodel('head',[0 0 0],filename); % get the available information from the fif file [orig.rawdata.range,orig.rawdata.calib] = rawdata('range'); [orig.rawdata.sf] = rawdata('sf'); [orig.rawdata.samples] = rawdata('samples'); [orig.chaninfo.N,orig.chaninfo.S,orig.chaninfo.T] = chaninfo; % Numbers, names & places [orig.chaninfo.TY,orig.chaninfo.NA] = chaninfo('type'); % Coil type [orig.chaninfo.NO] = chaninfo('noise'); % Default noise level [orig.channames.NA,orig.channames.KI,orig.channames.NU] = channames(filename); % names, kind, logical numbers % read a single trial to determine the data size [buf, status] = rawdata('next'); rawdata('close'); % This is to solve a problem reported by Doug Davidson: The problem % is that rawdata('samples') is not returning the number of samples % correctly. It appears that the example script rawchannels in meg-pd % might work, however, so I want to use rawchannels to read in one % channel of data in order to get the number of samples in the file: if orig.rawdata.samples<0 tmpchannel = 1; tmpvar = rawchannels(filename,tmpchannel); [orig.rawdata.samples] = size(tmpvar,2); clear tmpvar tmpchannel; end % convert to fieldtrip format header hdr.label = orig.channames.NA; hdr.Fs = orig.rawdata.sf; hdr.nSamplesPre = 0; % I don't know how to get this out of the file hdr.nChans = size(buf,1); hdr.nSamples = size(buf,2); % number of samples per trial hdr.nTrials = orig.rawdata.samples ./ hdr.nSamples; % add a gradiometer structure for forward and inverse modelling hdr.grad = fif2grad(filename); % remember the original header details hdr.orig = orig; case 'neuroprax_eeg' orig = np_readfileinfo(filename); hdr.Fs = orig.fa; hdr.nChans = orig.K; hdr.nSamples = orig.N; hdr.nSamplesPre = 0; % continuous hdr.nTrials = 1; % continuous hdr.label = orig.channels(:); hdr.unit = orig.units(:); % remember the original header details hdr.orig = orig; case 'neurosim_evolution' hdr = read_neurosim_evolution(filename); case {'neurosim_ds' 'neurosim_signals'} hdr = read_neurosim_signals(filename); case 'neurosim_spikes' headerOnly=true; hdr= read_neurosim_spikes(filename,headerOnly); case 'nimh_cortex' cortex = read_nimh_cortex(filename, 'epp', 'no', 'eog', 'no'); % look at the first trial to determine whether it contains data in the EPP and EOG channels trial1 = read_nimh_cortex(filename, 'epp', 'yes', 'eog', 'yes', 'begtrial', 1, 'endtrial', 1); hasepp = ~isempty(trial1.epp); haseog = ~isempty(trial1.eog); if hasepp warning('EPP channels are not yet supported'); end % at the moment only the EOG channels are supported here if haseog hdr.label = {'EOGx' 'EOGy'}; hdr.nChans = 2; else hdr.label = {}; hdr.nChans = 0; end hdr.nTrials = length(cortex); hdr.nSamples = inf; hdr.nSamplesPre = 0; hdr.orig.trial = cortex; hdr.orig.hasepp = hasepp; hdr.orig.haseog = haseog; case 'ns_avg' orig = read_ns_hdr(filename); % do some reformatting/renaming of the header items hdr.Fs = orig.rate; hdr.nSamples = orig.npnt; hdr.nSamplesPre = round(-orig.rate*orig.xmin/1000); hdr.nChans = orig.nchan; hdr.label = orig.label(:); hdr.nTrials = 1; % the number of trials in this datafile is only one, i.e. the average % remember the original header details hdr.orig = orig; case {'ns_cnt' 'ns_cnt16', 'ns_cnt32'} if strcmp(headerformat, 'ns_cnt') orig = loadcnt(filename); elseif strcmp(headerformat, 'ns_cnt16') orig = loadcnt(filename, 'dataformat', 'int16'); elseif strcmp(headerformat, 'ns_cnt32') orig = loadcnt(filename, 'dataformat', 'int32'); end orig = rmfield(orig, {'data', 'ldnsamples'}); % do some reformatting/renaming of the header items hdr.Fs = orig.header.rate; hdr.nChans = orig.header.nchannels; hdr.nSamples = orig.header.nums; hdr.nSamplesPre = 0; hdr.nTrials = 1; for i=1:hdr.nChans hdr.label{i} = deblank(orig.electloc(i).lab); end % remember the original header details hdr.orig = orig; case 'ns_eeg' orig = read_ns_hdr(filename); % do some reformatting/renaming of the header items hdr.label = orig.label; hdr.Fs = orig.rate; hdr.nSamples = orig.npnt; hdr.nSamplesPre = round(-orig.rate*orig.xmin/1000); hdr.nChans = orig.nchan; hdr.nTrials = orig.nsweeps; % remember the original header details hdr.orig = orig; case 'plexon_ds' hdr = read_plexon_ds(filename); case 'plexon_ddt' orig = read_plexon_ddt(filename); hdr.nChans = orig.NChannels; hdr.Fs = orig.Freq; hdr.nSamples = orig.NSamples; hdr.nSamplesPre = 0; % continuous hdr.nTrials = 1; % continuous hdr.label = cell(1,hdr.nChans); % give this warning only once warning('creating fake channel names'); for i=1:hdr.nChans hdr.label{i} = sprintf('%d', i); end % also remember the original header hdr.orig = orig; case {'read_nex_data'} % this is an alternative reader for nex files orig = read_nex_header(filename); % assign the obligatory items to the output FCDC header numsmp = cell2mat({orig.varheader.numsmp}); adindx = find(cell2mat({orig.varheader.typ})==5); if isempty(adindx) error('file does not contain continuous channels'); end hdr.nChans = length(orig.varheader); hdr.Fs = orig.varheader(adindx(1)).wfrequency; % take the sampling frequency from the first A/D channel hdr.nSamples = max(numsmp(adindx)); % take the number of samples from the longest A/D channel hdr.nTrials = 1; % it can always be interpreted as continuous data hdr.nSamplesPre = 0; % and therefore it is not trial based for i=1:hdr.nChans hdr.label{i} = deblank(char(orig.varheader(i).nam)); end hdr.label = hdr.label(:); % also remember the original header details hdr.orig = orig; case {'read_plexon_nex' 'plexon_nex'} % this is the default reader for nex files orig = read_plexon_nex(filename); numsmp = cell2mat({orig.VarHeader.NPointsWave}); adindx = find(cell2mat({orig.VarHeader.Type})==5); if isempty(adindx) error('file does not contain continuous channels'); end hdr.nChans = length(orig.VarHeader); hdr.Fs = orig.VarHeader(adindx(1)).WFrequency; % take the sampling frequency from the first A/D channel hdr.nSamples = max(numsmp(adindx)); % take the number of samples from the longest A/D channel hdr.nTrials = 1; % it can always be interpreted as continuous data hdr.nSamplesPre = 0; % and therefore it is not trial based for i=1:hdr.nChans hdr.label{i} = deblank(char(orig.VarHeader(i).Name)); end hdr.label = hdr.label(:); hdr.FirstTimeStamp = orig.FileHeader.Beg; hdr.TimeStampPerSample = orig.FileHeader.Frequency ./ hdr.Fs; % also remember the original header details hdr.orig = orig; case 'plexon_plx' orig = read_plexon_plx(filename); if orig.NumSlowChannels==0 error('file does not contain continuous channels'); end fsample = [orig.SlowChannelHeader.ADFreq]; if any(fsample~=fsample(1)) error('different sampling rates in continuous data not supported'); end for i=1:length(orig.SlowChannelHeader) label{i} = deblank(orig.SlowChannelHeader(i).Name); end % continuous channels don't always contain data, remove the empty ones sel = [orig.DataBlockHeader.Type]==5; % continuous chan = [orig.DataBlockHeader.Channel]; for i=1:length(label) chansel(i) = any(chan(sel)==orig.SlowChannelHeader(i).Channel); end chansel = find(chansel); % this is required for timestamp selection label = label(chansel); % only the continuous channels are returned as visible hdr.nChans = length(label); hdr.Fs = fsample(1); hdr.label = label; % also remember the original header hdr.orig = orig; % select the first continuous channel that has data sel = ([orig.DataBlockHeader.Type]==5 & [orig.DataBlockHeader.Channel]==orig.SlowChannelHeader(chansel(1)).Channel); % get the timestamps that correspond with the continuous data tsl = [orig.DataBlockHeader(sel).TimeStamp]'; tsh = [orig.DataBlockHeader(sel).UpperByteOf5ByteTimestamp]'; ts = timestamp_plexon(tsl, tsh); % use helper function, this returns an uint64 array % determine the number of samples in the continuous channels num = [orig.DataBlockHeader(sel).NumberOfWordsInWaveform]; hdr.nSamples = sum(num); hdr.nSamplesPre = 0; % continuous hdr.nTrials = 1; % continuous % the timestamps indicate the beginning of each block, hence the timestamp of the last block corresponds with the end of the previous block hdr.TimeStampPerSample = double(ts(end)-ts(1))/sum(num(1:(end-1))); hdr.FirstTimeStamp = ts(1); % the timestamp of the first continuous sample % also make the spike channels visible for i=1:length(orig.ChannelHeader) hdr.label{end+1} = deblank(orig.ChannelHeader(i).Name); end hdr.label = hdr.label(:); hdr.nChans = length(hdr.label); case {'tdt_tsq', 'tdt_tev'} % FIXME the code below is not yet functional, it requires more input from the ESI in Frankfurt % tsq = read_tdt_tsq(headerfile); % k = 0; % chan = unique([tsq.channel]); % % loop over the physical channels % for i=1:length(chan) % chansel = [tsq.channel]==chan(i); % code = unique({tsq(chansel).code}); % % loop over the logical channels % for j=1:length(code) % codesel = false(size(tsq)); % for k=1:numel(codesel) % codesel(k) = identical(tsq(k).code, code{j}); % end % % find the first instance of this logical channel % this = find(chansel(:) & codesel(:), 1); % % add it to the list of channels % k = k + 1; % frequency(k) = tsq(this).frequency; % label{k} = [char(typecast(tsq(this).code, 'uint8')) num2str(tsq(this).channel)]; % tsqorig(k) = tsq(this); % end % end error('not yet implemented'); case {'yokogawa_ave', 'yokogawa_con', 'yokogawa_raw', 'yokogawa_mrk'} % header can be read with two toolboxes: Yokogawa MEG Reader and Yokogawa MEG160 (old inofficial toolbox) % newest toolbox takes precedence. if ft_hastoolbox('yokogawa_meg_reader', 3); % stay silent if it cannot be added hdr = read_yokogawa_header_new(filename); % add a gradiometer structure for forward and inverse modelling hdr.grad = yokogawa2grad_new(hdr); else ft_hastoolbox('yokogawa', 1); % try it with the old version of the toolbox hdr = read_yokogawa_header(filename); % add a gradiometer structure for forward and inverse modelling hdr.grad = yokogawa2grad(hdr); end case 'nmc_archive_k' hdr = read_nmc_archive_k_hdr(filename); case 'neuroshare' % NOTE: still under development % check that the required neuroshare toolbox is available ft_hastoolbox('neuroshare', 1); tmp = read_neuroshare(filename); hdr.Fs = tmp.hdr.analoginfo(end).SampleRate; % take the sampling freq from the last analog channel (assuming this is the same for all chans) hdr.nChans = length(tmp.list.analog(tmp.analog.contcount~=0)); % get the analog channels, only the ones that are not empty hdr.nSamples = max([tmp.hdr.entityinfo(tmp.list.analog).ItemCount]); % take the number of samples from the longest channel hdr.nSamplesPre = 0; % continuous data hdr.nTrials = 1; % continuous data hdr.label = {tmp.hdr.entityinfo(tmp.list.analog(tmp.analog.contcount~=0)).EntityLabel}; %%% contains non-unique chans? hdr.orig = tmp; % remember the original header case 'bucn_nirs' orig = read_bucn_nirshdr(filename); hdr = rmfield(orig, 'time'); hdr.orig = orig; otherwise if strcmp(fallback, 'biosig') && ft_hastoolbox('BIOSIG', 1) hdr = read_biosig_header(filename); else error('unsupported header format (%s)', headerformat); end end % switch headerformat % Sometimes, the not all labels are correctly filled in by low-level reading % functions. See for example bug #1572. % First, make sure that there are enough (potentially empty) labels: if numel(hdr.label) < hdr.nChans warning('low-level reading function did not supply enough channel labels'); hdr.label{hdr.nChans} = []; end % Now, replace all empty labels with new name: if any(cellfun(@isempty, hdr.label)) warning('channel labels should not be empty, creating unique labels'); hdr.label = fix_empty(hdr.label); end if checkUniqueLabels if length(hdr.label)~=length(unique(hdr.label)) % all channels must have unique names warning('all channels must have unique labels, creating unique labels'); for i=1:hdr.nChans sel = find(strcmp(hdr.label{i}, hdr.label)); if length(sel)>1 for j=1:length(sel) hdr.label{sel(j)} = sprintf('%s-%d', hdr.label{sel(j)}, j); end end end end end % ensure that it is a column array hdr.label = hdr.label(:); % as of November 2011, the header is supposed to include the channel type % (see FT_CHANTYPE) and the units of each channel (e.g. uV, fT, ...). if ~isfield(hdr, 'chantype') % use a helper function which has some built in intelligence hdr.chantype = ft_chantype(hdr); end % for if ~isfield(hdr, 'chanunit') % use a helper function which has some built in intelligence hdr.chanunit = ft_chanunit(hdr); end % for % ensure that the output grad/elec is according to the latest definition % allow both elec and sens to be present if isfield(hdr, 'grad') hdr.grad = ft_datatype_sens(hdr.grad); end if isfield(hdr, 'elec') hdr.elec = ft_datatype_sens(hdr.elec); end % ensure that these are double precision and not integers, otherwise % subsequent computations that depend on these might be messed up hdr.Fs = double(hdr.Fs); hdr.nSamples = double(hdr.nSamples); hdr.nSamplesPre = double(hdr.nSamplesPre); hdr.nTrials = double(hdr.nTrials); hdr.nChans = double(hdr.nChans); if cache && exist(headerfile, 'file') % put the header in the cache cacheheader = hdr; % update the header details (including time stampp, size and name) cacheheader.details = dir(headerfile); % fprintf('added header to cache\n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to determine the file size in bytes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [siz] = filesize(filename) l = dir(filename); if l.isdir error('"%s" is not a file', filename); end siz = l.bytes; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to determine the file size in bytes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [hdr] = recursive_read_header(filename) [p, f, x] = fileparts(filename); ls = dir(filename); ls = ls(~strcmp({ls.name}, '.')); % exclude this directory ls = ls(~strcmp({ls.name}, '..')); % exclude parent directory for i=1:length(ls) % make sure that the directory listing includes the complete path ls(i).name = fullfile(filename, ls(i).name); end lst = {ls.name}; hdr = cell(size(lst)); sel = zeros(size(lst)); for i=1:length(lst) % read the header of each individual file try thishdr = ft_read_header(lst{i}); if isstruct(thishdr) thishdr.filename = lst{i}; end catch thishdr = []; warning(lasterr); fprintf('while reading %s\n\n', lst{i}); end if ~isempty(thishdr) hdr{i} = thishdr; sel(i) = true; else sel(i) = false; end end sel = logical(sel(:)); hdr = hdr(sel); tmp = {}; for i=1:length(hdr) if isstruct(hdr{i}) tmp = cat(1, tmp, hdr(i)); elseif iscell(hdr{i}) tmp = cat(1, tmp, hdr{i}{:}); end end hdr = tmp; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to fill in empty labels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function labels = fix_empty(labels) for i = find(cellfun(@isempty, {labels{:}})); labels{i} = sprintf('%d', i); end
github
philippboehmsturm/antx-master
ft_filetype.m
.m
antx-master/xspm8/external/fieldtrip/fileio/ft_filetype.m
59,071
utf_8
63c215c5b603d0b75250113171f7298d
function [type] = ft_filetype(filename, desired, varargin) % FT_FILETYPE determines the filetype of many EEG/MEG/MRI data files by % looking at the name, extension and optionally (part of) its contents. % It tries to determine the global type of file (which usually % corresponds to the manufacturer, the recording system or to the % software used to create the file) and the particular subtype (e.g. % continuous, average). % % Use as % type = ft_filetype(filename) % type = ft_filetype(dirname) % % This gives you a descriptive string with the data type, and can be % used in a switch-statement. The descriptive string that is returned % usually is something like 'XXX_YYY'/ where XXX refers to the % manufacturer and YYY to the type of the data. % % Alternatively, use as % flag = ft_filetype(filename, type) % flag = ft_filetype(dirname, type) % This gives you a boolean flag (0 or 1) indicating whether the file % is of the desired type, and can be used to check whether the % user-supplied file is what your subsequent code expects. % % Alternatively, use as % flag = ft_filetype(dirlist, type) % where the dirlist contains a list of files contained within one % directory. This gives you a boolean vector indicating for each file % whether it is of the desired type. % % Most filetypes of the following manufacturers and/or software programs are recognized % - 4D/BTi % - AFNI % - ASA % - Analyse % - Analyze/SPM % - BESA % - BrainVision % - Curry % - Dataq % - EDF % - EEProbe % - Elektra/Neuromag % - LORETA % - FreeSurfer % - MINC % - Neuralynx % - Neuroscan % - Plexon % - SR Research Eyelink % - Tucker Davis Technology % - VSM-Medtech/CTF % - Yokogawa % - nifti, gifti % Copyright (C) 2003-2011 Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_filetype.m 7351 2013-01-18 05:09:26Z josdie $ % these are for remembering the type on subsequent calls with the same input arguments persistent previous_argin previous_argout previous_pwd if nargin<2 % ensure that all input arguments are defined desired = []; end current_argin = {filename, desired, varargin{:}}; current_pwd = pwd; if isequal(current_argin, previous_argin) && isequal(current_pwd, previous_pwd) % don't do the detection again, but return the previous value from cache type = previous_argout{1}; return end if isa(filename, 'memmapfile') filename = filename.Filename; end % % get the optional arguments % checkheader = ft_getopt(varargin, 'checkheader', true); % % if ~checkheader % % assume that the header is always ok, e.g when the file does not yet exist % % this replaces the normal function with a function that always returns true % filetype_check_header = @filetype_true; % end if iscell(filename) if ~isempty(desired) % perform the test for each filename, return a boolean vector type = false(size(filename)); else % return a string with the type for each filename type = cell(size(filename)); end for i=1:length(filename) if strcmp(filename{i}(end), '.') % do not recurse into this directory or the parent directory continue else if iscell(type) type{i} = ft_filetype(filename{i}, desired); else type(i) = ft_filetype(filename{i}, desired); end end end return end % start with unknown values type = 'unknown'; manufacturer = 'unknown'; content = 'unknown'; if isempty(filename) if isempty(desired) % return the "unknown" outputs return else % return that it is a non-match type = false; return end end % the parts of the filename are used further down [p, f, x] = fileparts(filename); % prevent this test if the filename resembles an URI, i.e. like "scheme://" if isempty(strfind(filename , '://')) && isdir(filename) % the directory listing is needed below ls = dir(filename); % remove the parent directory and the directory itself from the list ls = ls(~strcmp({ls.name}, '.')); ls = ls(~strcmp({ls.name}, '..')); for i=1:length(ls) % make sure that the directory listing includes the complete path ls(i).name = fullfile(filename, ls(i).name); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % start determining the filetype %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this checks for a compressed file (of arbitrary type) if filetype_check_extension(filename, 'zip')... || (filetype_check_extension(filename, '.gz') && ~filetype_check_extension(filename, '.nii.gz'))... || filetype_check_extension(filename, 'tgz')... || filetype_check_extension(filename, 'tar') type = 'compressed'; manufacturer = 'undefined'; content = 'unknown, extract first'; % these are some streams for asynchronous BCI elseif filetype_check_uri(filename, 'fifo') type = 'fcdc_fifo'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'buffer') type = 'fcdc_buffer'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'mysql') type = 'fcdc_mysql'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'tcp') type = 'fcdc_tcp'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'udp') type = 'fcdc_udp'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'rfb') type = 'fcdc_rfb'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'serial') type = 'fcdc_serial'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'stream'; elseif filetype_check_uri(filename, 'global') type = 'fcdc_global'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'global variable'; elseif filetype_check_uri(filename, 'shm') type = 'ctf_shm'; manufacturer = 'CTF'; content = 'real-time shared memory buffer'; elseif filetype_check_uri(filename, 'empty') type = 'empty'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = '/dev/null'; % known CTF file types elseif isdir(filename) && filetype_check_extension(filename, '.ds') && exist(fullfile(filename, [f '.res4'])) type = 'ctf_ds'; manufacturer = 'CTF'; content = 'MEG dataset'; elseif isdir(filename) && ~isempty(dir(fullfile(filename, '*.res4'))) && ~isempty(dir(fullfile(filename, '*.meg4'))) type = 'ctf_ds'; manufacturer = 'CTF'; content = 'MEG dataset'; elseif filetype_check_extension(filename, '.res4') && (filetype_check_header(filename, 'MEG41RS') || filetype_check_header(filename, 'MEG42RS') || filetype_check_header(filename, 'MEG4RES') || filetype_check_header(filename, 'MEG3RES')) %'MEG3RES' pertains to ctf64.ds type = 'ctf_res4'; manufacturer = 'CTF'; content = 'MEG/EEG header information'; elseif filetype_check_extension(filename, '.meg4') && (filetype_check_header(filename, 'MEG41CP') || filetype_check_header(filename, 'MEG4CPT')) %'MEG4CPT' pertains to ctf64.ds type = 'ctf_meg4'; manufacturer = 'CTF'; content = 'MEG/EEG'; elseif strcmp(f, 'MarkerFile') && filetype_check_extension(filename, '.mrk') && filetype_check_header(filename, 'PATH OF DATASET:') type = 'ctf_mrk'; manufacturer = 'CTF'; content = 'marker file'; elseif filetype_check_extension(filename, '.mri') && filetype_check_header(filename, 'CTF_MRI_FORMAT VER 2.2') type = 'ctf_mri'; manufacturer = 'CTF'; content = 'MRI'; elseif filetype_check_extension(filename, '.mri') && filetype_check_header(filename, 'CTF_MRI_FORMAT VER 4', 31) type = 'ctf_mri4'; manufacturer = 'CTF'; content = 'MRI'; elseif filetype_check_extension(filename, '.hdm') type = 'ctf_hdm'; manufacturer = 'CTF'; content = 'volume conduction model'; elseif filetype_check_extension(filename, '.hc') type = 'ctf_hc'; manufacturer = 'CTF'; content = 'headcoil locations'; elseif filetype_check_extension(filename, '.shape') type = 'ctf_shape'; manufacturer = 'CTF'; content = 'headshape points'; elseif filetype_check_extension(filename, '.shape_info') type = 'ctf_shapeinfo'; manufacturer = 'CTF'; content = 'headshape information'; elseif filetype_check_extension(filename, '.wts') type = 'ctf_wts'; manufacturer = 'CTF'; content = 'SAM coefficients, i.e. spatial filter weights'; elseif filetype_check_extension(filename, '.svl') type = 'ctf_svl'; manufacturer = 'CTF'; content = 'SAM (pseudo-)statistic volumes'; % known Micromed file types elseif filetype_check_extension(filename, '.trc') && filetype_check_header(filename, '* MICROMED') type = 'micromed_trc'; manufacturer = 'Micromed'; content = 'Electrophysiological data'; % known BabySQUID file types, these should go before Neuromag elseif filetype_check_extension(filename, '.fif') && exist(fullfile(p, [f '.eve']), 'file') type = 'babysquid_fif'; manufacturer = 'Tristan Technologies'; content = 'MEG data'; elseif filetype_check_extension(filename, '.eve') && exist(fullfile(p, [f '.fif']), 'file') type = 'babysquid_eve'; manufacturer = 'Tristan Technologies'; content = 'MEG data'; % known Neuromag file types elseif filetype_check_extension(filename, '.fif') type = 'neuromag_fif'; manufacturer = 'Neuromag'; content = 'MEG header and data'; elseif filetype_check_extension(filename, '.bdip') type = 'neuromag_bdip'; manufacturer = 'Neuromag'; content = 'dipole model'; % known Yokogawa file types elseif filetype_check_extension(filename, '.ave') || filetype_check_extension(filename, '.sqd') type = 'yokogawa_ave'; manufacturer = 'Yokogawa'; content = 'averaged MEG data'; elseif filetype_check_extension(filename, '.con') type = 'yokogawa_con'; manufacturer = 'Yokogawa'; content = 'continuous MEG data'; elseif filetype_check_extension(filename, '.raw') && filetype_check_header(filename, char([0 0 0 0])) % FIXME, this detection should possibly be improved type = 'yokogawa_raw'; manufacturer = 'Yokogawa'; content = 'evoked/trialbased MEG data'; elseif filetype_check_extension(filename, '.mrk') && filetype_check_header(filename, char([0 0 0 0])) % FIXME, this detection should possibly be improved type = 'yokogawa_mrk'; manufacturer = 'Yokogawa'; content = 'headcoil locations'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-coregis')) == 1 type = 'yokogawa_coregis'; manufacturer = 'Yokogawa'; content = 'exported fiducials'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-calib')) == 1 type = 'yokogawa_calib'; manufacturer = 'Yokogawa'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-channel')) == 1 type = 'yokogawa_channel'; manufacturer = 'Yokogawa'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-property')) == 1 type = 'yokogawa_property'; manufacturer = 'Yokogawa'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-TextData')) == 1 type = 'yokogawa_textdata'; manufacturer = 'Yokogawa'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'-FLL')) == 1 type = 'yokogawa_fll'; manufacturer = 'Yokogawa'; elseif filetype_check_extension(filename, '.hsp') type = 'yokogawa_hsp'; manufacturer = 'Yokogawa'; % Neurosim files; this has to go before the 4D detection elseif ~isdir(filename) && (strcmp(f,'spikes') || filetype_check_header(filename,'# Spike information')) type = 'neurosim_spikes'; manufacturer = 'Jan van der Eerden (DCCN)'; content = 'simulated spikes'; elseif ~isdir(filename) && (strcmp(f,'evolution') || filetype_check_header(filename,'# Voltages')) type = 'neurosim_evolution'; manufacturer = 'Jan van der Eerden (DCCN)'; content = 'simulated membrane voltages and currents'; elseif ~isdir(filename) && (strcmp(f,'signals') || filetype_check_header(filename,'# Internal',2)) type = 'neurosim_signals'; manufacturer = 'Jan van der Eerden (DCCN)'; content = 'simulated network signals'; elseif isdir(filename) && exist(fullfile(filename, 'signals'), 'file') && exist(fullfile(filename, 'spikes'), 'file') type = 'neurosim_ds'; manufacturer = 'Jan van der Eerden (DCCN)'; content = 'simulated spikes and continuous signals'; % known 4D/BTI file types elseif filetype_check_extension(filename, '.pdf') && filetype_check_header(filename, 'E|lk') % I am not sure whether this header always applies type = '4d_pdf'; manufacturer = '4D/BTI'; content = 'raw MEG data (processed data file)'; elseif exist([filename '.m4d'], 'file') && exist([filename '.xyz'], 'file') % these two ascii header files accompany the raw data type = '4d_pdf'; manufacturer = '4D/BTI'; content = 'raw MEG data (processed data file)'; elseif filetype_check_extension(filename, '.m4d') && exist([filename(1:(end-3)) 'xyz'], 'file') % these come in pairs type = '4d_m4d'; manufacturer = '4D/BTI'; content = 'MEG header information'; elseif filetype_check_extension(filename, '.xyz') && exist([filename(1:(end-3)) 'm4d'], 'file') % these come in pairs type = '4d_xyz'; manufacturer = '4D/BTI'; content = 'MEG sensor positions'; elseif isequal(f, 'hs_file') % the filename is "hs_file" type = '4d_hs'; manufacturer = '4D/BTI'; content = 'head shape'; elseif length(filename)>=4 && ~isempty(strfind(filename,',rf')) type = '4d'; manufacturer = '4D/BTi'; content = ''; elseif filetype_check_extension(filename, '.el.ascii') && filetype_check_ascii(filename, 20) % assume that there are at least 20 bytes in the file, the example one has 4277 bytes type = '4d_el_ascii'; manufacturer = '4D/BTi'; content = 'electrode positions'; elseif length(f)<=4 && filetype_check_dir(p, 'config')%&& ~isempty(p) && exist(fullfile(p,'config'), 'file') %&& exist(fullfile(p,'hs_file'), 'file') % this could be a 4D file with non-standard/processed name % it will be detected as a 4D file when there is a config file in the % same directory as the specified file type = '4d'; manufacturer = '4D/BTi'; content = ''; % known EEProbe file types elseif filetype_check_extension(filename, '.cnt') && filetype_check_header(filename, 'RIFF') type = 'eep_cnt'; manufacturer = 'EEProbe'; content = 'EEG'; elseif filetype_check_extension(filename, '.avr') && filetype_check_header(filename, char([38 0 16 0])) type = 'eep_avr'; manufacturer = 'EEProbe'; content = 'ERP'; elseif filetype_check_extension(filename, '.trg') type = 'eep_trg'; manufacturer = 'EEProbe'; content = 'trigger information'; elseif filetype_check_extension(filename, '.rej') type = 'eep_rej'; manufacturer = 'EEProbe'; content = 'rejection marks'; % the yokogawa_mri has to be checked prior to asa_mri, because this one is more strict elseif filetype_check_extension(filename, '.mri') && filetype_check_header(filename, char(0)) % FIXME, this detection should possibly be improved type = 'yokogawa_mri'; manufacturer = 'Yokogawa'; content = 'anatomical MRI'; % known ASA file types elseif filetype_check_extension(filename, '.elc') type = 'asa_elc'; manufacturer = 'ASA'; content = 'electrode positions'; elseif filetype_check_extension(filename, '.vol') type = 'asa_vol'; manufacturer = 'ASA'; content = 'volume conduction model'; elseif filetype_check_extension(filename, '.bnd') type = 'asa_bnd'; manufacturer = 'ASA'; content = 'boundary element model details'; elseif filetype_check_extension(filename, '.msm') type = 'asa_msm'; manufacturer = 'ASA'; content = 'ERP'; elseif filetype_check_extension(filename, '.msr') type = 'asa_msr'; manufacturer = 'ASA'; content = 'ERP'; elseif filetype_check_extension(filename, '.dip') % FIXME, can also be CTF dipole file type = 'asa_dip'; manufacturer = 'ASA'; elseif filetype_check_extension(filename, '.mri') % FIXME, can also be CTF mri file type = 'asa_mri'; manufacturer = 'ASA'; content = 'MRI image header'; elseif filetype_check_extension(filename, '.iso') type = 'asa_iso'; manufacturer = 'ASA'; content = 'MRI image data'; % known BCI2000 file types elseif filetype_check_extension(filename, '.dat') && (filetype_check_header(filename, 'BCI2000') || filetype_check_header(filename, 'HeaderLen=')) type = 'bci2000_dat'; manufacturer = 'BCI2000'; content = 'continuous EEG'; % known Neuroscan file types elseif filetype_check_extension(filename, '.avg') && filetype_check_header(filename, 'Version 3.0') type = 'ns_avg'; manufacturer = 'Neuroscan'; content = 'averaged EEG'; elseif filetype_check_extension(filename, '.cnt') && filetype_check_header(filename, 'Version 3.0') type = 'ns_cnt'; manufacturer = 'Neuroscan'; content = 'continuous EEG'; elseif filetype_check_extension(filename, '.eeg') && filetype_check_header(filename, 'Version 3.0') type = 'ns_eeg'; manufacturer = 'Neuroscan'; content = 'epoched EEG'; elseif filetype_check_extension(filename, '.eeg') && filetype_check_header(filename, 'V3.0') type = 'neuroprax_eeg'; manufacturer = 'eldith GmbH'; content = 'continuous EEG'; elseif filetype_check_extension(filename, '.ee_') type = 'neuroprax_mrk'; manufacturer = 'eldith GmbH'; content = 'EEG markers'; % known Analyze & SPM file types elseif filetype_check_extension(filename, '.hdr') type = 'analyze_hdr'; manufacturer = 'Mayo Analyze'; content = 'PET/MRI image header'; elseif filetype_check_extension(filename, '.img') type = 'analyze_img'; manufacturer = 'Mayo Analyze'; content = 'PET/MRI image data'; elseif filetype_check_extension(filename, '.mnc') type = 'minc'; content = 'MRI image data'; elseif filetype_check_extension(filename, '.nii') type = 'nifti'; content = 'MRI image data'; % known FSL file types elseif filetype_check_extension(filename, '.nii.gz') type = 'nifti_fsl'; content = 'MRI image data'; % known LORETA file types elseif filetype_check_extension(filename, '.lorb') type = 'loreta_lorb'; manufacturer = 'old LORETA'; content = 'source reconstruction'; elseif filetype_check_extension(filename, '.slor') type = 'loreta_slor'; manufacturer = 'sLORETA'; content = 'source reconstruction'; % known AFNI file types elseif filetype_check_extension(filename, '.brik') || filetype_check_extension(filename, '.BRIK') type = 'afni_brik'; content = 'MRI image data'; elseif filetype_check_extension(filename, '.head') || filetype_check_extension(filename, '.HEAD') type = 'afni_head'; content = 'MRI header data'; % known BrainVison file types elseif filetype_check_extension(filename, '.vhdr') type = 'brainvision_vhdr'; manufacturer = 'BrainProducts'; content = 'EEG header'; elseif filetype_check_extension(filename, '.vmrk') type = 'brainvision_vmrk'; manufacturer = 'BrainProducts'; content = 'EEG markers'; elseif filetype_check_extension(filename, '.vabs') type = 'brainvision_vabs'; manufacturer = 'BrainProducts'; content = 'Brain Vison Analyzer macro'; elseif filetype_check_extension(filename, '.eeg') && exist(fullfile(p, [f '.vhdr']), 'file') type = 'brainvision_eeg'; manufacturer = 'BrainProducts'; content = 'continuous EEG data'; elseif filetype_check_extension(filename, '.seg') type = 'brainvision_seg'; manufacturer = 'BrainProducts'; content = 'segmented EEG data'; elseif filetype_check_extension(filename, '.dat') && exist(fullfile(p, [f '.vhdr']), 'file') &&... ~filetype_check_header(filename, 'HeaderLen=') && ~filetype_check_header(filename, 'BESA_SA_IMAGE') &&... ~(exist(fullfile(p, [f '.gen']), 'file') || exist(fullfile(p, [f '.generic']), 'file')) % WARNING this is a very general name, it could be exported BrainVision % data but also a BESA beamformer source reconstruction or BCI2000 type = 'brainvision_dat'; manufacturer = 'BrainProducts'; content = 'exported EEG data'; elseif filetype_check_extension(filename, '.marker') type = 'brainvision_marker'; manufacturer = 'BrainProducts'; content = 'rejection markers'; % known Polhemus file types elseif filetype_check_extension(filename, '.pos') type = 'polhemus_pos'; manufacturer = 'BrainProducts/CTF/Polhemus?'; % actually I don't know whose software it is content = 'electrode positions'; % known Neuralynx file types elseif filetype_check_extension(filename, '.nev') || filetype_check_extension(filename, '.Nev') type = 'neuralynx_nev'; manufacturer = 'Neuralynx'; content = 'event information'; elseif filetype_check_extension(filename, '.ncs') && filetype_check_header(filename, '####') type = 'neuralynx_ncs'; manufacturer = 'Neuralynx'; content = 'continuous single channel recordings'; elseif filetype_check_extension(filename, '.nse') && filetype_check_header(filename, '####') type = 'neuralynx_nse'; manufacturer = 'Neuralynx'; content = 'spike waveforms'; elseif filetype_check_extension(filename, '.nts') && filetype_check_header(filename, '####') type = 'neuralynx_nts'; manufacturer = 'Neuralynx'; content = 'timestamps only'; elseif filetype_check_extension(filename, '.nvt') type = 'neuralynx_nvt'; manufacturer = 'Neuralynx'; content = 'video tracker'; elseif filetype_check_extension(filename, '.nst') type = 'neuralynx_nst'; manufacturer = 'Neuralynx'; content = 'continuous stereotrode recordings'; elseif filetype_check_extension(filename, '.ntt') type = 'neuralynx_ntt'; manufacturer = 'Neuralynx'; content = 'continuous tetrode recordings'; elseif strcmpi(f, 'logfile') && strcmpi(x, '.txt') % case insensitive type = 'neuralynx_log'; manufacturer = 'Neuralynx'; content = 'log information in ASCII format'; elseif ~isempty(strfind(lower(f), 'dma')) && strcmpi(x, '.log') % this is not a very strong detection type = 'neuralynx_dma'; manufacturer = 'Neuralynx'; content = 'raw aplifier data directly from DMA'; elseif filetype_check_extension(filename, '.nrd') % see also above, since Cheetah 5.x the file extension has changed type = 'neuralynx_dma'; manufacturer = 'Neuralynx'; content = 'raw aplifier data directly from DMA'; elseif isdir(filename) && (any(filetype_check_extension({ls.name}, '.nev')) || any(filetype_check_extension({ls.name}, '.Nev'))) % a regular Neuralynx dataset directory that contains an event file type = 'neuralynx_ds'; manufacturer = 'Neuralynx'; content = 'dataset'; elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.ncs')) % a directory containing continuously sampled channels in Neuralynx format type = 'neuralynx_ds'; manufacturer = 'Neuralynx'; content = 'continuously sampled channels'; elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.nse')) % a directory containing spike waveforms in Neuralynx format type = 'neuralynx_ds'; manufacturer = 'Neuralynx'; content = 'spike waveforms'; elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.nte')) % a directory containing spike timestamps in Neuralynx format type = 'neuralynx_ds'; manufacturer = 'Neuralynx'; content = 'spike timestamps'; elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.ntt')) % a directory containing tetrode recordings in Neuralynx format type = 'neuralynx_ds'; manufacturer = 'Neuralynx'; content = 'tetrode recordings '; elseif isdir(p) && exist(fullfile(p, 'header'), 'file') && exist(fullfile(p, 'events'), 'file') type = 'fcdc_buffer_offline'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'FieldTrip buffer offline dataset'; elseif isdir(filename) && exist(fullfile(filename, 'info.xml'), 'file') && exist(fullfile(filename, 'signal1.bin'), 'file') % this is an OS X package directory representing a complete EEG dataset % it contains a Content file, multiple xml files and one or more signalN.bin files type = 'egi_mff'; manufacturer = 'Electrical Geodesics Incorporated'; content = 'raw EEG data'; elseif ~isdir(filename) && isdir(p) && exist(fullfile(p, 'info.xml'), 'file') && exist(fullfile(p, 'signal1.bin'), 'file') % the file that the user specified is one of the files in an mff package directory type = 'egi_mff'; manufacturer = 'Electrical Geodesics Incorporated'; content = 'raw EEG data'; % these are formally not Neuralynx file formats, but at the FCDC we use them together with Neuralynx elseif isdir(filename) && filetype_check_neuralynx_cds(filename) % a downsampled Neuralynx DMA file can be split into three seperate lfp/mua/spike directories % treat them as one combined dataset type = 'neuralynx_cds'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'dataset containing seperate lfp/mua/spike directories'; elseif filetype_check_extension(filename, '.tsl') && filetype_check_header(filename, 'tsl') type = 'neuralynx_tsl'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'timestamps from DMA log file'; elseif filetype_check_extension(filename, '.tsh') && filetype_check_header(filename, 'tsh') type = 'neuralynx_tsh'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'timestamps from DMA log file'; elseif filetype_check_extension(filename, '.ttl') && filetype_check_header(filename, 'ttl') type = 'neuralynx_ttl'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'Parallel_in from DMA log file'; elseif filetype_check_extension(filename, '.bin') && filetype_check_header(filename, {'uint8', 'uint16', 'uint32', 'int8', 'int16', 'int32', 'int64', 'float32', 'float64'}) type = 'neuralynx_bin'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'single channel continuous data'; elseif isdir(filename) && any(filetype_check_extension({ls.name}, '.ttl')) && any(filetype_check_extension({ls.name}, '.tsl')) && any(filetype_check_extension({ls.name}, '.tsh')) % a directory containing the split channels from a DMA logfile type = 'neuralynx_sdma'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'split DMA log file'; elseif isdir(filename) && filetype_check_extension(filename, '.sdma') % a directory containing the split channels from a DMA logfile type = 'neuralynx_sdma'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'split DMA log file'; % known Plexon file types elseif filetype_check_extension(filename, '.nex') && filetype_check_header(filename, 'NEX1') type = 'plexon_nex'; manufacturer = 'Plexon'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.plx') && filetype_check_header(filename, 'PLEX') type = 'plexon_plx'; manufacturer = 'Plexon'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.ddt') type = 'plexon_ddt'; manufacturer = 'Plexon'; elseif isdir(filename) && most(filetype_check_extension({ls.name}, '.nex')) && most(filetype_check_header({ls.name}, 'NEX1')) % a directory containing multiple plexon NEX files type = 'plexon_ds'; manufacturer = 'Plexon'; content = 'electrophysiological data'; % known Cambridge Electronic Design file types elseif filetype_check_extension(filename, '.smr') type = 'ced_son'; manufacturer = 'Cambridge Electronic Design'; content = 'Spike2 SON filing system'; % known BESA file types elseif filetype_check_extension(filename, '.avr') && strcmp(type, 'unknown') type = 'besa_avr'; % FIXME, can also be EEProbe average EEG manufacturer = 'BESA'; content = 'average EEG'; elseif filetype_check_extension(filename, '.elp') type = 'besa_elp'; manufacturer = 'BESA'; content = 'electrode positions'; elseif filetype_check_extension(filename, '.eps') type = 'besa_eps'; manufacturer = 'BESA'; content = 'digitizer information'; elseif filetype_check_extension(filename, '.sfp') type = 'besa_sfp'; manufacturer = 'BESA'; content = 'sensor positions'; elseif filetype_check_extension(filename, '.ela') type = 'besa_ela'; manufacturer = 'BESA'; content = 'sensor information'; elseif filetype_check_extension(filename, '.pdg') type = 'besa_pdg'; manufacturer = 'BESA'; content = 'paradigm file'; elseif filetype_check_extension(filename, '.tfc') type = 'besa_tfc'; manufacturer = 'BESA'; content = 'time frequency coherence'; elseif filetype_check_extension(filename, '.mul') type = 'besa_mul'; manufacturer = 'BESA'; content = 'multiplexed ascii format'; elseif filetype_check_extension(filename, '.dat') && filetype_check_header(filename, 'BESA_SA') % header can start with BESA_SA_IMAGE or BESA_SA_MN_IMAGE type = 'besa_src'; manufacturer = 'BESA'; content = 'beamformer source reconstruction'; elseif filetype_check_extension(filename, '.swf') && filetype_check_header(filename, 'Npts=') type = 'besa_swf'; manufacturer = 'BESA'; content = 'beamformer source waveform'; elseif filetype_check_extension(filename, '.bsa') type = 'besa_bsa'; manufacturer = 'BESA'; content = 'beamformer source locations and orientations'; elseif exist(fullfile(p, [f '.dat']), 'file') && (exist(fullfile(p, [f '.gen']), 'file') || exist(fullfile(p, [f '.generic']), 'file')) type = 'besa_sb'; manufacturer = 'BESA'; content = 'simple binary channel data with a seperate generic ascii header'; % known Dataq file formats elseif filetype_check_extension(upper(filename), '.WDQ') type = 'dataq_wdq'; manufacturer = 'dataq instruments'; content = 'electrophysiological data'; % old files from Pascal Fries' PhD research at the MPI elseif filetype_check_extension(filename, '.dap') && filetype_check_header(filename, char(1)) type = 'mpi_dap'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; elseif isdir(filename) && ~isempty(cell2mat(regexp({ls.name}, '.dap$'))) type = 'mpi_ds'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; % Frankfurt SPASS format, which uses the Labview Datalog (DTLG) format elseif filetype_check_extension(filename, '.ana') && filetype_check_header(filename, 'DTLG') type = 'spass_ana'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.swa') && filetype_check_header(filename, 'DTLG') type = 'spass_swa'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.spi') && filetype_check_header(filename, 'DTLG') type = 'spass_spi'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.stm') && filetype_check_header(filename, 'DTLG') type = 'spass_stm'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.bhv') && filetype_check_header(filename, 'DTLG') type = 'spass_bhv'; manufacturer = 'MPI Frankfurt'; content = 'electrophysiological data'; % known Chieti ITAB file types elseif filetype_check_extension(filename, '.raw') && (filetype_check_header(filename, 'FORMAT: ATB-BIOMAGDATA') || filetype_check_header(filename, '[HeaderType]')) type = 'itab_raw'; manufacturer = 'Chieti ITAB'; content = 'MEG data, including sensor positions'; elseif filetype_check_extension(filename, '.raw.mhd') type = 'itab_mhd'; manufacturer = 'Chieti ITAB'; content = 'MEG header data, including sensor positions'; elseif filetype_check_extension(filename, '.asc') && ~filetype_check_header(filename, '**') type = 'itab_asc'; manufacturer = 'Chieti ITAB'; content = 'headshape digitization file'; % known Nexstim file types elseif filetype_check_extension(filename, '.nxe') type = 'nexstim_nxe'; manufacturer = 'Nexstim'; content = 'electrophysiological data'; % known Tucker-Davis-Technology file types elseif filetype_check_extension(filename, '.tbk') type = 'tdt_tbk'; manufacturer = 'Tucker-Davis-Technology'; content = 'database/tank meta-information'; elseif filetype_check_extension(filename, '.tdx') type = 'tdt_tdx'; manufacturer = 'Tucker-Davis-Technology'; content = 'database/tank meta-information'; elseif filetype_check_extension(filename, '.tsq') type = 'tdt_tsq'; manufacturer = 'Tucker-Davis-Technology'; content = 'block header information'; elseif filetype_check_extension(filename, '.tev') type = 'tdt_tev'; manufacturer = 'Tucker-Davis-Technology'; content = 'electrophysiological data'; elseif (filetype_check_extension(filename, '.dat') || filetype_check_extension(filename, '.Dat')) && (exist(fullfile(p, [f '.ini']), 'file') || exist(fullfile(p, [f '.Ini']), 'file')) % this should go before curry_dat type = 'deymed_dat'; manufacturer = 'Deymed'; content = 'raw eeg data'; elseif (filetype_check_extension(filename, '.ini') || filetype_check_extension(filename, '.Ini')) && (exist(fullfile(p, [f '.dat']), 'file') || exist(fullfile(p, [f '.Dat']), 'file')) type = 'deymed_ini'; manufacturer = 'Deymed'; content = 'eeg header information'; % known Curry V4 file types elseif filetype_check_extension(filename, '.dap') type = 'curry_dap'; % FIXME, can also be MPI Frankfurt electrophysiological data manufacturer = 'Curry'; content = 'data parameter file'; elseif filetype_check_extension(filename, '.dat') type = 'curry_dat'; manufacturer = 'Curry'; content = 'raw data file'; elseif filetype_check_extension(filename, '.rs4') type = 'curry_rs4'; manufacturer = 'Curry'; content = 'sensor geometry file'; elseif filetype_check_extension(filename, '.par') type = 'curry_par'; manufacturer = 'Curry'; content = 'data or image parameter file'; elseif filetype_check_extension(filename, '.bd0') || filetype_check_extension(filename, '.bd1') || filetype_check_extension(filename, '.bd2') || filetype_check_extension(filename, '.bd3') || filetype_check_extension(filename, '.bd4') || filetype_check_extension(filename, '.bd5') || filetype_check_extension(filename, '.bd6') || filetype_check_extension(filename, '.bd7') || filetype_check_extension(filename, '.bd8') || filetype_check_extension(filename, '.bd9') type = 'curry_bd'; manufacturer = 'Curry'; content = 'BEM description file'; elseif filetype_check_extension(filename, '.bt0') || filetype_check_extension(filename, '.bt1') || filetype_check_extension(filename, '.bt2') || filetype_check_extension(filename, '.bt3') || filetype_check_extension(filename, '.bt4') || filetype_check_extension(filename, '.bt5') || filetype_check_extension(filename, '.bt6') || filetype_check_extension(filename, '.bt7') || filetype_check_extension(filename, '.bt8') || filetype_check_extension(filename, '.bt9') type = 'curry_bt'; manufacturer = 'Curry'; content = 'BEM transfer matrix file'; elseif filetype_check_extension(filename, '.bm0') || filetype_check_extension(filename, '.bm1') || filetype_check_extension(filename, '.bm2') || filetype_check_extension(filename, '.bm3') || filetype_check_extension(filename, '.bm4') || filetype_check_extension(filename, '.bm5') || filetype_check_extension(filename, '.bm6') || filetype_check_extension(filename, '.bm7') || filetype_check_extension(filename, '.bm8') || filetype_check_extension(filename, '.bm9') type = 'curry_bm'; manufacturer = 'Curry'; content = 'BEM full matrix file'; elseif filetype_check_extension(filename, '.dig') type = 'curry_dig'; manufacturer = 'Curry'; content = 'digitizer file'; % known SR Research eyelink file formats elseif filetype_check_extension(filename, '.asc') && filetype_check_header(filename, '**') type = 'eyelink_asc'; manufacturer = 'SR Research (ascii)'; content = 'eyetracker data'; elseif filetype_check_extension(filename, '.edf') && filetype_check_header(filename, 'SR_RESEARCH') type = 'eyelink_edf'; manufacturer = 'SR Research'; content = 'eyetracker data (binary)'; % known Curry V2 file types elseif filetype_check_extension(filename, '.sp0') || filetype_check_extension(filename, '.sp1') || filetype_check_extension(filename, '.sp2') || filetype_check_extension(filename, '.sp3') || filetype_check_extension(filename, '.sp4') || filetype_check_extension(filename, '.sp5') || filetype_check_extension(filename, '.sp6') || filetype_check_extension(filename, '.sp7') || filetype_check_extension(filename, '.sp8') || filetype_check_extension(filename, '.sp9') type = 'curry_sp'; manufacturer = 'Curry'; content = 'point list'; elseif filetype_check_extension(filename, '.s10') || filetype_check_extension(filename, '.s11') || filetype_check_extension(filename, '.s12') || filetype_check_extension(filename, '.s13') || filetype_check_extension(filename, '.s14') || filetype_check_extension(filename, '.s15') || filetype_check_extension(filename, '.s16') || filetype_check_extension(filename, '.s17') || filetype_check_extension(filename, '.s18') || filetype_check_extension(filename, '.s19') || filetype_check_extension(filename, '.s20') || filetype_check_extension(filename, '.s21') || filetype_check_extension(filename, '.s22') || filetype_check_extension(filename, '.s23') || filetype_check_extension(filename, '.s24') || filetype_check_extension(filename, '.s25') || filetype_check_extension(filename, '.s26') || filetype_check_extension(filename, '.s27') || filetype_check_extension(filename, '.s28') || filetype_check_extension(filename, '.s29') || filetype_check_extension(filename, '.s30') || filetype_check_extension(filename, '.s31') || filetype_check_extension(filename, '.s32') || filetype_check_extension(filename, '.s33') || filetype_check_extension(filename, '.s34') || filetype_check_extension(filename, '.s35') || filetype_check_extension(filename, '.s36') || filetype_check_extension(filename, '.s37') || filetype_check_extension(filename, '.s38') || filetype_check_extension(filename, '.s39') type = 'curry_s'; manufacturer = 'Curry'; content = 'triangle or tetraedra list'; elseif filetype_check_extension(filename, '.pom') type = 'curry_pom'; manufacturer = 'Curry'; content = 'anatomical localization file'; elseif filetype_check_extension(filename, '.res') type = 'curry_res'; manufacturer = 'Curry'; content = 'functional localization file'; % known MBFYS file types elseif filetype_check_extension(filename, '.tri') type = 'mbfys_tri'; manufacturer = 'MBFYS'; content = 'triangulated surface'; elseif filetype_check_extension(filename, '.ama') && filetype_check_header(filename, [10 0 0 0]) type = 'mbfys_ama'; manufacturer = 'MBFYS'; content = 'BEM volume conduction model'; % Electrical Geodesics Incorporated formats % the egi_mff format is checked earlier elseif (filetype_check_extension(filename, '.egis') || filetype_check_extension(filename, '.ave') || filetype_check_extension(filename, '.gave') || filetype_check_extension(filename, '.raw')) && (filetype_check_header(filename, [char(1) char(2) char(3) char(4) char(255) char(255)]) || filetype_check_header(filename, [char(3) char(4) char(1) char(2) char(255) char(255)])) type = 'egi_egia'; manufacturer = 'Electrical Geodesics Incorporated'; content = 'averaged EEG data'; elseif (filetype_check_extension(filename, '.egis') || filetype_check_extension(filename, '.ses') || filetype_check_extension(filename, '.raw')) && (filetype_check_header(filename, [char(1) char(2) char(3) char(4) char(0) char(3)]) || filetype_check_header(filename, [char(3) char(4) char(1) char(2) char(0) char(3)])) type = 'egi_egis'; manufacturer = 'Electrical Geodesics Incorporated'; content = 'raw EEG data'; elseif (filetype_check_extension(filename, '.sbin') || filetype_check_extension(filename, '.raw')) % note that the Chieti MEG data format also has the extension *.raw % but that can be detected by looking at the file header type = 'egi_sbin'; manufacturer = 'Electrical Geodesics Incorporated'; content = 'averaged EEG data'; % FreeSurfer file formats, see also http://www.grahamwideman.com/gw/brain/fs/surfacefileformats.htm elseif filetype_check_extension(filename, '.mgz') type = 'freesurfer_mgz'; manufacturer = 'FreeSurfer'; content = 'anatomical MRI'; elseif filetype_check_extension(filename, '.mgh') type = 'freesurfer_mgh'; manufacturer = 'FreeSurfer'; content = 'anatomical MRI'; elseif filetype_check_header(filename, [255 255 254]) % FreeSurfer Triangle Surface Binary Format type = 'freesurfer_triangle_binary'; % there is also an ascii triangle format manufacturer = 'FreeSurfer'; content = 'surface description'; elseif filetype_check_header(filename, [255 255 255]) % Quadrangle File type = 'freesurfer_quadrangle'; % there is no ascii quadrangle format manufacturer = 'FreeSurfer'; content = 'surface description'; elseif filetype_check_header(filename, [255 255 253]) && ~exist([filename(1:(end-4)) '.mat'], 'file') % "New" Quadrangle File type = 'freesurfer_quadrangle_new'; manufacturer = 'FreeSurfer'; content = 'surface description'; elseif filetype_check_extension(filename, '.curv') && filetype_check_header(filename, [255 255 255]) % "New" Curv File type = 'freesurfer_curv_new'; manufacturer = 'FreeSurfer'; content = 'surface description'; elseif filetype_check_extension(filename, '.annot') % Freesurfer annotation file type = 'freesurfer_annot'; manufacturer = 'FreeSurfer'; content = 'parcellation annotation'; elseif filetype_check_extension(filename, '.txt') && numel(strfind(filename,'_nrs_')) == 1 % This may be improved by looking into the file, rather than assuming the % filename has "_nrs_" somewhere. Also, distinction by the different file % types could be made type = 'bucn_nirs'; manufacturer = 'BUCN'; content = 'ascii formatted nirs data'; % known TETGEN file types, see http://tetgen.berlios.de/fformats.html elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.poly']), 'file') type = 'tetgen_poly'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with piecewise linear complex'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.smesh']), 'file') type = 'tetgensmesh'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with simple piecewise linear complex'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.ele']), 'file') type = 'tetgen_ele'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with tetrahedra'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.face']), 'file') type = 'tetgen_face'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with triangular faces'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.edge']), 'file') type = 'tetgen_edge'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with boundary edges'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.vol']), 'file') type = 'tetgen_vol'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with maximum volumes'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.var']), 'file') type = 'tetgen_var'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with variant constraints for facets/segments'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) && exist(fullfile(p, [f '.neigh']), 'file') type = 'tetgen_neigh'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with neighbors'; elseif any(filetype_check_extension(filename, {'.node' '.poly' '.smesh' '.ele' '.face' '.edge' '.vol' '.var' '.neigh'})) && exist(fullfile(p, [f '.node']), 'file') && filetype_check_ascii(fullfile(p, [f '.node']), 100) type = 'tetgen_node'; manufacturer = 'TetGen, see http://tetgen.berlios.de'; content = 'geometrical data desribed with only nodes'; % some other known file types elseif length(filename)>4 && exist([filename(1:(end-4)) '.mat'], 'file') && exist([filename(1:(end-4)) '.bin'], 'file') % this is a self-defined FCDC data format, consisting of two files % there is a matlab V6 file with the header and a binary file with the data (multiplexed, ieee-le, double) type = 'fcdc_matbin'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'multiplexed electrophysiology data'; elseif filetype_check_extension(filename, '.lay') type = 'layout'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'layout of channels for plotting'; elseif filetype_check_extension(filename, '.stl') type = 'stl'; manufacturer = 'various'; content = 'stereo litography file'; elseif filetype_check_extension(filename, '.dcm') || filetype_check_extension(filename, '.ima') || filetype_check_header(filename, 'DICM', 128) type = 'dicom'; manufacturer = 'Dicom'; content = 'image data'; elseif filetype_check_extension(filename, '.trl') type = 'fcdc_trl'; manufacturer = 'Donders Centre for Cognitive Neuroimaging'; content = 'trial definitions'; elseif filetype_check_extension(filename, '.bdf') && filetype_check_header(filename, [255 'BIOSEMI']) type = 'biosemi_bdf'; manufacturer = 'Biosemi Data Format'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.edf') type = 'edf'; manufacturer = 'European Data Format'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.gdf') && filetype_check_header(filename, 'GDF') type = 'gdf'; manufacturer = 'BIOSIG - Alois Schloegl'; content = 'biosignals'; elseif filetype_check_extension(filename, '.mat') && filetype_check_header(filename, 'MATLAB') && filetype_check_spmeeg_mat(filename) type = 'spmeeg_mat'; manufacturer = 'Wellcome Trust Centre for Neuroimaging, UCL, UK'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.mat') && filetype_check_header(filename, 'MATLAB') && filetype_check_gtec_mat(filename) type = 'gtec_mat'; manufacturer = 'Guger Technologies, http://www.gtec.at'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.mat') && filetype_check_header(filename, 'MATLAB') && filetype_check_ced_spike6mat(filename) type = 'ced_spike6mat'; manufacturer = 'Cambridge Electronic Design Limited'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.mat') && filetype_check_header(filename, 'MATLAB') type = 'matlab'; manufacturer = 'Matlab'; content = 'Matlab binary data'; elseif filetype_check_header(filename, 'RIFF', 0) && filetype_check_header(filename, 'WAVE', 8) type = 'riff_wave'; manufacturer = 'Microsoft'; content = 'audio'; elseif filetype_check_extension(filename, '.txt') type = 'ascii_txt'; manufacturer = ''; content = ''; elseif filetype_check_extension(filename, '.pol') type = 'polhemus_fil'; manufacturer = 'Functional Imaging Lab, London, UK'; content = 'headshape points'; elseif filetype_check_extension(filename, '.set') type = 'eeglab_set'; manufacturer = 'Swartz Center for Computational Neuroscience, San Diego, USA'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.erp') type = 'eeglab_erp'; manufacturer = 'Swartz Center for Computational Neuroscience, San Diego, USA'; content = 'electrophysiological data'; elseif filetype_check_extension(filename, '.t') && filetype_check_header(filename, '%%BEGINHEADER') type = 'mclust_t'; manufacturer = 'MClust'; content = 'sorted spikes'; elseif filetype_check_header(filename, 26) type = 'nimh_cortex'; manufacturer = 'NIMH Laboratory of Neuropsychology, http://www.cortex.salk.edu'; content = 'events and eye channels'; elseif filetype_check_extension(filename, '.foci') && filetype_check_header(filename, '<?xml') type = 'caret_foci'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.border') && filetype_check_header(filename, '<?xml') type = 'caret_border'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.spec') && filetype_check_header(filename, '<?xml') type = 'caret_spec'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.coord.')) && filetype_check_header(filename, '<?xml') type = 'caret_coord'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.topo.')) && filetype_check_header(filename, '<?xml') type = 'caret_topo'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.surf.')) && filetype_check_header(filename, '<?xml') type = 'caret_surf'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.label.')) && filetype_check_header(filename, '<?xml') type = 'caret_label'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.func.')) && filetype_check_header(filename, '<?xml') type = 'caret_func'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && ~isempty(strfind(filename, '.shape.')) && filetype_check_header(filename, '<?xml') type = 'caret_shape'; manufacturer = 'Caret and ConnectomeWB'; elseif filetype_check_extension(filename, '.gii') && filetype_check_header(filename, '<?xml') type = 'gifti'; manufacturer = 'Neuroimaging Informatics Technology Initiative'; content = 'tesselated surface description'; elseif filetype_check_extension(filename, '.v') type = 'vista'; manufacturer = 'University of British Columbia, Canada, http://www.cs.ubc.ca/nest/lci/vista/vista.html'; content = 'A format for computer vision research, contains meshes or volumes'; elseif filetype_check_extension(filename, '.tet') type = 'tet'; manufacturer = 'a.o. INRIA, see http://shapes.aimatshape.net/'; content = 'tetraedral mesh'; elseif filetype_check_extension(filename, '.nc') type = 'netmeg'; manufacturer = 'Center for Biomedical Research Excellence (COBRE), see http://cobre.mrn.org/megsim/tools/netMEG/netMEG.html'; content = 'MEG data'; elseif filetype_check_extension(filename, 'trk') type = 'trackvis_trk'; manufacturer = 'Martinos Center for Biomedical Imaging, see http://www.trackvis.org'; content = 'fiber tracking data from diffusion MR imaging'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % finished determining the filetype %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(type, 'unknown') warning_once(sprintf('could not determine filetype of %s', filename)); end if ~isempty(desired) % return a boolean value instead of a descriptive string type = strcmp(type, desired); end % remember the current input and output arguments, so that they can be % reused on a subsequent call in case the same input argument is given current_argout = {type}; if isempty(previous_argin) && ~strcmp(type, 'unknown') previous_argin = current_argin; previous_argout = current_argout; previous_pwd = current_pwd; elseif isempty(previous_argin) && (exist(filename,'file') || exist(filename,'dir')) && strcmp(type, 'unknown') % if the type is unknown, but the file or dir exists, save the current output previous_argin = current_argin; previous_argout = current_argout; previous_pwd = current_pwd; else % don't remember in case unknown previous_argin = []; previous_argout = []; previous_pwd = []; end return % filetype main() %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that helps in deciding whether a directory with files should % be treated as a "dataset". This function returns a logical 1 (TRUE) if more % than half of the element of a vector are nonzero number or are 1 or TRUE. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = most(x) x = x(~isnan(x(:))); y = sum(x==0)<ceil(length(x)/2); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that always returns a true value %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = filetype_true(varargin) y = 1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that checks for CED spike6 mat file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = filetype_check_ced_spike6mat(filename) res = 1; var = whos('-file', filename); % Check whether all the variables in the file are structs (representing channels) if ~all(strcmp('struct', unique({var(:).class})) == 1) res = 0; return; end var = load(filename, var(1).name); var = struct2cell(var); % Check whether the fields of the first struct have some particular names fnames = { 'title' 'comment' 'interval' 'scale' 'offset' 'units' 'start' 'length' 'values' 'times' }; res = (numel(intersect(fieldnames(var{1}), fnames)) >= 5); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that checks for a SPM eeg/meg mat file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = filetype_check_spmeeg_mat(filename) % check for the accompanying *.dat file res = exist([filename(1:(end-4)) '.dat'], 'file'); if ~res, return; end % check the content of the *.mat file var = whos('-file', filename); res = res && numel(var)==1; res = res && strcmp('D', getfield(var, {1}, 'name')); res = res && strcmp('struct', getfield(var, {1}, 'class')); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that checks for a GTEC mat file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = filetype_check_gtec_mat(filename) % check the content of the *.mat file var = whos('-file', filename); res = length(intersect({'log', 'names'}, {var.name}))==2; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that checks the presence of a specified file in a directory %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = filetype_check_dir(p, filename) if ~isempty(p) d = dir(p); else d = dir; end res = ~isempty(strmatch(filename,{d.name},'exact')); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that checks whether the directory is neuralynx_cds %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = filetype_check_neuralynx_cds(filename) res=false; files=dir(filename); dirlist=files([files.isdir]); % 1) check for a subdirectory with extension .lfp, .mua or .spike haslfp = any(filetype_check_extension({dirlist.name}, 'lfp')); hasmua = any(filetype_check_extension({dirlist.name}, 'mua')); hasspike = any(filetype_check_extension({dirlist.name}, 'spike')); % 2) check for each of the subdirs being a neuralynx_ds if haslfp || hasmua || hasspike sel=find(filetype_check_extension({dirlist.name}, 'lfp')+... filetype_check_extension({dirlist.name}, 'mua')+... filetype_check_extension({dirlist.name}, 'spike')); neuralynxdirs=cell(1,length(sel)); for n=1:length(sel) neuralynxdirs{n}=fullfile(filename, dirlist(sel(n)).name); end res=any(ft_filetype(neuralynxdirs, 'neuralynx_ds')); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that checks whether the file contains only ascii characters %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function res = filetype_check_ascii(filename, len) % See http://en.wikipedia.org/wiki/ASCII if exist(filename, 'file') fid = fopen(filename, 'rt'); bin = fread(fid, len, 'uint8=>uint8'); fclose(fid); printable = bin>31 & bin<127; % the printable characters, represent letters, digits, punctuation marks, and a few miscellaneous symbols special = bin==10 | bin==13 | bin==11; % line feed, form feed, tab res = all(printable | special); else % always return true if the file does not (yet) exist, this is important % for determining the format to which data should be written res = 1; end
github
philippboehmsturm/antx-master
read_mff_bin.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_mff_bin.m
4,095
utf_8
14e1df31f92faf2b6f02cfe4a32060c9
function [output] = read_mff_bin(filename, begblock, endblock, chanindx) % READ_MFF_BIN % % Use as % [hdr] = read_mff_bin(filename) % or % [dat] = read_mff_bin(filename, begblock, endblock); fid = fopen(filename,'r'); if fid == -1 error('wrong filename') % could not find signal(n) end needhdr = (nargin==1); needdat = (nargin==4); if needhdr hdr = read_mff_block(fid, [], [], 'skip'); prevhdr = hdr(end); for i=2:hdr.opthdr.nblocks hdr(i) = read_mff_block(fid, prevhdr, [], 'skip'); prevhdr = hdr(end); end % assign the output variable output = hdr; elseif needdat prevhdr = []; dat = {}; block = 0; while true block = block+1; if block<begblock [hdr] = read_mff_block(fid, prevhdr, chanindx, 'skip'); prevhdr = hdr; continue % with the next block end if block==begblock [hdr, dat] = read_mff_block(fid, prevhdr, chanindx, 'read'); prevhdr = hdr; continue % with the next block end if block<=endblock [hdr, dat(:,end+1)] = read_mff_block(fid, prevhdr, chanindx, 'read'); prevhdr = hdr; continue % with the next block end break % out of the while loop end % while % assign the output variable output = dat; end % need header or data fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [hdr, dat] = read_mff_block(fid, prevhdr, chanindx, action) if nargin<3 prevhdr = []; end if nargin<4 action = 'none'; end %-Endianness endian = 'ieee-le'; % General information hdr.version = fread(fid, 1, 'int32', endian); if hdr.version==0 % the header did not change compared to the previous one % no additional information is present in the file % the file continues with the actual data hdr = prevhdr; hdr.version = 0; else hdr.headersize = fread(fid, 1, 'int32', endian); hdr.datasize = fread(fid, 1, 'int32', endian); % the documentation specified that this includes the data, but that seems not to be the case hdr.nsignals = fread(fid, 1, 'int32', endian); % channel-specific information hdr.offset = fread(fid, hdr.nsignals, 'int32', endian); % signal depth and frequency for each channel for i = 1:hdr.nsignals hdr.depth(i) = fread(fid, 1, 'int8', endian); hdr.fsample(i) = fread(fid, 1, 'bit24', endian); %ingnie: is bit24 the same as int24? end %-Optional header length hdr.optlength = fread(fid, 1, 'int32', endian); if hdr.optlength hdr.opthdr.EGItype = fread(fid, 1, 'int32', endian); hdr.opthdr.nblocks = fread(fid, 1, 'int64', endian); hdr.opthdr.nsamples = fread(fid, 1, 'int64', endian); hdr.opthdr.nsignals = fread(fid, 1, 'int32', endian); else hdr.opthdr = []; end % determine the number of samples for each channel hdr.nsamples = diff(hdr.offset); % the last one has to be determined by looking at the total data block length hdr.nsamples(end+1) = hdr.datasize - hdr.offset(end); % divide by the number of bytes in each channel hdr.nsamples = hdr.nsamples(:) ./ (hdr.depth(:)./8); end % reading the rest of the header switch action case 'read' dat = cell(length(chanindx), 1); currchan = 1; for i = 1:hdr.nsignals switch hdr.depth(i) % length in bit case 16 slen = 2; % sample length, for fseek datatype = 'int16'; case 32 slen = 4; % sample length, for fseek datatype = 'single'; case 64 slen = 8; % sample length, for fseek datatype = 'double'; end % case tmp = fread(fid, [1 hdr.nsamples(i)], datatype); if ~isempty(intersect(chanindx,i)) %only keep channels that are requested dat{currchan} = tmp; currchan = currchan + 1; end end % for case 'skip' dat = {}; fseek(fid, hdr.datasize, 'cof'); case 'none' dat = {}; return; end % switch action
github
philippboehmsturm/antx-master
ft_datatype_sens.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/ft_datatype_sens.m
8,876
utf_8
9cca02c1384fde3f0c40f1a5a3a0253a
function [sens] = ft_datatype_sens(sens, varargin) % FT_DATATYPE_SENS describes the FieldTrip structure that represents % an EEG, ECoG, or MEG sensor array. This structure is commonly called % "elec" for EEG and "grad" for MEG, or more general "sens" for either % one. % % The structure for MEG gradiometers and/or magnetometers contains % sens.label = Mx1 cell-array with channel labels % sens.chanpos = Mx3 matrix with channel positions % sens.chanori = Mx3 matrix with channel orientations, used for synthetic planar gradient computation % sens.tra = MxN matrix to combine coils into channels % sens.coilpos = Nx3 matrix with coil positions % sens.coilori = Nx3 matrix with coil orientations % sens.balance = structure containing info about the balancing, See FT_APPLY_MONTAGE % % The structure for EEG or ECoG channels contains % sens.label = Mx1 cell-array with channel labels % sens.chanpos = Mx3 matrix with channel positions % sens.tra = MxN matrix to combine electrodes into channels % sens.elecpos = Nx3 matrix with electrode positions % In case sens.tra is not present in the EEG sensor array, the channels % are assumed to be average referenced. % % The following fields are optional % sens.type = string with the MEG or EEG acquisition system, see FT_SENSTYPE % 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. 'T', 'fT' or 'fT/cm' % sens.fid = structure with fiducial information % % Revision history: % % (2011v2/latest) The chantype and chanunit have been added for MEG. % % (2011v1) To facilitate determining the position of channels (e.g. for plotting) % in case of balanced MEG or bipolar EEG, an explicit distinction has been made % between chanpos+chanori and coilpos+coilori (for MEG) and chanpos and elecpos % (for EEG). The pnt and ori fields are removed % % (2010) Added support for bipolar or otherwise more complex linear combinations % of EEG electrodes using sens.tra, similar to MEG. % % (2009) Noice reduction has been added for MEG systems in the balance field. % % (2006) The optional fields sens.type and sens.unit were added. % % (2003) The initial version was defined, which looked like this for EEG % sens.pnt = Mx3 matrix with electrode positions % sens.label = Mx1 cell-array with channel labels % and like this for MEG % sens.pnt = Nx3 matrix with coil positions % sens.ori = Nx3 matrix with coil orientations % sens.tra = MxN matrix to combine coils into channels % sens.label = Mx1 cell-array with channel labels % % See also FT_READ_SENS, FT_SENSTYPE, FT_CHANTYPE, FT_APPLY_MONTAGE, CTF2GRAD, FIF2GRAD, % BTI2GRAD, YOKOGAWA2GRAD, ITAB2GRAD % Copyright (C) 2011, Robert Oostenveld & Jan-Mathijs Schoffelen % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_datatype_sens.m 7248 2012-12-21 11:37:13Z roboos $ % 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}; end % get the optional input arguments, which should be specified as key-value pairs version = ft_getopt(varargin, 'version', 'latest'); if strcmp(version, 'latest') version = '2011v2'; end if isempty(sens) return; end switch version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case '2011v2' % 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 % there are many cases which deal with either eeg or meg ismeg = ft_senstype(sens, 'meg'); 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, 'channel', 'all'); % 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, 'channel', 'all'); % 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 % FIXME for EEG we have not yet figured out how to deal with this end end if ~isfield(sens, 'chanunit') || all(strcmp(sens.chanunit, 'unknown')) if ismeg sens.chanunit = ft_chanunit(sens); else % FIXME for EEG we have not yet figured out how to deal with this end end if ~isfield(sens, 'unit') sens = ft_convert_units(sens); 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 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 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
philippboehmsturm/antx-master
avw_img_read.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/avw_img_read.m
29,199
utf_8
be1e5b74cfdcf9acc49582896e9fadec
function [ avw, machine ] = avw_img_read(fileprefix,IMGorient,machine,verbose) % avw_img_read - read Analyze format data image (*.img) % % [ avw, machine ] = avw_img_read(fileprefix,[orient],[machine],[verbose]) % % fileprefix - a string, the filename without the .img extension % % orient - read a specified orientation, integer values: % % '', use header history orient field % 0, transverse unflipped (LAS*) % 1, coronal unflipped (LA*S) % 2, sagittal unflipped (L*AS) % 3, transverse flipped (LPS*) % 4, coronal flipped (LA*I) % 5, sagittal flipped (L*AI) % % where * follows the slice dimension and letters indicate +XYZ % orientations (L left, R right, A anterior, P posterior, % I inferior, & S superior). % % Some files may contain data in the 3-5 orientations, but this % is unlikely. For more information about orientation, see the % documentation at the end of this .m file. See also the % AVW_FLIP function for orthogonal reorientation. % % machine - a string, see machineformat in fread for details. % The default here is 'ieee-le' but the routine % will automatically switch between little and big % endian to read any such Analyze header. It % reports the appropriate machine format and can % return the machine value. % % verbose - the default is to output processing information to the command % window. If verbose = 0, this will not happen. % % Returned values: % % avw.hdr - a struct with image data parameters. % avw.img - a 3D matrix of image data (double precision). % % A returned 3D matrix will correspond with the % default ANALYZE coordinate system, which % is Left-handed: % % X-Y plane is Transverse % X-Z plane is Coronal % Y-Z plane is Sagittal % % X axis runs from patient right (low X) to patient Left (high X) % Y axis runs from posterior (low Y) to Anterior (high Y) % Z axis runs from inferior (low Z) to Superior (high Z) % % The function can read a 4D Analyze volume, but only if it is in the % axial unflipped orientation. % % See also: avw_hdr_read (called by this function), % avw_view, avw_write, avw_img_write, avw_flip % % $Revision: 7123 $ $Date: 2009/01/14 09:24:45 $ % Licence: GNU GPL, no express or implied warranties % History: 05/2002, [email protected] % The Analyze format is copyright % (c) Copyright, 1986-1995 % Biomedical Imaging Resource, Mayo Foundation % 01/2003, [email protected] % - adapted for matlab v5 % - revised all orientation information and handling % after seeking further advice from AnalyzeDirect.com % 03/2003, [email protected] % - adapted for -ve pixdim values (non standard Analyze) % 07/2004, [email protected], added ability to % read volumes with dimensionality greather than 3. % a >3D volume cannot be flipped. and error is thrown if a volume of % greater than 3D (ie, avw.hdr.dime.dim(1) > 3) requests a data flip % (ie, avw.hdr.hist.orient ~= 0 ). i pulled the transfer of read-in % data (tmp) to avw.img out of any looping mechanism. looping is not % necessary as the data is already in its correct orientation. using % 'reshape' rather than looping should be faster but, more importantly, % it allows the reading in of N-D volumes. See lines 270-280. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist('IMGorient','var'), IMGorient = ''; end if ~exist('machine','var'), machine = 'ieee-le'; end if ~exist('verbose','var'), verbose = 1; end if isempty(IMGorient), IMGorient = ''; end if isempty(machine), machine = 'ieee-le'; end if isempty(verbose), verbose = 1; end if ~exist('fileprefix','var'), msg = sprintf('...no input fileprefix - see help avw_img_read\n\n'); error(msg); end if findstr('.hdr',fileprefix), fileprefix = strrep(fileprefix,'.hdr',''); end if findstr('.img',fileprefix), fileprefix = strrep(fileprefix,'.img',''); end % MAIN % Read the file header [ avw, machine ] = avw_hdr_read(fileprefix,machine,verbose); avw = read_image(avw,IMGorient,machine,verbose); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ avw ] = read_image(avw,IMGorient,machine,verbose) fid = fopen(sprintf('%s.img',avw.fileprefix),'r',machine); if fid < 0, msg = sprintf('...cannot open file %s.img\n\n',avw.fileprefix); error(msg); end if verbose, ver = '[$Revision: 7123 $]'; fprintf('\nAVW_IMG_READ [v%s]\n',ver(12:16)); tic; end % short int bitpix; /* Number of bits per pixel; 1, 8, 16, 32, or 64. */ % short int datatype /* Datatype for this image set */ % /*Acceptable values for datatype are*/ % #define DT_NONE 0 % #define DT_UNKNOWN 0 /*Unknown data type*/ % #define DT_BINARY 1 /*Binary ( 1 bit per voxel)*/ % #define DT_UNSIGNED_CHAR 2 /*Unsigned character ( 8 bits per voxel)*/ % #define DT_SIGNED_SHORT 4 /*Signed short (16 bits per voxel)*/ % #define DT_SIGNED_INT 8 /*Signed integer (32 bits per voxel)*/ % #define DT_FLOAT 16 /*Floating point (32 bits per voxel)*/ % #define DT_COMPLEX 32 /*Complex (64 bits per voxel; 2 floating point numbers)/* % #define DT_DOUBLE 64 /*Double precision (64 bits per voxel)*/ % #define DT_RGB 128 /*A Red-Green-Blue datatype*/ % #define DT_ALL 255 /*Undocumented*/ switch double(avw.hdr.dime.bitpix), case 1, precision = 'bit1'; case 8, precision = 'uchar'; case 16, precision = 'int16'; case 32, if isequal(avw.hdr.dime.datatype, 8), precision = 'int32'; else precision = 'single'; end case 64, precision = 'double'; otherwise, precision = 'uchar'; if verbose, fprintf('...precision undefined in header, using ''uchar''\n'); end end % read the whole .img file into matlab (faster) if verbose, fprintf('...reading %s Analyze %s image format.\n',machine,precision); end fseek(fid,0,'bof'); % adjust for matlab version ver = version; ver = str2num(ver(1)); if ver < 6, tmp = fread(fid,inf,sprintf('%s',precision)); else, tmp = fread(fid,inf,sprintf('%s=>double',precision)); end fclose(fid); % Update the global min and max values avw.hdr.dime.glmax = max(double(tmp)); avw.hdr.dime.glmin = min(double(tmp)); %--------------------------------------------------------------- % Now partition the img data into xyz % --- first figure out the size of the image % short int dim[ ]; /* Array of the image dimensions */ % % dim[0] Number of dimensions in database; usually 4. % dim[1] Image X dimension; number of pixels in an image row. % dim[2] Image Y dimension; number of pixel rows in slice. % dim[3] Volume Z dimension; number of slices in a volume. % dim[4] Time points; number of volumes in database. PixelDim = double(avw.hdr.dime.dim(2)); RowDim = double(avw.hdr.dime.dim(3)); SliceDim = double(avw.hdr.dime.dim(4)); TimeDim = double(avw.hdr.dime.dim(5)); PixelSz = double(avw.hdr.dime.pixdim(2)); RowSz = double(avw.hdr.dime.pixdim(3)); SliceSz = double(avw.hdr.dime.pixdim(4)); TimeSz = double(avw.hdr.dime.pixdim(5)); % ---- NON STANDARD ANALYZE... % Some Analyze files have been found to set -ve pixdim values, eg % the MNI template avg152T1_brain in the FSL etc/standard folder, % perhaps to indicate flipped orientation? If so, this code below % will NOT handle the flip correctly! if PixelSz < 0, warning('X pixdim < 0 !!! resetting to abs(avw.hdr.dime.pixdim(2))'); PixelSz = abs(PixelSz); avw.hdr.dime.pixdim(2) = single(PixelSz); end if RowSz < 0, warning('Y pixdim < 0 !!! resetting to abs(avw.hdr.dime.pixdim(3))'); RowSz = abs(RowSz); avw.hdr.dime.pixdim(3) = single(RowSz); end if SliceSz < 0, warning('Z pixdim < 0 !!! resetting to abs(avw.hdr.dime.pixdim(4))'); SliceSz = abs(SliceSz); avw.hdr.dime.pixdim(4) = single(SliceSz); end % ---- END OF NON STANDARD ANALYZE % --- check the orientation specification and arrange img accordingly if ~isempty(IMGorient), if ischar(IMGorient), avw.hdr.hist.orient = uint8(str2num(IMGorient)); else avw.hdr.hist.orient = uint8(IMGorient); end end, if isempty(avw.hdr.hist.orient), msg = [ '...unspecified avw.hdr.hist.orient, using default 0\n',... ' (check image and try explicit IMGorient option).\n']; fprintf(msg); avw.hdr.hist.orient = uint8(0); end % --- check if the orientation is to be flipped for a volume with more % --- than 3 dimensions. this logic is currently unsupported so throw % --- an error. volumes of any dimensionality may be read in *only* as % --- unflipped, ie, avw.hdr.hist.orient == 0 if ( TimeDim > 1 ) && (avw.hdr.hist.orient ~= 0 ), msg = [ 'ERROR: This volume has more than 3 dimensions *and* ', ... 'requires flipping the data. Flipping is not supported ', ... 'for volumes with dimensionality greater than 3. Set ', ... 'avw.hdr.hist.orient = 0 and flip your volume after ', ... 'calling this function' ]; msg = sprintf( '%s (%s).', msg, mfilename ); error( msg ); end switch double(avw.hdr.hist.orient), case 0, % transverse unflipped % orient = 0: The primary orientation of the data on disk is in the % transverse plane relative to the object scanned. Most commonly, the fastest % moving index through the voxels that are part of this transverse image would % span the right-left extent of the structure imaged, with the next fastest % moving index spanning the posterior-anterior extent of the structure. This % 'orient' flag would indicate to Analyze that this data should be placed in % the X-Y plane of the 3D Analyze Coordinate System, with the Z dimension % being the slice direction. % For the 'transverse unflipped' type, the voxels are stored with % Pixels in 'x' axis (varies fastest) - from patient right to left % Rows in 'y' axis - from patient posterior to anterior % Slices in 'z' axis - from patient inferior to superior if verbose, fprintf('...reading axial unflipped orientation\n'); end % -- This code will handle nD files dims = double( avw.hdr.dime.dim(2:end) ); % replace dimensions of 0 with 1 to be used in reshape idx = find( dims == 0 ); dims( idx ) = 1; avw.img = reshape( tmp, dims ); % -- The code above replaces this % avw.img = zeros(PixelDim,RowDim,SliceDim); % % n = 1; % x = 1:PixelDim; % for z = 1:SliceDim, % for y = 1:RowDim, % % load Y row of X values into Z slice avw.img % avw.img(x,y,z) = tmp(n:n+(PixelDim-1)); % n = n + PixelDim; % end % end % no need to rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim case 1, % coronal unflipped % orient = 1: The primary orientation of the data on disk is in the coronal % plane relative to the object scanned. Most commonly, the fastest moving % index through the voxels that are part of this coronal image would span the % right-left extent of the structure imaged, with the next fastest moving % index spanning the inferior-superior extent of the structure. This 'orient' % flag would indicate to Analyze that this data should be placed in the X-Z % plane of the 3D Analyze Coordinate System, with the Y dimension being the % slice direction. % For the 'coronal unflipped' type, the voxels are stored with % Pixels in 'x' axis (varies fastest) - from patient right to left % Rows in 'z' axis - from patient inferior to superior % Slices in 'y' axis - from patient posterior to anterior if verbose, fprintf('...reading coronal unflipped orientation\n'); end avw.img = zeros(PixelDim,SliceDim,RowDim); n = 1; x = 1:PixelDim; for y = 1:SliceDim, for z = 1:RowDim, % load Z row of X values into Y slice avw.img avw.img(x,y,z) = tmp(n:n+(PixelDim-1)); n = n + PixelDim; end end % rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim avw.hdr.dime.dim(2:4) = int16([PixelDim,SliceDim,RowDim]); avw.hdr.dime.pixdim(2:4) = single([PixelSz,SliceSz,RowSz]); case 2, % sagittal unflipped % orient = 2: The primary orientation of the data on disk is in the sagittal % plane relative to the object scanned. Most commonly, the fastest moving % index through the voxels that are part of this sagittal image would span the % posterior-anterior extent of the structure imaged, with the next fastest % moving index spanning the inferior-superior extent of the structure. This % 'orient' flag would indicate to Analyze that this data should be placed in % the Y-Z plane of the 3D Analyze Coordinate System, with the X dimension % being the slice direction. % For the 'sagittal unflipped' type, the voxels are stored with % Pixels in 'y' axis (varies fastest) - from patient posterior to anterior % Rows in 'z' axis - from patient inferior to superior % Slices in 'x' axis - from patient right to left if verbose, fprintf('...reading sagittal unflipped orientation\n'); end avw.img = zeros(SliceDim,PixelDim,RowDim); n = 1; y = 1:PixelDim; % posterior to anterior (fastest) for x = 1:SliceDim, % right to left (slowest) for z = 1:RowDim, % inferior to superior % load Z row of Y values into X slice avw.img avw.img(x,y,z) = tmp(n:n+(PixelDim-1)); n = n + PixelDim; end end % rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim avw.hdr.dime.dim(2:4) = int16([SliceDim,PixelDim,RowDim]); avw.hdr.dime.pixdim(2:4) = single([SliceSz,PixelSz,RowSz]); %-------------------------------------------------------------------------------- % Orient values 3-5 have the second index reversed in order, essentially % 'flipping' the images relative to what would most likely become the vertical % axis of the displayed image. %-------------------------------------------------------------------------------- case 3, % transverse/axial flipped % orient = 3: The primary orientation of the data on disk is in the % transverse plane relative to the object scanned. Most commonly, the fastest % moving index through the voxels that are part of this transverse image would % span the right-left extent of the structure imaged, with the next fastest % moving index spanning the *anterior-posterior* extent of the structure. This % 'orient' flag would indicate to Analyze that this data should be placed in % the X-Y plane of the 3D Analyze Coordinate System, with the Z dimension % being the slice direction. % For the 'transverse flipped' type, the voxels are stored with % Pixels in 'x' axis (varies fastest) - from patient right to Left % Rows in 'y' axis - from patient anterior to Posterior * % Slices in 'z' axis - from patient inferior to Superior if verbose, fprintf('...reading axial flipped (+Y from Anterior to Posterior)\n'); end avw.img = zeros(PixelDim,RowDim,SliceDim); n = 1; x = 1:PixelDim; for z = 1:SliceDim, for y = RowDim:-1:1, % flip in Y, read A2P file into P2A 3D matrix % load a flipped Y row of X values into Z slice avw.img avw.img(x,y,z) = tmp(n:n+(PixelDim-1)); n = n + PixelDim; end end % no need to rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim case 4, % coronal flipped % orient = 4: The primary orientation of the data on disk is in the coronal % plane relative to the object scanned. Most commonly, the fastest moving % index through the voxels that are part of this coronal image would span the % right-left extent of the structure imaged, with the next fastest moving % index spanning the *superior-inferior* extent of the structure. This 'orient' % flag would indicate to Analyze that this data should be placed in the X-Z % plane of the 3D Analyze Coordinate System, with the Y dimension being the % slice direction. % For the 'coronal flipped' type, the voxels are stored with % Pixels in 'x' axis (varies fastest) - from patient right to Left % Rows in 'z' axis - from patient superior to Inferior* % Slices in 'y' axis - from patient posterior to Anterior if verbose, fprintf('...reading coronal flipped (+Z from Superior to Inferior)\n'); end avw.img = zeros(PixelDim,SliceDim,RowDim); n = 1; x = 1:PixelDim; for y = 1:SliceDim, for z = RowDim:-1:1, % flip in Z, read S2I file into I2S 3D matrix % load a flipped Z row of X values into Y slice avw.img avw.img(x,y,z) = tmp(n:n+(PixelDim-1)); n = n + PixelDim; end end % rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim avw.hdr.dime.dim(2:4) = int16([PixelDim,SliceDim,RowDim]); avw.hdr.dime.pixdim(2:4) = single([PixelSz,SliceSz,RowSz]); case 5, % sagittal flipped % orient = 5: The primary orientation of the data on disk is in the sagittal % plane relative to the object scanned. Most commonly, the fastest moving % index through the voxels that are part of this sagittal image would span the % posterior-anterior extent of the structure imaged, with the next fastest % moving index spanning the *superior-inferior* extent of the structure. This % 'orient' flag would indicate to Analyze that this data should be placed in % the Y-Z plane of the 3D Analyze Coordinate System, with the X dimension % being the slice direction. % For the 'sagittal flipped' type, the voxels are stored with % Pixels in 'y' axis (varies fastest) - from patient posterior to Anterior % Rows in 'z' axis - from patient superior to Inferior* % Slices in 'x' axis - from patient right to Left if verbose, fprintf('...reading sagittal flipped (+Z from Superior to Inferior)\n'); end avw.img = zeros(SliceDim,PixelDim,RowDim); n = 1; y = 1:PixelDim; for x = 1:SliceDim, for z = RowDim:-1:1, % flip in Z, read S2I file into I2S 3D matrix % load a flipped Z row of Y values into X slice avw.img avw.img(x,y,z) = tmp(n:n+(PixelDim-1)); n = n + PixelDim; end end % rearrange avw.hdr.dime.dim or avw.hdr.dime.pixdim avw.hdr.dime.dim(2:4) = int16([SliceDim,PixelDim,RowDim]); avw.hdr.dime.pixdim(2:4) = single([SliceSz,PixelSz,RowSz]); otherwise error('unknown value in avw.hdr.hist.orient, try explicit IMGorient option.'); end if verbose, t=toc; fprintf('...done (%5.2f sec).\n\n',t); end return % This function attempts to read the orientation of the % Analyze file according to the hdr.hist.orient field of the % header. Unfortunately, this field is optional and not % all programs will set it correctly, so there is no guarantee, % that the data loaded will be correctly oriented. If necessary, % experiment with the 'orient' option to read the .img % data into the 3D matrix of avw.img as preferred. % % (Conventions gathered from e-mail with [email protected]) % % 0 transverse unflipped % X direction first, progressing from patient right to left, % Y direction second, progressing from patient posterior to anterior, % Z direction third, progressing from patient inferior to superior. % 1 coronal unflipped % X direction first, progressing from patient right to left, % Z direction second, progressing from patient inferior to superior, % Y direction third, progressing from patient posterior to anterior. % 2 sagittal unflipped % Y direction first, progressing from patient posterior to anterior, % Z direction second, progressing from patient inferior to superior, % X direction third, progressing from patient right to left. % 3 transverse flipped % X direction first, progressing from patient right to left, % Y direction second, progressing from patient anterior to posterior, % Z direction third, progressing from patient inferior to superior. % 4 coronal flipped % X direction first, progressing from patient right to left, % Z direction second, progressing from patient superior to inferior, % Y direction third, progressing from patient posterior to anterior. % 5 sagittal flipped % Y direction first, progressing from patient posterior to anterior, % Z direction second, progressing from patient superior to inferior, % X direction third, progressing from patient right to left. %---------------------------------------------------------------------------- % From ANALYZE documentation... % % The ANALYZE coordinate system has an origin in the lower left % corner. That is, with the subject lying supine, the coordinate % origin is on the right side of the body (x), at the back (y), % and at the feet (z). This means that: % % +X increases from right (R) to left (L) % +Y increases from the back (posterior,P) to the front (anterior, A) % +Z increases from the feet (inferior,I) to the head (superior, S) % % The LAS orientation is the radiological convention, where patient % left is on the image right. The alternative neurological % convention is RAS (also Talairach convention). % % A major advantage of the Analzye origin convention is that the % coordinate origin of each orthogonal orientation (transverse, % coronal, and sagittal) lies in the lower left corner of the % slice as it is displayed. % % Orthogonal slices are numbered from one to the number of slices % in that orientation. For example, a volume (x, y, z) dimensioned % 128, 256, 48 has: % % 128 sagittal slices numbered 1 through 128 (X) % 256 coronal slices numbered 1 through 256 (Y) % 48 transverse slices numbered 1 through 48 (Z) % % Pixel coordinates are made with reference to the slice numbers from % which the pixels come. Thus, the first pixel in the volume is % referenced p(1,1,1) and not at p(0,0,0). % % Transverse slices are in the XY plane (also known as axial slices). % Sagittal slices are in the ZY plane. % Coronal slices are in the ZX plane. % %---------------------------------------------------------------------------- %---------------------------------------------------------------------------- % E-mail from [email protected] % % The 'orient' field in the data_history structure specifies the primary % orientation of the data as it is stored in the file on disk. This usually % corresponds to the orientation in the plane of acquisition, given that this % would correspond to the order in which the data is written to disk by the % scanner or other software application. As you know, this field will contain % the values: % % orient = 0 transverse unflipped % 1 coronal unflipped % 2 sagittal unflipped % 3 transverse flipped % 4 coronal flipped % 5 sagittal flipped % % It would be vary rare that you would ever encounter any old Analyze 7.5 % files that contain values of 'orient' which indicate that the data has been % 'flipped'. The 'flipped flag' values were really only used internal to % Analyze to precondition data for fast display in the Movie module, where the % images were actually flipped vertically in order to accommodate the raster % paint order on older graphics devices. The only cases you will encounter % will have values of 0, 1, or 2. % % As mentioned, the 'orient' flag only specifies the primary orientation of % data as stored in the disk file itself. It has nothing to do with the % representation of the data in the 3D Analyze coordinate system, which always % has a fixed representation to the data. The meaning of the 'orient' values % should be interpreted as follows: % % orient = 0: The primary orientation of the data on disk is in the % transverse plane relative to the object scanned. Most commonly, the fastest % moving index through the voxels that are part of this transverse image would % span the right-left extent of the structure imaged, with the next fastest % moving index spanning the posterior-anterior extent of the structure. This % 'orient' flag would indicate to Analyze that this data should be placed in % the X-Y plane of the 3D Analyze Coordinate System, with the Z dimension % being the slice direction. % % orient = 1: The primary orientation of the data on disk is in the coronal % plane relative to the object scanned. Most commonly, the fastest moving % index through the voxels that are part of this coronal image would span the % right-left extent of the structure imaged, with the next fastest moving % index spanning the inferior-superior extent of the structure. This 'orient' % flag would indicate to Analyze that this data should be placed in the X-Z % plane of the 3D Analyze Coordinate System, with the Y dimension being the % slice direction. % % orient = 2: The primary orientation of the data on disk is in the sagittal % plane relative to the object scanned. Most commonly, the fastest moving % index through the voxels that are part of this sagittal image would span the % posterior-anterior extent of the structure imaged, with the next fastest % moving index spanning the inferior-superior extent of the structure. This % 'orient' flag would indicate to Analyze that this data should be placed in % the Y-Z plane of the 3D Analyze Coordinate System, with the X dimension % being the slice direction. % % Orient values 3-5 have the second index reversed in order, essentially % 'flipping' the images relative to what would most likely become the vertical % axis of the displayed image. % % Hopefully you understand the difference between the indication this 'orient' % flag has relative to data stored on disk and the full 3D Analyze Coordinate % System for data that is managed as a volume image. As mentioned previously, % the orientation of patient anatomy in the 3D Analyze Coordinate System has a % fixed orientation relative to each of the orthogonal axes. This orientation % is completely described in the information that is attached, but the basics % are: % % Left-handed coordinate system % % X-Y plane is Transverse % X-Z plane is Coronal % Y-Z plane is Sagittal % % X axis runs from patient right (low X) to patient left (high X) % Y axis runs from posterior (low Y) to anterior (high Y) % Z axis runs from inferior (low Z) to superior (high Z) % %---------------------------------------------------------------------------- %---------------------------------------------------------------------------- % SPM2 NOTES from spm2 webpage: One thing to watch out for is the image % orientation. The proper Analyze format uses a left-handed co-ordinate % system, whereas Talairach uses a right-handed one. In SPM99, images were % flipped at the spatial normalisation stage (from one co-ordinate system % to the other). In SPM2b, a different approach is used, so that either a % left- or right-handed co-ordinate system is used throughout. The SPM2b % program is told about the handedness that the images are stored with by % the spm_flip_analyze_images.m function and the defaults.analyze.flip % parameter that is specified in the spm_defaults.m file. These files are % intended to be customised for each site. If you previously used SPM99 % and your images were flipped during spatial normalisation, then set % defaults.analyze.flip=1. If no flipping took place, then set % defaults.analyze.flip=0. Check that when using the Display facility % (possibly after specifying some rigid-body rotations) that: % % The top-left image is coronal with the top (superior) of the head displayed % at the top and the left shown on the left. This is as if the subject is viewed % from behind. % % The bottom-left image is axial with the front (anterior) of the head at the % top and the left shown on the left. This is as if the subject is viewed from above. % % The top-right image is sagittal with the front (anterior) of the head at the % left and the top of the head shown at the top. This is as if the subject is % viewed from the left. %----------------------------------------------------------------------------
github
philippboehmsturm/antx-master
read_yokogawa_event.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_yokogawa_event.m
7,112
utf_8
a70ad744018275d54a5de06fbcc9d1ff
function [event] = read_yokogawa_event(filename, varargin) % READ_YOKOGAWA_EVENT reads event information from continuous, % epoched or averaged MEG data that has been generated by the Yokogawa % MEG system and software and allows those events to be used in % combination with FieldTrip. % % Use as % [event] = read_yokogawa_event(filename) % % See also READ_YOKOGAWA_HEADER, READ_YOKOGAWA_DATA % Copyright (C) 2005, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_yokogawa_event.m 7123 2012-12-06 21:21:38Z roboos $ event = []; handles = definehandles; % get the options, the default is set below trigindx = ft_getopt(varargin, 'trigindx'); threshold = ft_getopt(varargin, 'threshold'); detectflank = ft_getopt(varargin, 'detectflank'); % ensure that the required toolbox is on the path if ft_hastoolbox('yokogawa_meg_reader'); % read the dataset header hdr = read_yokogawa_header_new(filename); ch_info = hdr.orig.channel_info.channel; type = [ch_info.type]; % determine the trigger channels (if not specified by the user) if isempty(trigindx) trigindx = find(type==handles.TriggerChannel); end % Use the MEG Reader documentation if more detailed support is % required. if hdr.orig.acq_type==handles.AcqTypeEvokedRaw % read the trigger id from all trials event = getYkgwHdrEvent(filename); % use the standard FieldTrip header for trial events % make an event for each trial as defined in the header for i=1:hdr.nTrials event(end+1).type = 'trial'; event(end ).sample = (i-1)*hdr.nSamples + 1; event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; if ~isempty(value) event(end ).value = event(i).code; end end % Use the MEG Reader documentation if more detailed support is required. elseif hdr.orig.acq_type==handles.AcqTypeEvokedAve % make an event for the average event(1).type = 'average'; event(1).sample = 1; event(1).offset = -hdr.nSamplesPre; event(1).duration = hdr.nSamples; elseif hdr.orig.acq_type==handles.AcqTypeContinuousRaw % the data structure does not contain events, but flank detection on the trigger channel might reveal them % this is done below for all formats end elseif ft_hastoolbox('yokogawa'); % read the dataset header hdr = read_yokogawa_header(filename); % determine the trigger channels (if not specified by the user) if isempty(trigindx) trigindx = find(hdr.orig.channel_info(:,2)==handles.TriggerChannel); end if hdr.orig.acq_type==handles.AcqTypeEvokedRaw % read the trigger id from all trials fid = fopen(filename, 'r'); value = GetMeg160TriggerEventM(fid); fclose(fid); % use the standard FieldTrip header for trial events % make an event for each trial as defined in the header for i=1:hdr.nTrials event(end+1).type = 'trial'; event(end ).sample = (i-1)*hdr.nSamples + 1; event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; if ~isempty(value) event(end ).value = value(i); end end elseif hdr.orig.acq_type==handles.AcqTypeEvokedAve % make an event for the average event(1).type = 'average'; event(1).sample = 1; event(1).offset = -hdr.nSamplesPre; event(1).duration = hdr.nSamples; elseif hdr.orig.acq_type==handles.AcqTypeContinuousRaw % the data structure does not contain events, but flank detection on the trigger channel might reveal them % this is done below for all formats end else error('cannot determine, whether Yokogawa toolbox is present'); end % read the trigger channels and detect the flanks if ~isempty(trigindx) trigger = read_trigger(filename, 'header', hdr, 'denoise', false, 'chanindx', trigindx, 'detectflank', detectflank, 'threshold', threshold); % combine the triggers and the other events event = appendevent(event, trigger); end if isempty(event) warning('no triggers were detected, please specify the "trigindx" option'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles; handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.eegchannel_ch_no = []; handles.sqd.eegchannel_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
philippboehmsturm/antx-master
read_4d_hdr.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_4d_hdr.m
25,611
utf_8
77cce2d47b4c91e12a33138b871a54d0
function [header] = read_4d_hdr(datafile, configfile) % hdr=READ_4D_HDR(datafile, configfile) % Collects the required Fieldtrip header data from the data file 'filename' % and the associated 'config' file for that data. % % Adapted from the MSI>>Matlab code written by Eugene Kronberg % Copyright (C) 2008-2009, Centre for Cognitive Neuroimaging, Glasgow, Gavin Paterson & J.M.Schoffelen % Copyright (C) 2010-2011, Donders Institute for Brain, Cognition and Behavior, J.M.Schoffelen % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_4d_hdr.m 7238 2012-12-20 19:53:52Z jansch $ %read header if nargin ~= 2 [path, file, ext] = fileparts(datafile); configfile = fullfile(path, 'config'); end if ~isempty(datafile), %always big endian fid = fopen(datafile, 'r', 'b'); if fid == -1 error('Cannot open file %s', datafile); end fseek(fid, 0, 'eof'); header_end = ftell(fid); %last 8 bytes of the pdf is header offset fseek(fid, -8, 'eof'); header_offset = fread(fid,1,'uint64'); %first byte of the header fseek(fid, header_offset, 'bof'); % read header data align_file_pointer(fid) header.header_data.FileType = fread(fid, 1, 'uint16=>uint16'); file_type = char(fread(fid, 5, 'uchar'))'; header.header_data.file_type = file_type(file_type>0); fseek(fid, 1, 'cof'); format = fread(fid, 1, 'int16=>int16'); switch format case 1 header.header_data.Format = 'SHORT'; case 2 header.header_data.Format = 'LONG'; case 3 header.header_data.Format = 'FLOAT'; case 4 header.header_data.Format ='DOUBLE'; end header.header_data.acq_mode = fread(fid, 1, 'uint16=>uint16'); header.header_data.TotalEpochs = fread(fid, 1, 'uint32=>double'); header.header_data.input_epochs = fread(fid, 1, 'uint32=>uint32'); header.header_data.TotalEvents = fread(fid, 1, 'uint32=>uint32'); header.header_data.total_fixed_events = fread(fid, 1, 'uint32=>uint32'); header.header_data.SamplePeriod = fread(fid, 1, 'float32=>float64'); header.header_data.SampleFrequency = 1/header.header_data.SamplePeriod; xaxis_label = char(fread(fid, 16, 'uchar'))'; header.header_data.xaxis_label = xaxis_label(xaxis_label>0); header.header_data.total_processes = fread(fid, 1, 'uint32=>uint32'); header.header_data.TotalChannels = fread(fid, 1, 'uint16=>double'); fseek(fid, 2, 'cof'); header.header_data.checksum = fread(fid, 1, 'int32=>int32'); header.header_data.total_ed_classes = fread(fid, 1, 'uint32=>uint32'); header.header_data.total_associated_files = fread(fid, 1, 'uint16=>uint16'); header.header_data.last_file_index = fread(fid, 1, 'uint16=>uint16'); header.header_data.timestamp = fread(fid, 1, 'uint32=>uint32'); header.header_data.reserved = fread(fid, 20, 'uchar')'; fseek(fid, 4, 'cof'); %read epoch_data for epoch = 1:header.header_data.TotalEpochs; align_file_pointer(fid) header.epoch_data(epoch).pts_in_epoch = fread(fid, 1, 'uint32=>uint32'); header.epoch_data(epoch).epoch_duration = fread(fid, 1, 'float32=>float32'); header.epoch_data(epoch).expected_iti = fread(fid, 1, 'float32=>float32'); header.epoch_data(epoch).actual_iti = fread(fid, 1, 'float32=>float32'); header.epoch_data(epoch).total_var_events = fread(fid, 1, 'uint32=>uint32'); header.epoch_data(epoch).checksum = fread(fid, 1, 'int32=>int32'); header.epoch_data(epoch).epoch_timestamp = fread(fid, 1, 'int32=>int32'); header.epoch_data(epoch).reserved = fread(fid, 28, 'uchar')'; header.header_data.SlicesPerEpoch = double(header.epoch_data(1).pts_in_epoch); %read event data (var_events) for event = 1:header.epoch_data(epoch).total_var_events align_file_pointer(fid) event_name = char(fread(fid, 16, 'uchar'))'; header.epoch_data(epoch).var_event{event}.event_name = event_name(event_name>0); header.epoch_data(epoch).var_event{event}.start_lat = fread(fid, 1, 'float32=>float32'); header.epoch_data(epoch).var_event{event}.end_lat = fread(fid, 1, 'float32=>float32'); header.epoch_data(epoch).var_event{event}.step_size = fread(fid, 1, 'float32=>float32'); header.epoch_data(epoch).var_event{event}.fixed_event = fread(fid, 1, 'uint16=>uint16'); fseek(fid, 2, 'cof'); header.epoch_data(epoch).var_event{event}.checksum = fread(fid, 1, 'int32=>int32'); header.epoch_data(epoch).var_event{event}.reserved = fread(fid, 32, 'uchar')'; fseek(fid, 4, 'cof'); end end %read channel ref data for channel = 1:header.header_data.TotalChannels align_file_pointer(fid) chan_label = (fread(fid, 16, 'uint8=>char'))'; header.channel_data(channel).chan_label = chan_label(chan_label>0); header.channel_data(channel).chan_no = fread(fid, 1, 'uint16=>uint16'); header.channel_data(channel).attributes = fread(fid, 1, 'uint16=>uint16'); header.channel_data(channel).scale = fread(fid, 1, 'float32=>float32'); yaxis_label = char(fread(fid, 16, 'uint8=>char'))'; header.channel_data(channel).yaxis_label = yaxis_label(yaxis_label>0); header.channel_data(channel).valid_min_max = fread(fid, 1, 'uint16=>uint16'); fseek(fid, 6, 'cof'); header.channel_data(channel).ymin = fread(fid, 1, 'float64'); header.channel_data(channel).ymax = fread(fid, 1, 'float64'); header.channel_data(channel).index = fread(fid, 1, 'uint32=>uint32'); header.channel_data(channel).checksum = fread(fid, 1, 'int32=>int32'); header.channel_data(channel).whatisit = char(fread(fid, 4, 'uint8=>char'))'; header.channel_data(channel).reserved = fread(fid, 28, 'uint8')'; end %read event data for event = 1:header.header_data.total_fixed_events align_file_pointer(fid) event_name = char(fread(fid, 16, 'uchar'))'; header.event_data(event).event_name = event_name(event_name>0); header.event_data(event).start_lat = fread(fid, 1, 'float32=>float32'); header.event_data(event).end_lat = fread(fid, 1, 'float32=>float32'); header.event_data(event).step_size = fread(fid, 1, 'float32=>float32'); header.event_data(event).fixed_event = fread(fid, 1, 'uint16=>uint16'); fseek(fid, 2, 'cof'); header.event_data(event).checksum = fread(fid, 1, 'int32=>int32'); header.event_data(event).reserved = fread(fid, 32, 'uchar')'; fseek(fid, 4, 'cof'); end header.header_data.FirstLatency = double(header.event_data(1).start_lat); %experimental: read process information for np = 1:header.header_data.total_processes align_file_pointer(fid) nbytes = fread(fid, 1, 'uint32=>uint32'); fp = ftell(fid); header.process(np).hdr.nbytes = nbytes; type = char(fread(fid, 20, 'uchar'))'; header.process(np).hdr.type = type(type>0); header.process(np).hdr.checksum = fread(fid, 1, 'int32=>int32'); user = char(fread(fid, 32, 'uchar'))'; header.process(np).user = user(user>0); header.process(np).timestamp = fread(fid, 1, 'uint32=>uint32'); fname = char(fread(fid, 32, 'uchar'))'; header.process(np).filename = fname(fname>0); fseek(fid, 28*8, 'cof'); %dont know header.process(np).totalsteps = fread(fid, 1, 'uint32=>uint32'); header.process(np).checksum = fread(fid, 1, 'int32=>int32'); header.process(np).reserved = fread(fid, 32, 'uchar')'; for ns = 1:header.process(np).totalsteps align_file_pointer(fid) nbytes2 = fread(fid, 1, 'uint32=>uint32'); header.process(np).step(ns).hdr.nbytes = nbytes2; type = char(fread(fid, 20, 'uchar'))'; header.process(np).step(ns).hdr.type = type(type>0); %dont know how to interpret the first two header.process(np).step(ns).hdr.checksum = fread(fid, 1, 'int32=>int32'); userblocksize = fread(fid, 1, 'int32=>int32'); %we are at 32 bytes here header.process(np).step(ns).userblocksize = userblocksize; fseek(fid, nbytes2 - 32, 'cof'); if strcmp(header.process(np).step(ns).hdr.type, 'PDF_Weight_Table'), warning('reading in weight table: no warranty that this is correct. it seems to work for the Glasgow 248-magnetometer system. if you have some code yourself, and/or would like to test it on your own data, please contact Jan-Mathijs'); tmpfp = ftell(fid); tmp = fread(fid, 1, 'uint8'); Nchan = fread(fid, 1, 'uint32'); Nref = fread(fid, 1, 'uint32'); for k = 1:Nref name = fread(fid, 17, 'uchar'); %strange number, but seems to be true header.process(np).step(ns).RefChan{k,1} = char(name(name>0))'; end fseek(fid, 152, 'cof'); for k = 1:Nchan name = fread(fid, 17, 'uchar'); header.process(np).step(ns).Chan{k,1} = char(name(name>0))'; end %fseek(fid, 20, 'cof'); %fseek(fid, 4216, 'cof'); header.process(np).step(ns).stuff1 = fread(fid, 4236, 'uint8'); name = fread(fid, 16, 'uchar'); header.process(np).step(ns).Creator = char(name(name>0))'; %some stuff I don't understand yet %fseek(fid, 136, 'cof'); header.process(np).step(ns).stuff2 = fread(fid, 136, 'uint8'); %now something strange is going to happen: the weights are probably little-endian encoded. %here we go: check whether this applies to the whole PDF weight table fp = ftell(fid); fclose(fid); fid = fopen(datafile, 'r', 'l'); fseek(fid, fp, 'bof'); for k = 1:Nchan header.process(np).step(ns).Weights(k,:) = fread(fid, 23, 'float32=>float32')'; fseek(fid, 36, 'cof'); end else if userblocksize < 1e6, %for one reason or another userblocksize can assume strangely high values fseek(fid, userblocksize, 'cof'); end end end end fclose(fid); end %end read header %read config file fid = fopen(configfile, 'r', 'b'); if fid == -1 error('Cannot open config file'); end header.config_data.version = fread(fid, 1, 'uint16=>uint16'); site_name = char(fread(fid, 32, 'uchar'))'; header.config_data.site_name = site_name(site_name>0); dap_hostname = char(fread(fid, 16, 'uchar'))'; header.config_data.dap_hostname = dap_hostname(dap_hostname>0); header.config_data.sys_type = fread(fid, 1, 'uint16=>uint16'); header.config_data.sys_options = fread(fid, 1, 'uint32=>uint32'); header.config_data.supply_freq = fread(fid, 1, 'uint16=>uint16'); header.config_data.total_chans = fread(fid, 1, 'uint16=>uint16'); header.config_data.system_fixed_gain = fread(fid, 1, 'float32=>float32'); header.config_data.volts_per_bit = fread(fid, 1, 'float32=>float32'); header.config_data.total_sensors = fread(fid, 1, 'uint16=>uint16'); header.config_data.total_user_blocks = fread(fid, 1, 'uint16=>uint16'); header.config_data.next_derived_channel_number = fread(fid, 1, 'uint16=>uint16'); fseek(fid, 2, 'cof'); header.config_data.checksum = fread(fid, 1, 'int32=>int32'); header.config_data.reserved = fread(fid, 32, 'uchar=>uchar')'; header.config.Xfm = fread(fid, [4 4], 'double'); %user blocks for ub = 1:header.config_data.total_user_blocks align_file_pointer(fid) header.user_block_data{ub}.hdr.nbytes = fread(fid, 1, 'uint32=>uint32'); type = char(fread(fid, 20, 'uchar'))'; header.user_block_data{ub}.hdr.type = type(type>0); header.user_block_data{ub}.hdr.checksum = fread(fid, 1, 'int32=>int32'); user = char(fread(fid, 32, 'uchar'))'; header.user_block_data{ub}.user = user(user>0); header.user_block_data{ub}.timestamp = fread(fid, 1, 'uint32=>uint32'); header.user_block_data{ub}.user_space_size = fread(fid, 1, 'uint32=>uint32'); header.user_block_data{ub}.reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); user_space_size = double(header.user_block_data{ub}.user_space_size); if strcmp(type(type>0), 'B_weights_used'), %warning('reading in weight table: no warranty that this is correct. it seems to work for the Glasgow 248-magnetometer system. if you have some code yourself, and/or would like to test it on your own data, please contact Jan-Mathijs'); tmpfp = ftell(fid); %read user_block_data weights %there is information in the 4th and 8th byte, these might be related to the settings? version = fread(fid, 1, 'uint32'); header.user_block_data{ub}.version = version; if version==1, Nbytes = fread(fid,1,'uint32'); Nchan = fread(fid,1,'uint32'); Position = fread(fid, 32, 'uchar'); header.user_block_data{ub}.position = char(Position(Position>0))'; fseek(fid,tmpfp+user_space_size - Nbytes*Nchan, 'bof'); Ndigital = floor((Nbytes - 4*2) / 4); Nanalog = 3; %lucky guess? % how to know number of analog weights vs digital weights??? for ch = 1:Nchan % for Konstanz -- comment for others? header.user_block_data{ub}.aweights(ch,:) = fread(fid, [1 Nanalog], 'int16')'; fseek(fid,2,'cof'); % alignment header.user_block_data{ub}.dweights(ch,:) = fread(fid, [1 Ndigital], 'single=>double')'; end fseek(fid, tmpfp, 'bof'); %there is no information with respect to the channels here. %the best guess would be to assume the order identical to the order in header.config.channel_data %for the digital weights it would be the order of the references in that list %for the analog weights I would not know elseif version==2, unknown2 = fread(fid, 1, 'uint32'); Nchan = fread(fid, 1, 'uint32'); Position = fread(fid, 32, 'uchar'); header.user_block_data{ub}.position = char(Position(Position>0))'; fseek(fid, tmpfp+124, 'bof'); Nanalog = fread(fid, 1, 'uint32'); Ndigital = fread(fid, 1, 'uint32'); fseek(fid, tmpfp+204, 'bof'); for k = 1:Nchan Name = fread(fid, 16, 'uchar'); header.user_block_data{ub}.channames{k,1} = char(Name(Name>0))'; end for k = 1:Nanalog Name = fread(fid, 16, 'uchar'); header.user_block_data{ub}.arefnames{k,1} = char(Name(Name>0))'; end for k = 1:Ndigital Name = fread(fid, 16, 'uchar'); header.user_block_data{ub}.drefnames{k,1} = char(Name(Name>0))'; end header.user_block_data{ub}.dweights = fread(fid, [Ndigital Nchan], 'single=>double')'; header.user_block_data{ub}.aweights = fread(fid, [Nanalog Nchan], 'int16')'; fseek(fid, tmpfp, 'bof'); end elseif strcmp(type(type>0), 'B_E_table_used'), %warning('reading in weight table: no warranty that this is correct'); %tmpfp = ftell(fid); %fseek(fid, 4, 'cof'); %there's info here dont know how to interpret %Nx = fread(fid, 1, 'uint32'); %Nchan = fread(fid, 1, 'uint32'); %type = fread(fid, 32, 'uchar'); %don't know whether correct %header.user_block_data{ub}.type = char(type(type>0))'; %fseek(fid, 16, 'cof'); %for k = 1:Nchan % name = fread(fid, 16, 'uchar'); % header.user_block_data{ub}.name{k,1} = char(name(name>0))'; %end elseif strcmp(type(type>0), 'B_COH_Points'), tmpfp = ftell(fid); Ncoil = fread(fid, 1, 'uint32'); N = fread(fid, 1, 'uint32'); coils = fread(fid, [7 Ncoil], 'double'); header.user_block_data{ub}.pnt = coils(1:3,:)'; header.user_block_data{ub}.ori = coils(4:6,:)'; header.user_block_data{ub}.Ncoil = Ncoil; header.user_block_data{ub}.N = N; tmp = fread(fid, (904-288)/8, 'double'); header.user_block_data{ub}.tmp = tmp; %FIXME try to find out what these bytes mean fseek(fid, tmpfp, 'bof'); elseif strcmp(type(type>0), 'b_ccp_xfm_block'), tmpfp = ftell(fid); tmp1 = fread(fid, 1, 'uint32'); %tmp = fread(fid, [4 4], 'double'); %tmp = fread(fid, [4 4], 'double'); %the next part seems to be in little endian format (at least when I tried) tmp = fread(fid, 128, 'uint8'); tmp = uint8(reshape(tmp, [8 16])'); xfm = zeros(4,4); for k = 1:size(tmp,1) xfm(k) = typecast(tmp(k,:), 'double'); if abs(xfm(k))<1e-10 || abs(xfm(k))>1e10, xfm(k) = typecast(fliplr(tmp(k,:)), 'double');end end fseek(fid, tmpfp, 'bof'); %FIXME try to find out why this looks so strange elseif strcmp(type(type>0), 'b_eeg_elec_locs'), %this block contains the digitized coil and electrode positions tmpfp = ftell(fid); Npoints = user_space_size./40; for k = 1:Npoints tmp = fread(fid, 16, 'uchar'); %tmplabel = char(tmp(tmp>47 & tmp<128)'); %stick to plain ASCII % store up until the first space tmplabel = char(tmp(1:max(1,(find(tmp==0,1,'first')-1)))'); %stick to plain ASCII %if strmatch('Coil', tmplabel), % label{k} = tmplabel(1:5); %elseif ismember(tmplabel(1), {'L' 'R' 'C' 'N' 'I'}), % label{k} = tmplabel(1); %else % label{k} = ''; %end label{k} = tmplabel; tmp = fread(fid, 3, 'double'); pnt(k,:) = tmp(:)'; end % post-processing of the labels % it seems the following can happen % - a sequence of L R N C I, i.e. the coordinate system defining landmarks for k = 1:numel(label) firstletter(k) = label{k}(1); end sel = strfind(firstletter, 'LRNCI'); if ~isempty(sel) label{sel} = label{sel}(1); label{sel+1} = label{sel+1}(1); label{sel+2} = label{sel+2}(1); label{sel+3} = label{sel+3}(1); label{sel+4} = label{sel+4}(1); end % - a sequence of coil1...coil5 i.e. the localization coils for k = 1:numel(label) if strncmpi(label{k},'coil',4) label{k} = label{k}(1:5); end end % - something else: EEG electrodes? header.user_block_data{ub}.label = label(:); header.user_block_data{ub}.pnt = pnt; fseek(fid, tmpfp, 'bof'); end fseek(fid, user_space_size, 'cof'); end %channels for ch = 1:header.config_data.total_chans align_file_pointer(fid) name = char(fread(fid, 16, 'uchar'))'; header.config.channel_data(ch).name = name(name>0); %FIXME this is a very dirty fix to get the reading in of continuous headlocalization %correct. At the moment, the numbering of the hmt related channels seems to start with 1000 %which I don't understand, but seems rather nonsensical. chan_no = fread(fid, 1, 'uint16=>uint16'); if chan_no > header.config_data.total_chans, %FIXME fix the number in header.channel_data as well sel = find([header.channel_data.chan_no]== chan_no); if ~isempty(sel), chan_no = ch; header.channel_data(sel).chan_no = chan_no; header.channel_data(sel).chan_label = header.config.channel_data(ch).name; else %does not matter end end header.config.channel_data(ch).chan_no = chan_no; header.config.channel_data(ch).type = fread(fid, 1, 'uint16=>uint16'); header.config.channel_data(ch).sensor_no = fread(fid, 1, 'int16=>int16'); fseek(fid, 2, 'cof'); header.config.channel_data(ch).gain = fread(fid, 1, 'float32=>float32'); header.config.channel_data(ch).units_per_bit = fread(fid, 1, 'float32=>float32'); yaxis_label = char(fread(fid, 16, 'uchar'))'; header.config.channel_data(ch).yaxis_label = yaxis_label(yaxis_label>0); header.config.channel_data(ch).aar_val = fread(fid, 1, 'double'); header.config.channel_data(ch).checksum = fread(fid, 1, 'int32=>int32'); header.config.channel_data(ch).reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); align_file_pointer(fid) header.config.channel_data(ch).device_data.hdr.size = fread(fid, 1, 'uint32=>uint32'); header.config.channel_data(ch).device_data.hdr.checksum = fread(fid, 1, 'int32=>int32'); header.config.channel_data(ch).device_data.hdr.reserved = fread(fid, 32, 'uchar=>uchar')'; switch header.config.channel_data(ch).type case {1, 3}%meg/ref header.config.channel_data(ch).device_data.inductance = fread(fid, 1, 'float32=>float32'); fseek(fid, 4, 'cof'); header.config.channel_data(ch).device_data.Xfm = fread(fid, [4 4], 'double'); header.config.channel_data(ch).device_data.xform_flag = fread(fid, 1, 'uint16=>uint16'); header.config.channel_data(ch).device_data.total_loops = fread(fid, 1, 'uint16=>uint16'); header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); for loop = 1:header.config.channel_data(ch).device_data.total_loops align_file_pointer(fid) header.config.channel_data(ch).device_data.loop_data(loop).position = fread(fid, 3, 'double'); header.config.channel_data(ch).device_data.loop_data(loop).direction = fread(fid, 3, 'double'); header.config.channel_data(ch).device_data.loop_data(loop).radius = fread(fid, 1, 'double'); header.config.channel_data(ch).device_data.loop_data(loop).wire_radius = fread(fid, 1, 'double'); header.config.channel_data(ch).device_data.loop_data(loop).turns = fread(fid, 1, 'uint16=>uint16'); fseek(fid, 2, 'cof'); header.config.channel_data(ch).device_data.loop_data(loop).checksum = fread(fid, 1, 'int32=>int32'); header.config.channel_data(ch).device_data.loop_data(loop).reserved = fread(fid, 32, 'uchar=>uchar')'; end case 2%eeg header.config.channel_data(ch).device_data.impedance = fread(fid, 1, 'float32=>float32'); fseek(fid, 4, 'cof'); header.config.channel_data(ch).device_data.Xfm = fread(fid, [4 4], 'double'); header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; case 4%external header.config.channel_data(ch).device_data.user_space_size = fread(fid, 1, 'uint32=>uint32'); header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); case 5%TRIGGER header.config.channel_data(ch).device_data.user_space_size = fread(fid, 1, 'uint32=>uint32'); header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); case 6%utility header.config.channel_data(ch).device_data.user_space_size = fread(fid, 1, 'uint32=>uint32'); header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); case 7%derived header.config.channel_data(ch).device_data.user_space_size = fread(fid, 1, 'uint32=>uint32'); header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; fseek(fid, 4, 'cof'); case 8%shorted header.config.channel_data(ch).device_data.reserved = fread(fid, 32, 'uchar=>uchar')'; otherwise error('Unknown device type: %d\n', header.config.channel_data(ch).type); end end fclose(fid); %end read config file header.header_data.FileDescriptor = 0; %no obvious field to take this from header.header_data.Events = 1;%no obvious field to take this from header.header_data.EventCodes = 0;%no obvious field to take this from if isfield(header, 'channel_data'), header.ChannelGain = double([header.config.channel_data([header.channel_data.chan_no]).gain]'); header.ChannelUnitsPerBit = double([header.config.channel_data([header.channel_data.chan_no]).units_per_bit]'); %header.Channel = {header.config.channel_data([header.channel_data.chan_no]).name}'; header.Channel = {header.channel_data.chan_label}'; header.Format = header.header_data.Format; end function align_file_pointer(fid) current_position = ftell(fid); if mod(current_position, 8) ~= 0 offset = 8 - mod(current_position,8); fseek(fid, offset, 'cof'); end
github
philippboehmsturm/antx-master
decode_nifti1.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/decode_nifti1.m
2,915
utf_8
32b6ac0b0549062ef13624ad21eb55e2
function H = decode_nifti1(blob) % function H = decode_nifti1(blob) % % Decodes a NIFTI-1 header given as raw 348 bytes (uint8) into a Matlab structure % that matches the C struct defined in nifti1.h, with the only difference that the % variable length arrays "dim" and "pixdim" are cut off to the right size, e.g., the % "dim" entry will only contain the relevant elements: % dim[0..7]={3,64,64,18,x,x,x,x} in C would become dim=[64,64,18] in Matlab. % % WARNING: This function currently ignores endianness !!! % (C) 2010 S.Klanke if class(blob)~='uint8' error 'Bad type for blob' end if length(blob)~=348 error 'Blob must be exactly 348 bytes long' end % see nift1.h for information on structure H = []; magic = char(blob(345:347)); if blob(348)~=0 | magic~='ni1' & magic~='n+1' error 'Not a NIFTI-1 header!'; end H.sizeof_hdr = typecast(blob(1:4),'int32'); H.data_type = cstr2matlab(blob(5:14)); H.db_name = cstr2matlab(blob(15:32)); H.extents = typecast(blob(33:36),'int32'); H.session_error = typecast(blob(37:38),'int16'); H.regular = blob(39); H.dim_info = blob(40); dim = typecast(blob(41:56),'int16'); H.dim = dim(2:dim(1)+1); H.intent_p1 = typecast(blob(57:60),'single'); H.intent_p2 = typecast(blob(61:64),'single'); H.intent_p3 = typecast(blob(65:68),'single'); H.intent_code = typecast(blob(69:70),'int16'); H.datatype = typecast(blob(71:72),'int16'); H.bitpix = typecast(blob(73:74),'int16'); H.slice_start = typecast(blob(75:76),'int16'); pixdim = typecast(blob(77:108),'single'); H.qfac = pixdim(1); H.pixdim = pixdim(2:dim(1)+1); H.vox_offset = typecast(blob(109:112),'single'); H.scl_scope = typecast(blob(113:116),'single'); H.scl_inter = typecast(blob(117:120),'single'); H.slice_end = typecast(blob(121:122),'int16'); H.slice_code = blob(123); H.xyzt_units = blob(124); H.cal_max = typecast(blob(125:128),'single'); H.cal_min = typecast(blob(129:132),'single'); H.slice_duration = typecast(blob(133:136),'single'); H.toffset = typecast(blob(137:140),'single'); H.glmax = typecast(blob(141:144),'int32'); H.glmin = typecast(blob(145:148),'int32'); H.descrip = cstr2matlab(blob(149:228)); H.aux_file = cstr2matlab(blob(229:252)); H.qform_code = typecast(blob(253:254),'int16'); H.sform_code = typecast(blob(255:256),'int16'); quats = typecast(blob(257:280),'single'); H.quatern_b = quats(1); H.quatern_c = quats(2); H.quatern_d = quats(3); H.quatern_x = quats(4); H.quatern_y = quats(5); H.quatern_z = quats(6); trafo = typecast(blob(281:328),'single'); H.srow_x = trafo(1:4); H.srow_y = trafo(5:8); H.srow_z = trafo(9:12); %H.S = [H.srow_x; H.srow_y; H.srow_z; 0 0 0 1]; H.intent_name = cstr2matlab(blob(329:344)); H.magic = magic; function ms = cstr2matlab(cs) if cs(1)==0 ms = ''; else ind = find(cs==0); if isempty(ind) ms = char(cs)'; else ms = char(cs(1:ind(1)-1))'; end end
github
philippboehmsturm/antx-master
read_edf.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_edf.m
14,871
utf_8
f65668521c40899923c7b7feca756f23
function [dat] = read_edf(filename, hdr, begsample, endsample, chanindx) % READ_EDF reads specified samples from an EDF continous datafile % It neglects all trial boundaries as if the data was acquired in % non-continous mode. % % Use as % [hdr] = read_edf(filename); % where % filename name of the datafile, including the .bdf extension % This returns a header structure with the following elements % hdr.Fs sampling frequency % hdr.nChans number of channels % hdr.nSamples number of samples per trial % hdr.nSamplesPre number of pre-trigger samples in each trial % hdr.nTrials number of trials % hdr.label cell-array with labels of each channel % hdr.orig detailled EDF header information % % Or use as % [dat] = read_edf(filename, hdr, begsample, endsample, chanindx); % where % filename name of the datafile, including the .bdf extension % hdr header structure, see above % begsample index of the first sample to read % endsample index of the last sample to read % chanindx index of channels to read (optional, default is all) % This returns a Nchans X Nsamples data matrix % Copyright (C) 2006, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_edf.m 7123 2012-12-06 21:21:38Z roboos $ needhdr = (nargin==1); needevt = (nargin==2); needdat = (nargin>3); if needhdr %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the header, this code is from EEGLAB's openbdf %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FILENAME = filename; % defines Seperator for Subdirectories SLASH='/'; BSLASH=char(92); cname=computer; if cname(1:2)=='PC' SLASH=BSLASH; end; fid=fopen(FILENAME,'r','ieee-le'); if fid<0 fprintf(2,['Error LOADEDF: File ' FILENAME ' not found\n']); return; end; EDF.FILE.FID=fid; EDF.FILE.OPEN = 1; EDF.FileName = FILENAME; PPos=min([max(find(FILENAME=='.')) length(FILENAME)+1]); SPos=max([0 find((FILENAME=='/') | (FILENAME==BSLASH))]); EDF.FILE.Ext = FILENAME(PPos+1:length(FILENAME)); EDF.FILE.Name = FILENAME(SPos+1:PPos-1); if SPos==0 EDF.FILE.Path = pwd; else EDF.FILE.Path = FILENAME(1:SPos-1); end; EDF.FileName = [EDF.FILE.Path SLASH EDF.FILE.Name '.' EDF.FILE.Ext]; H1=char(fread(EDF.FILE.FID,256,'char')'); % EDF.VERSION=H1(1:8); % 8 Byte Versionsnummer %if 0 fprintf(2,'LOADEDF: WARNING Version EDF Format %i',ver); end; EDF.PID = deblank(H1(9:88)); % 80 Byte local patient identification EDF.RID = deblank(H1(89:168)); % 80 Byte local recording identification %EDF.H.StartDate = H1(169:176); % 8 Byte %EDF.H.StartTime = H1(177:184); % 8 Byte EDF.T0=[str2num(H1(168+[7 8])) str2num(H1(168+[4 5])) str2num(H1(168+[1 2])) str2num(H1(168+[9 10])) str2num(H1(168+[12 13])) str2num(H1(168+[15 16])) ]; % Y2K compatibility until year 2090 if EDF.VERSION(1)=='0' if EDF.T0(1) < 91 EDF.T0(1)=2000+EDF.T0(1); else EDF.T0(1)=1900+EDF.T0(1); end; else ; % in a future version, this is hopefully not needed end; EDF.HeadLen = str2num(H1(185:192)); % 8 Byte Length of Header % reserved = H1(193:236); % 44 Byte EDF.NRec = str2num(H1(237:244)); % 8 Byte # of data records EDF.Dur = str2num(H1(245:252)); % 8 Byte # duration of data record in sec EDF.NS = str2num(H1(253:256)); % 8 Byte # of signals EDF.Label = char(fread(EDF.FILE.FID,[16,EDF.NS],'char')'); EDF.Transducer = char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); EDF.PhysDim = char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'); EDF.PhysMin= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.PhysMax= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.DigMin = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.DigMax = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); % check validity of DigMin and DigMax if (length(EDF.DigMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Minimum\n'); EDF.DigMin = -(2^15)*ones(EDF.NS,1); end if (length(EDF.DigMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Maximum\n'); EDF.DigMax = (2^15-1)*ones(EDF.NS,1); end if (any(EDF.DigMin >= EDF.DigMax)) fprintf(2,'Warning OPENEDF: Digital Minimum larger than Maximum\n'); end % check validity of PhysMin and PhysMax if (length(EDF.PhysMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Minimum\n'); EDF.PhysMin = EDF.DigMin; end if (length(EDF.PhysMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Maximum\n'); EDF.PhysMax = EDF.DigMax; end if (any(EDF.PhysMin >= EDF.PhysMax)) fprintf(2,'Warning OPENEDF: Physical Minimum larger than Maximum\n'); EDF.PhysMin = EDF.DigMin; EDF.PhysMax = EDF.DigMax; end EDF.PreFilt= char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); % tmp = fread(EDF.FILE.FID,[8,EDF.NS],'char')'; % samples per data record EDF.SPR = str2num(char(tmp)); % samples per data record fseek(EDF.FILE.FID,32*EDF.NS,0); EDF.Cal = (EDF.PhysMax-EDF.PhysMin)./(EDF.DigMax-EDF.DigMin); EDF.Off = EDF.PhysMin - EDF.Cal .* EDF.DigMin; tmp = find(EDF.Cal < 0); EDF.Cal(tmp) = ones(size(tmp)); EDF.Off(tmp) = zeros(size(tmp)); EDF.Calib=[EDF.Off';(diag(EDF.Cal))]; %EDF.Calib=sparse(diag([1; EDF.Cal])); %EDF.Calib(1,2:EDF.NS+1)=EDF.Off'; EDF.SampleRate = EDF.SPR / EDF.Dur; EDF.FILE.POS = ftell(EDF.FILE.FID); if EDF.NRec == -1 % unknown record size, determine correct NRec fseek(EDF.FILE.FID, 0, 'eof'); endpos = ftell(EDF.FILE.FID); EDF.NRec = floor((endpos - EDF.FILE.POS) / (sum(EDF.SPR) * 2)); fseek(EDF.FILE.FID, EDF.FILE.POS, 'bof'); H1(237:244)=sprintf('%-8i',EDF.NRec); % write number of records end; EDF.Chan_Select=(EDF.SPR==max(EDF.SPR)); for k=1:EDF.NS if EDF.Chan_Select(k) EDF.ChanTyp(k)='N'; else EDF.ChanTyp(k)=' '; end; if findstr(upper(EDF.Label(k,:)),'ECG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EKG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EEG') EDF.ChanTyp(k)='E'; elseif findstr(upper(EDF.Label(k,:)),'EOG') EDF.ChanTyp(k)='O'; elseif findstr(upper(EDF.Label(k,:)),'EMG') EDF.ChanTyp(k)='M'; end; end; EDF.AS.spb = sum(EDF.SPR); % Samples per Block bi=[0;cumsum(EDF.SPR)]; idx=[];idx2=[]; for k=1:EDF.NS, idx2=[idx2, (k-1)*max(EDF.SPR)+(1:EDF.SPR(k))]; end; maxspr=max(EDF.SPR); idx3=zeros(EDF.NS*maxspr,1); for k=1:EDF.NS, idx3(maxspr*(k-1)+(1:maxspr))=bi(k)+ceil((1:maxspr)'/maxspr*EDF.SPR(k));end; %EDF.AS.bi=bi; EDF.AS.IDX2=idx2; %EDF.AS.IDX3=idx3; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert the header to Fieldtrip-style %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if all(EDF.SampleRate==EDF.SampleRate(1)) hdr.Fs = EDF.SampleRate(1); hdr.nChans = EDF.NS; hdr.label = cellstr(EDF.Label); % it is continuous data, therefore append all records in one trial hdr.nSamples = EDF.Dur * EDF.SampleRate(1); hdr.nSamplesPre = 0; hdr.nTrials = EDF.NRec; hdr.orig = EDF; elseif all(EDF.SampleRate(1:end-1)==EDF.SampleRate(1)) % only the last channel has a deviant sampling frequency % this is the case for EGI recorded datasets that have been converted % to EDF+, in which case the annotation channel is the last chansel = find(EDF.SampleRate==EDF.SampleRate(1)); % continue with the subset of channels that has a consistent sampling frequency hdr.Fs = EDF.SampleRate(chansel(1)); hdr.nChans = length(chansel); warning('Skipping "%s" as continuous data channel because of inconsistent sampling frequency (%g Hz)', deblank(EDF.Label(end,:)), EDF.SampleRate(end)); hdr.label = cellstr(EDF.Label); hdr.label = hdr.label(chansel); % it is continuous data, therefore append all records in one trial hdr.nSamples = EDF.Dur * EDF.SampleRate(chansel(1)); hdr.nSamplesPre = 0; hdr.nTrials = EDF.NRec; hdr.orig = EDF; % this will be used on subsequent reading of data hdr.orig.chansel = chansel; hdr.orig.annotation = find(strcmp(cellstr(hdr.orig.Label), 'EDF Annotations')); else % select the sampling rate that results in the most channels [a, b, c] = unique(EDF.SampleRate); for i=1:length(a) chancount(i) = sum(c==i); end [dum, indx] = max(chancount); chansel = find(EDF.SampleRate == a(indx)); % continue with the subset of channels that has a consistent sampling frequency hdr.Fs = EDF.SampleRate(chansel(1)); hdr.nChans = length(chansel); hdr.label = cellstr(EDF.Label); hdr.label = hdr.label(chansel); % it is continuous data, therefore append all records in one trial hdr.nSamples = EDF.Dur * EDF.SampleRate(chansel(1)); hdr.nSamplesPre = 0; hdr.nTrials = EDF.NRec; hdr.orig = EDF; % this will be used on subsequent reading of data hdr.orig.chansel = chansel; hdr.orig.annotation = find(strcmp(cellstr(hdr.orig.Label), 'EDF Annotations')); warning('channels with different sampling rate not supported, using a subselection of %d channels at %f Hz', length(hdr.label), hdr.Fs); end % return the header dat = hdr; elseif needdat || needevt %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % retrieve the original header EDF = hdr.orig; % determine whether a subset of channels should be used % which is the case if channels have a variable sampling frequency variableFs = isfield(EDF, 'chansel'); if variableFs && needevt % read the annotation channel, not the data channels EDF.chansel = EDF.annotation; begsample = 1; endsample = EDF.SampleRate(end)*EDF.NRec*EDF.Dur; end if variableFs epochlength = EDF.Dur * EDF.SampleRate(EDF.chansel(1)); % in samples for the selected channel blocksize = sum(EDF.Dur * EDF.SampleRate); % in samples for all channels chanoffset = EDF.Dur * EDF.SampleRate; chanoffset = cumsum([0; chanoffset(1:end-1)]); % use a subset of channels nchans = length(EDF.chansel); else epochlength = EDF.Dur * EDF.SampleRate(1); % in samples for a single channel blocksize = sum(EDF.Dur * EDF.SampleRate); % in samples for all channels % use all channels nchans = EDF.NS; end % determine the trial containing the begin and end sample begepoch = floor((begsample-1)/epochlength) + 1; endepoch = floor((endsample-1)/epochlength) + 1; nepochs = endepoch - begepoch + 1; if nargin<5 chanindx = 1:nchans; end % allocate memory to hold the data dat = zeros(length(chanindx),nepochs*epochlength); % read and concatenate all required data epochs for i=begepoch:endepoch if variableFs % only a subset of channels with consistent sampling frequency is read offset = EDF.HeadLen + (i-1)*blocksize*2; % in bytes % read the complete data block buf = readLowLevel(filename, offset, blocksize); % see below in subfunction for j=1:length(chanindx) % cut out the part that corresponds with a single channel dat(j,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf((1:epochlength) + chanoffset(EDF.chansel(chanindx(j)))); end elseif length(chanindx)==1 % this is more efficient if only one channel has to be read, e.g. the status channel offset = EDF.HeadLen + (i-1)*blocksize*2; % in bytes offset = offset + (chanindx-1)*epochlength*2; % read the data for a single channel buf = readLowLevel(filename, offset, epochlength); % see below in subfunction dat(:,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf; else % read the data from all channels, subsequently select the desired channels offset = EDF.HeadLen + (i-1)*blocksize*2; % in bytes % read the complete data block buf = readLowLevel(filename, offset, blocksize); % see below in subfunction buf = reshape(buf, epochlength, nchans); dat(:,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf(:,chanindx)'; end end % select the desired samples begsample = begsample - (begepoch-1)*epochlength; % correct for the number of bytes that were skipped endsample = endsample - (begepoch-1)*epochlength; % correct for the number of bytes that were skipped dat = dat(:, begsample:endsample); % Calibrate the data if variableFs calib = diag(EDF.Cal(EDF.chansel(chanindx))); else calib = diag(EDF.Cal(chanindx)); end if length(chanindx)>1 % using a sparse matrix speeds up the multiplication dat = sparse(calib) * dat; else % in case of one channel the sparse multiplication would result in a sparse array dat = calib * dat; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for reading the 16 bit values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function buf = readLowLevel(filename, offset, numwords) if offset < 2*1024^2 % use the external mex file, only works for <2GB buf = read_16bit(filename, offset, numwords); else % use plain matlab, thanks to Philip van der Broek fp = fopen(filename,'r','ieee-le'); status = fseek(fp, offset, 'bof'); if status error(['failed seeking ' filename]); end [buf,num] = fread(fp,numwords,'bit16=>double'); fclose(fp); if (num<numwords) error(['failed reading ' filename]); return end end
github
philippboehmsturm/antx-master
yokogawa2grad.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/yokogawa2grad.m
7,205
utf_8
c61a324e8fd20060380618a1f0760a72
function grad = yokogawa2grad(hdr) % YOKOGAWA2GRAD converts the position and weights of all coils that % compromise a gradiometer system into a structure that can be used % by FieldTrip. This implementation uses the old "yokogawa" toolbox. % % See also CTF2GRAD, BTI2GRAD, FIF2GRAD, MNE2GRAD, ITAB2GRAD, % FT_READ_SENS, FT_READ_HEADER % Copyright (C) 2005-2008, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: yokogawa2grad.m 7123 2012-12-06 21:21:38Z roboos $ if ~ft_hastoolbox('yokogawa') error('cannot determine whether Yokogawa toolbox is present'); end if isfield(hdr, 'label') label = hdr.label; % keep for later use end if isfield(hdr, 'orig') hdr = hdr.orig; % use the original header, not the FieldTrip header end % The "channel_info" contains % 1 channel number, zero offset % 2 channel type, type of gradiometer % 3 position x (in m) % 4 position y (in m) % 5 position z (in m) % 6 orientation of first coil (theta in deg) % 7 orientation of first coil (phi in deg) % 8 orientation from the 1st to 2nd coil for gradiometer (theta in deg) % 9 orientation from the 1st to 2nd coil for gradiometer (phi in deg) % 10 coil size (in m) % 11 baseline (in m) handles = definehandles; isgrad = (hdr.channel_info(:,2)==handles.AxialGradioMeter | ... hdr.channel_info(:,2)==handles.PlannerGradioMeter | ... hdr.channel_info(:,2)==handles.MagnetoMeter | ... hdr.channel_info(:,2)==handles.RefferenceAxialGradioMeter); % reference channels are excluded because the positions are not specified % hdr.channel_info(:,2)==handles.RefferencePlannerGradioMeter % hdr.channel_info(:,2)==handles.RefferenceMagnetoMeter isgrad_handles = hdr.channel_info(isgrad,2); ismag = (isgrad_handles(:)==handles.MagnetoMeter | isgrad_handles(:)==handles.RefferenceMagnetoMeter); grad.coilpos = hdr.channel_info(isgrad,3:5)*100; % cm grad.unit = 'cm'; % Get orientation of the 1st coil ori_1st = hdr.channel_info(find(isgrad),[6 7]); % polar to x,y,z coordinates ori_1st = ... [sin(ori_1st(:,1)/180*pi).*cos(ori_1st(:,2)/180*pi) ... sin(ori_1st(:,1)/180*pi).*sin(ori_1st(:,2)/180*pi) ... cos(ori_1st(:,1)/180*pi)]; grad.coilori = ori_1st; % Get orientation from the 1st to 2nd coil for gradiometer ori_1st_to_2nd = hdr.channel_info(find(isgrad),[8 9]); % polar to x,y,z coordinates ori_1st_to_2nd = ... [sin(ori_1st_to_2nd(:,1)/180*pi).*cos(ori_1st_to_2nd(:,2)/180*pi) ... sin(ori_1st_to_2nd(:,1)/180*pi).*sin(ori_1st_to_2nd(:,2)/180*pi) ... cos(ori_1st_to_2nd(:,1)/180*pi)]; % Get baseline baseline = hdr.channel_info(isgrad,size(hdr.channel_info,2)); % Define the location and orientation of 2nd coil info = hdr.channel_info(isgrad,2); for i=1:sum(isgrad) if (info(i) == handles.AxialGradioMeter || info(i) == handles.RefferenceAxialGradioMeter ) grad.coilpos(i+sum(isgrad),:) = [grad.coilpos(i,:)+ori_1st(i,:)*baseline(i)*100]; grad.coilori(i+sum(isgrad),:) = -ori_1st(i,:); elseif (info(i) == handles.PlannerGradioMeter || info(i) == handles.RefferencePlannerGradioMeter) grad.coilpos(i+sum(isgrad),:) = [grad.coilpos(i,:)+ori_1st_to_2nd(i,:)*baseline(i)*100]; grad.coilori(i+sum(isgrad),:) = -ori_1st(i,:); else grad.coilpos(i+sum(isgrad),:) = [0 0 0]; grad.coilori(i+sum(isgrad),:) = [0 0 0]; end end % Define the pair of 1st and 2nd coils for each gradiometer grad.tra = repmat(diag(ones(1,size(grad.coilpos,1)/2),0),1,2); % for mangetometers change tra as there is no second coil if any(ismag) sz_pnt = size(grad.coilpos,1)/2; % create logical variable not_2nd_coil = ([diag(zeros(sz_pnt),0)' ismag']~=0); grad.tra(ismag,not_2nd_coil) = 0; end % the gradiometer labels should be consistent with the channel labels in % read_yokogawa_header, the predefined list of channel names in ft_senslabel % and with ft_channelselection % ONLY consistent with read_yokogawa_header as NO FIXED relation between % channel index and type of channel exists for Yokogawa systems. Therefore % all have individual label sequences: No useful support in ft_senslabel possible if ~isempty(label) grad.label = label(isgrad); else % this is only backup, if something goes wrong above. label = cell(size(isgrad)); for i=1:length(label) label{i} = sprintf('AG%03d', i); end grad.label = label(isgrad); end grad.unit = 'cm'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % ????4.0mm???????` handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % ???a15.5mm???~?? handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % ????12.0mm???????` handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
philippboehmsturm/antx-master
read_erplabheader.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_erplabheader.m
2,048
utf_8
c72fab70eaf79706e1f1f452bc50692a
% read_erplabheader() - import ERPLAB dataset files % % Usage: % >> header = read_erplabheader(filename); % % Inputs: % filename - [string] file name % % Outputs: % header - FILEIO toolbox type structure % % Modified from read_eeglabheader %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_erplabheader(filename) if nargin < 1 help read_erplabheader; return; end; if ~isstruct(filename) load('-mat', filename); else ERP = filename; end; header.Fs = ERP.srate; header.nChans = ERP.nchan; header.nSamples = ERP.pnts; header.nSamplesPre = -ERP.xmin*ERP.srate; header.nTrials = ERP.nbin; try header.label = { ERP.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( ERP.chanlocs ) if isfield(ERP.chanlocs(i), 'X') && ~isempty(ERP.chanlocs(i).X) header.elec.label{ind, 1} = ERP.chanlocs(i).labels; % this channel has a position header.elec.pnt(ind,1) = ERP.chanlocs(i).X; header.elec.pnt(ind,2) = ERP.chanlocs(i).Y; header.elec.pnt(ind,3) = ERP.chanlocs(i).Z; ind = ind+1; end; end; header.orig = ERP;
github
philippboehmsturm/antx-master
write_plexon_nex.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/write_plexon_nex.m
9,546
utf_8
c3e00b18b8d0d194f3b0231301f3945f
function write_plexon_nex(filename, nex) % WRITE_PLEXON_NEX writes a Plexon *.nex file, which is a file % containing action-potential (spike) timestamps and waveforms (spike % channels), event timestamps (event channels), and continuous variable % data (continuous A/D channels). % % Use as % write_plexon_nex(filename, nex); % % The data structure should contain % nex.hdr.FileHeader.Frequency = TimeStampFreq % nex.hdr.VarHeader.Type = type, 5 for continuous % nex.hdr.VarHeader.Name = label, padded to length 64 % nex.hdr.VarHeader.WFrequency = sampling rate of continuous channel % nex.var.dat = data % nex.var.ts = timestamps % % See also READ_PLEXON_NEX, READ_PLEXON_PLX, READ_PLEXON_DDT % Copyright (C) 2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: write_plexon_nex.m 7123 2012-12-06 21:21:38Z roboos $ % get the optional arguments, these are all required % FirstTimeStamp = ft_getopt(varargin, 'FirstTimeStamp'); % TimeStampFreq = ft_getopt(varargin, 'TimeStampFreq'); hdr = nex.hdr; UVtoMV = 1/1000; switch hdr.VarHeader.Type case 5 dat = nex.var.dat; % this is in microVolt buf = zeros(size(dat), 'int16'); nchans = size(dat,1); nsamples = size(dat,2); nwaves = 1; % only one continuous datasegment is supported if length(hdr.VarHeader)~=nchans error('incorrect number of channels'); end % convert the data from floating point into int16 values % each channel gets its own optimal calibration factor for varlop=1:nchans ADMaxValue = double(intmax('int16')); ADMaxUV = max(abs(dat(varlop,:))); % this is in microVolt ADMaxMV = ADMaxUV/1000; % this is in miliVolt if isa(dat, 'int16') % do not rescale data that is already 16 bit MVtoAD = 1; elseif ADMaxMV==0 % do not rescale the data if the data is zero MVtoAD = 1; elseif ADMaxMV>0 % rescale the data so that it fits into the 16 bits with as little loss as possible MVtoAD = ADMaxValue / ADMaxMV; end buf(varlop,:) = int16(double(dat) * UVtoMV * MVtoAD); % remember the calibration value, it should be stored in the variable header ADtoMV(varlop) = 1/MVtoAD; end dat = buf; clear buf; case 3 dat = nex.var.dat; % this is in microVolt nchans = 1; % only one channel is supported nsamples = size(dat,1); nwaves = size(dat,2); if length(hdr.VarHeader)~=nchans error('incorrect number of channels'); end % convert the data from floating point into int16 values ADMaxValue = double(intmax('int16')); ADMaxUV = max(abs(dat(:))); % this is in microVolt ADMaxMV = ADMaxUV/1000; % this is in miliVolt if isa(dat, 'int16') % do not rescale data that is already 16 bit MVtoAD = 1; elseif ADMaxMV==0 % do not rescale the data if the data is zero MVtoAD = 1; elseif ADMaxMV>0 % rescale the data so that it fits into the 16 bits with as little loss as possible MVtoAD = ADMaxValue / ADMaxMV; end dat = int16(double(dat) * UVtoMV * MVtoAD); % remember the calibration value, it should be stored in the variable header ADtoMV = 1/MVtoAD; otherwise error('unsupported data type') end % switch type % determine the first and last timestamp ts = nex.var.ts; ts_beg = min(ts); ts_end = 0; % FIXME fid = fopen(filename, 'wb', 'ieee-le'); % write the file header write_NexFileHeader; % write the variable headers for varlop=1:nchans write_NexVarHeader; end % write the variable data for varlop=1:nchans write_NexVarData; end fclose(fid); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nested function for writing the details %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function write_NexFileHeader % prepare the two char buffers buf1 = padstr('$Id: write_plexon_nex.m 7123 2012-12-06 21:21:38Z roboos $', 256); buf2 = char(zeros(1, 256)); % write the stuff to the file fwrite(fid, 'NEX1' , 'char'); % NexFileHeader = string NEX1 fwrite(fid, 100 , 'int32'); % Version = version fwrite(fid, buf1 , 'char'); % Comment = comment, 256 bytes fwrite(fid, hdr.FileHeader.Frequency, 'double'); % Frequency = timestamped freq. - tics per second fwrite(fid, ts_beg, 'int32'); % Beg = usually 0, minimum of all the timestamps in the file fwrite(fid, ts_end, 'int32'); % End = maximum timestamp + 1 fwrite(fid, nchans, 'int32'); % NumVars = number of variables in the first batch fwrite(fid, 0 , 'int32'); % NextFileHeader = position of the next file header in the file, not implemented yet fwrite(fid, buf2 , 'char'); % Padding = future expansion end % of the nested function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nested function for writing the details %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function write_NexVarHeader filheadersize = 544; varheadersize = 208; offset = filheadersize + nchans*varheadersize + (varlop-1)*nsamples; calib = ADtoMV(varlop); % prepare the two char buffers buf1 = padstr(hdr.VarHeader(varlop).Name, 64); buf2 = char(zeros(1, 68)); % write the continuous variable to the file fwrite(fid, hdr.VarHeader.Type, 'int32'); % Type = 0 - neuron, 1 event, 2- interval, 3 - waveform, 4 - pop. vector, 5 - continuously recorded fwrite(fid, 100, 'int32'); % Version = 100 fwrite(fid, buf1, 'char'); % Name = variable name, 1x64 char fwrite(fid, offset, 'int32'); % DataOffset = where the data array for this variable is located in the file fwrite(fid, nwaves, 'int32'); % Count = number of events, intervals, waveforms or weights fwrite(fid, 0, 'int32'); % WireNumber = neuron only, not used now fwrite(fid, 0, 'int32'); % UnitNumber = neuron only, not used now fwrite(fid, 0, 'int32'); % Gain = neuron only, not used now fwrite(fid, 0, 'int32'); % Filter = neuron only, not used now fwrite(fid, 0, 'double'); % XPos = neuron only, electrode position in (0,100) range, used in 3D fwrite(fid, 0, 'double'); % YPos = neuron only, electrode position in (0,100) range, used in 3D fwrite(fid, hdr.VarHeader.WFrequency, 'double'); % WFrequency = waveform and continuous vars only, w/f sampling frequency fwrite(fid, calib, 'double'); % ADtoMV = waveform continuous vars only, coeff. to convert from A/D values to Millivolts fwrite(fid, nsamples, 'int32'); % NPointsWave = waveform only, number of points in each wave fwrite(fid, 0, 'int32'); % NMarkers = how many values are associated with each marker fwrite(fid, 0, 'int32'); % MarkerLength = how many characters are in each marker value fwrite(fid, buf2, 'char'); % Padding, 1x68 char end % of the nested function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % nested function for writing the details %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function write_NexVarData switch hdr.VarHeader.Type case 5 % this code only supports one continuous segment index = 0; fwrite(fid, ts , 'int32'); % timestamps, one for each continuous segment fwrite(fid, index , 'int32'); % where to cut the segments, zero offset fwrite(fid, dat(varlop,:) , 'int16'); % data case 3 fwrite(fid, ts , 'int32'); % timestamps, one for each spike fwrite(fid, dat , 'int16'); % waveforms, one for each spike otherwise error('unsupported data type'); end % switch end % of the nested function end % of the primary function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % subfunction for zero padding a char array to fixed length %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function str = padstr(str, num); if length(str)>num str = str(1:num); else str((end+1):num) = 0; end end % of the padstr subfunction
github
philippboehmsturm/antx-master
ft_convert_units.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/ft_convert_units.m
7,014
utf_8
b6713ad4580d1dac67d2d43489f0dc55
function [obj] = ft_convert_units(obj, target) % FT_CONVERT_UNITS changes the geometrical dimension to the specified SI unit. % The units of the input object is determined from the structure field % object.unit, or is estimated based on the spatial extend of the structure, % e.g. a volume conduction model of the head should be approximately 20 cm large. % % Use as % [object] = ft_convert_units(object, target) % % The following input objects are supported % simple dipole position % electrode definition % gradiometer array definition % volume conductor definition % dipole grid definition % anatomical mri % segmented mri % % 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 FT_ESTIMATE_UNITS, FT_READ_VOL, FT_READ_SENS % Copyright (C) 2005-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_convert_units.m 7337 2013-01-16 15:52:00Z johzum $ % 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 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); else tmp(i) = ft_convert_units(obj(i)); end end obj = tmp; 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; 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, '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 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, '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 % compue the scaling factor from the input units to the desired ones scale = scalingfactor(unit, target); % give some information about the conversion fprintf('converting units from ''%s'' to ''%s''\n', unit, target) % volume conductor model if isfield(obj, 'r'), obj.r = scale * obj.r; end if isfield(obj, 'o'), obj.o = scale * obj.o; end if isfield(obj, 'bnd'), for i=1:length(obj.bnd), obj.bnd(i).pnt = scale * obj.bnd(i).pnt; end, end % gradiometer array if isfield(obj, 'pnt1'), obj.pnt1 = scale * obj.pnt1; end if isfield(obj, 'pnt2'), obj.pnt2 = scale * obj.pnt2; end if isfield(obj, 'prj'), obj.prj = scale * obj.prj; end % gradiometer array, electrode array, head shape or dipole grid if isfield(obj, 'pnt'), obj.pnt = scale * obj.pnt; end if isfield(obj, 'chanpos'), obj.chanpos = scale * obj.chanpos; end 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 length(tok)==1 % assume that it is T or so elseif length(tok)==2 % assume that it is T/cm or so obj.tra(i,:) = obj.tra(i,:) / scale; obj.chanunit{i} = [tok{1} '/' target]; 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 % dipole grid if isfield(obj, 'pos'), obj.pos = scale * obj.pos; end % anatomical MRI or functional volume if isfield(obj, 'transform'), H = diag([scale scale scale 1]); obj.transform = H * obj.transform; end if isfield(obj, 'transformorig'), H = diag([scale scale scale 1]); obj.transformorig = H * obj.transformorig; end % remember the unit obj.unit = target; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 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
philippboehmsturm/antx-master
nansum.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/nansum.m
185
utf_8
4859ec062780c478011dd7a8d94684a0
% NANSUM provides a replacement for MATLAB's nanmean. % % For usage see SUM. function y = nansum(x, dim) if nargin == 1 dim = 1; end idx = isnan(x); x(idx) = 0; y = sum(x, dim); end
github
philippboehmsturm/antx-master
ft_datatype.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/ft_datatype.m
7,749
utf_8
975852e96f4caa3ccb50bbbd5f8c5248
function [type, dimord] = ft_datatype(data, desired) % FT_DATATYPE determines the type of data represented in a FieldTrip data % structure and returns a string with raw, freq, timelock source, comp, % spike, source, volume, dip. % % Use as % [type, dimord] = ft_datatype(data) % [status] = ft_datatype(data, desired) % % See also FT_DATATYPE_COMP FT_DATATYPE_FREQ FT_DATATYPE_MVAR % FT_DATATYPE_SEGMENTATION FT_DATATYPE_PARCELLATION FT_DATATYPE_SOURCE % FT_DATATYPE_TIMELOCK FT_DATATYPE_DIP FT_DATATYPE_HEADMODEL % FT_DATATYPE_RAW FT_DATATYPE_SENS FT_DATATYPE_SPIKE FT_DATATYPE_VOLUME % Copyright (C) 2008-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_datatype.m 7123 2012-12-06 21:21:38Z roboos $ % determine the type of input data, this can be raw, freq, timelock, comp, spike, source, volume, dip, segmentation, parcellation israw = isfield(data, 'label') && isfield(data, 'time') && isa(data.time, 'cell') && isfield(data, 'trial') && isa(data.trial, 'cell') && ~isfield(data,'trialtime'); isfreq = (isfield(data, 'label') || isfield(data, 'labelcmb')) && isfield(data, 'freq') && ~isfield(data,'trialtime') && ~isfield(data,'origtrial'); %&& (isfield(data, 'powspctrm') || isfield(data, 'crsspctrm') || isfield(data, 'cohspctrm') || isfield(data, 'fourierspctrm') || isfield(data, 'powcovspctrm')); istimelock = isfield(data, 'label') && isfield(data, 'time') && ~isfield(data, 'freq') && ~isfield(data,'trialtime'); %&& ((isfield(data, 'avg') && isnumeric(data.avg)) || (isfield(data, 'trial') && isnumeric(data.trial) || (isfield(data, 'cov') && isnumeric(data.cov)))); iscomp = isfield(data, 'label') && isfield(data, 'topo') || isfield(data, 'topolabel'); isvolume = isfield(data, 'transform') && isfield(data, 'dim'); issource = isfield(data, 'pos'); isdip = isfield(data, 'dip'); ismvar = isfield(data, 'dimord') && ~isempty(strfind(data.dimord, 'lag')); isfreqmvar = isfield(data, 'freq') && isfield(data, 'transfer'); ischan = isfield(data, 'dimord') && strcmp(data.dimord, 'chan') && ~isfield(data, 'time') && ~isfield(data, 'freq'); issegmentation = check_segmentation(data); isparcellation = check_parcellation(data); if ~isfreq % this applies to a ferq structure from 2003 up to early 2006 isfreq = all(isfield(data, {'foi', 'label', 'dimord'})) && ~isempty(strfind(data.dimord, 'frq')); end % check if it is a spike structure spk_hastimestamp = isfield(data,'label') && isfield(data, 'timestamp') && isa(data.timestamp, 'cell'); spk_hastrials = isfield(data,'label') && isfield(data, 'time') && isa(data.time, 'cell') && isfield(data, 'trial') && isa(data.trial, 'cell') && isfield(data, 'trialtime') && isa(data.trialtime, 'numeric'); spk_hasorig = isfield(data,'origtrial') && isfield(data,'origtime'); % for compatibility isspike = isfield(data, 'label') && (spk_hastimestamp || spk_hastrials || spk_hasorig); % check if it is a sensor array isgrad = isfield(data, 'label') && isfield(data, 'coilpos') && isfield(data, 'chanpos') && isfield(data, 'coilori'); iselec = isfield(data, 'label') && isfield(data, 'elecpos') && isfield(data, 'chanpos'); if iscomp % comp should conditionally go before raw, otherwise the returned ft_datatype will be raw type = 'comp'; elseif israw type = 'raw'; elseif isfreqmvar % freqmvar should conditionally go before freq, otherwise the returned ft_datatype will be freq in the case of frequency mvar data type = 'freqmvar'; elseif isfreq type = 'freq'; elseif ismvar type = 'mvar'; elseif isdip % dip should conditionally go before timelock, otherwise the ft_datatype will be timelock type = 'dip'; elseif istimelock type = 'timelock'; elseif isspike type = 'spike'; elseif issegmentation % a segmentation data structure is a volume data structure, but in general not vice versa % segmentation should conditionally go before volume, otherwise the returned ft_datatype will be volume type = 'segmentation'; elseif isvolume type = 'volume'; elseif isparcellation % a parcellation data structure is a source data structure, but in general not vice versa % parcellation should conditionally go before source, otherwise the returned ft_datatype will be source type = 'parcellation'; elseif issource type = 'source'; elseif ischan % this results from avgovertime/avgoverfreq after timelockstatistics or freqstatistics type = 'chan'; elseif iselec type = 'elec'; elseif isgrad type = 'grad'; else type = 'unknown'; end if nargin>1 % return a boolean value switch desired case 'raw' type = any(strcmp(type, {'raw', 'comp'})); case 'volume' type = any(strcmp(type, {'volume', 'segmentation'})); case 'source' type = any(strcmp(type, {'source', 'parcellation'})); case 'sens' type = any(strcmp(type, {'elec', 'grad'})); otherwise type = strcmp(type, desired); end % switch end if nargout>1 % also return the dimord of the input data if isfield(data, 'dimord') dimord = data.dimord; else dimord = 'unknown'; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [res] = check_segmentation(volume) res = false; if ~isfield(volume, 'dim') return end if isfield(volume, 'pos') return end if any(isfield(volume, {'seg', 'csf', 'white', 'gray', 'skull', 'scalp', 'brain'})) res = true; return end fn = fieldnames(volume); for i=1:length(fn) if isfield(volume, [fn{i} 'label']) res = true; return end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [res] = check_parcellation(source) res = false; if ~isfield(source, 'pos') return end fn = fieldnames(source); fb = false(size(fn)); npos = size(source.pos,1); for i=1:numel(fn) % for each of the fields check whether it might be a logical array with the size of the number of sources tmp = source.(fn{i}); fb(i) = numel(tmp)==npos && islogical(tmp); end if sum(fb)>1 % the presence of multiple logical arrays suggests it is a parcellation res = true; end if res == false % check if source has more D elements check = 0; for i = 1: length(fn) fname = fn{i}; switch fname case 'tri' npos = size(source.tri,1); check = 1; case 'hex' npos = size(source.hex,1); check = 1; case 'tet' npos = size(source.tet,1); check = 1; end end if check == 1 % check if elements are labelled for i=1:numel(fn) tmp = source.(fn{i}); fb(i) = numel(tmp)==npos && islogical(tmp); end if sum(fb)>1 res = true; end end end fn = fieldnames(source); for i=1:length(fn) if isfield(source, [fn{i} 'label']) res = true; return end end
github
philippboehmsturm/antx-master
ft_apply_montage.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/ft_apply_montage.m
13,440
utf_8
ba256ae86f2bc28cc2d9f26098e25236
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 inputor array. The inputor array can subsequently be used for % forward computation and source reconstruction of the data. % % Use as % [sens] = ft_apply_montage(sens, montage, ...) % [data] = ft_apply_montage(data, montage, ...) % [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.labelnew = Mx1 cell-array % montage.labelorg = Nx1 cell-array % % As an example, a bipolar montage could look like this % bipolar.labelorg = {'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 % ]; % % Additional options should be specified in key-value pairs and can be % 'keepunused' string, 'yes' or 'no' (default = 'no') % 'inverse' string, 'yes' or 'no' (default = 'no') % % If the first input is a montage, then the second input montage will be % applied to the first. In effect, the output montage will first do % montage1, then montage2. % % See also FT_READ_SENS, FT_TRANSFORM_SENS % Copyright (C) 2008-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_apply_montage.m 7394 2013-01-23 14:33:30Z jorhor $ % get optional input arguments keepunused = ft_getopt(varargin, 'keepunused', 'no'); inverse = ft_getopt(varargin, 'inverse', 'no'); feedback = ft_getopt(varargin, 'feedback', 'text'); bname = ft_getopt(varargin, 'balancename', ''); if ~isfield(input, 'label') && isfield(input, 'labelnew') % the input data structure is also a montage inputlabel = input.labelnew; else % the input should describe the channel labels inputlabel = input.label; end % check the consistency of the input inputor array or data if ~all(isfield(montage, {'tra', 'labelorg', '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.labelorg) error('the number of channels in the montage is inconsistent'); end if strcmp(inverse, 'yes') % apply the inverse montage, i.e. undo a previously applied montage tmp.labelnew = montage.labelorg; % swap around tmp.labelorg = montage.labelnew; % swap around tmp.tra = full(montage.tra); if rank(tmp.tra) < length(tmp.tra) warning('the linear projection for the montage is not full-rank, the resulting data will have reduced dimensionality'); tmp.tra = pinv(tmp.tra); else tmp.tra = inv(tmp.tra); end montage = tmp; end % use default transfer from sensors to channels if not specified if isfield(input, 'pnt') && ~isfield(input, 'tra') nchan = size(input.pnt,1); input.tra = eye(nchan); elseif isfield(input, 'chanpos') && ~isfield(input, 'tra') nchan = size(input.chanpos,1); input.tra = eye(nchan); end % select and keep the columns that are non-empty, i.e. remove the empty columns selcol = find(~all(montage.tra==0, 1)); montage.tra = montage.tra(:,selcol); montage.labelorg = montage.labelorg(selcol); clear selcol % select and remove the columns corresponding to channels that are not present in the original data remove = setdiff(montage.labelorg, intersect(montage.labelorg, inputlabel)); selcol = match_str(montage.labelorg, remove); % we cannot just remove the colums, all rows that depend on it should also be removed selrow = false(length(montage.labelnew),1); for i=1:length(selcol) selrow = selrow & (montage.tra(:,selcol(i))~=0); end % convert from indices to logical vector selcol = indx2logical(selcol, length(montage.labelorg)); % remove rows and columns montage.labelorg = montage.labelorg(~selcol); montage.labelnew = montage.labelnew(~selrow); montage.tra = montage.tra(~selrow, ~selcol); clear remove selcol selrow i % add columns for the channels that are present in the data but not involved in the montage, and stick to the original order in the data [add, ix] = setdiff(inputlabel, montage.labelorg); add = inputlabel(sort(ix)); m = size(montage.tra,1); n = size(montage.tra,2); k = length(add); if strcmp(keepunused, 'yes') % add the channels that are not rereferenced to the input and output montage.tra((m+(1:k)),(n+(1:k))) = eye(k); montage.labelorg = cat(1, montage.labelorg(:), add(:)); montage.labelnew = cat(1, montage.labelnew(:), add(:)); else % add the channels that are not rereferenced to the input montage only montage.tra(:,(n+(1:k))) = zeros(m,k); montage.labelorg = cat(1, montage.labelorg(:), add(:)); end clear add m n k % determine whether all channels are unique m = size(montage.tra,1); n = size(montage.tra,2); if length(unique(montage.labelnew))~=m error('not all output channels of the montage are unique'); end if length(unique(montage.labelorg))~=n error('not all input channels of the montage are unique'); end % determine whether all channels that have to be rereferenced are available if length(intersect(inputlabel, montage.labelorg))~=length(montage.labelorg) error('not all channels that are required in the montage are available in the data'); end % reorder the columns of the montage matrix [selinput, selmontage] = match_str(inputlabel, montage.labelorg); montage.tra = double(montage.tra(:,selmontage)); montage.labelorg = montage.labelorg(selmontage); % making the tra matrix sparse will speed up subsequent multiplications % but should not result in a sparse matrix if size(montage.tra,1)>1 montage.tra = sparse(montage.tra); end inputtype = 'unknown'; if isfield(input, 'labelorg') && isfield(input, 'labelnew') inputtype = 'montage'; elseif isfield(input, 'tra') inputtype = 'sens'; elseif isfield(input, 'trial') inputtype = 'raw'; elseif isfield(input, 'fourierspctrm') inputtype = 'freq'; 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; 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 sens.chanpos = nan(numel(montage.labelnew),3); %input = rmfield(input, 'chanpos'); end end if isfield(sens, 'chanori') if keepchans sens.chanori = sens.chanori(sel2,:); else sens.chanori = nan(numel(montage.labelnew),3); %input = rmfield(input, 'chanori'); end end sens.label = montage.labelnew; % keep track of the order of the balancing and which one is the current one if strcmp(inverse, 'yes') if isfield(sens, 'balance')% && isfield(sens.balance, 'previous') if isfield(sens.balance, 'previous') && numel(sens.balance.previous)>=1 sens.balance.current = sens.balance.previous{1}; sens.balance.previous = sens.balance.previous(2:end); elseif isfield(sens.balance, 'previous') sens.balance.current = 'none'; sens.balance = rmfield(sens.balance, 'previous'); else sens.balance.current = 'none'; end end elseif ~strcmp(inverse, 'yes') && ~isempty(bname) if isfield(sens, 'balance'), % 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; % 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 elseif strcmp(freq.dimord, 'rpttap_chan_freq_time') siz = size(freq.fourierspctrm); nrpt = siz(1); nchan = siz(2); nfreq = siz(3); ntime = siz(4); output = zeros(nrpt, size(montage.tra,1), nfreq, ntime); for foilop=1:nfreq for toilop = 1:ntime output(:,:,foilop,toilop) = freq.fourierspctrm(:,:,foilop,toilop) * montage.tra'; end end else error('unsupported dimord in frequency data (%s)', freq.dimord); end % replace the Fourier spectrum freq.fourierspctrm = output; freq.label = montage.labelnew; % rename the output variable input = freq; clear freq otherwise error('unrecognized input'); end % switch inputtype % check whether the input contains chantype and/or chanunit and remove these % as they may have been invalidated by the transform (e.g. with megplanar) [sel1, sel2] = match_str(montage.labelnew, inputlabel); keepchans = (length(sel1)==length(montage.labelnew)); if isfield(input, 'chantype') if keepchans % reorder them according to the montage sens.chantype = input.chantype(sel2,:); else input = rmfield(input, 'chantype'); end end if isfield(input, 'chanunit') if keepchans % reorder them according to the montage sens.chanunit = input.chanunit(sel2,:); else input = rmfield(input, 'chanunit'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % HELPER FUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function y = indx2logical(x, n) y = false(1,n); y(x) = true;
github
philippboehmsturm/antx-master
read_erplabdata.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_erplabdata.m
2,110
utf_8
60380c3ce12bbfd85b4dd554bdc0ae20
% read_erplabdata() - import ERPLAB dataset files % % Usage: % >> dat = read_erplabdata(filename); % % Inputs: % filename - [string] file name % % Optional inputs: % 'begtrial' - [integer] first trial to read % 'endtrial' - [integer] last trial to read % 'chanindx' - [integer] list with channel indices to read % 'header' - FILEIO structure header % % Outputs: % dat - data over the specified range % % Modified from read_eeglabheader %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function dat = read_erplabdata(filename, varargin); if nargin < 1 help read_erplabdata; return; end; header = ft_getopt(varargin, 'header'); begsample = ft_getopt(varargin, 'begsample'); endsample = ft_getopt(varargin, 'endsample'); begtrial = ft_getopt(varargin, 'begtrial'); endtrial = ft_getopt(varargin, 'endtrial'); chanindx = ft_getopt(varargin, 'chanindx'); if isempty(header) header = read_erplabheader(filename); end dat = header.orig.bindata; if isempty(begtrial), begtrial = 1; end; if isempty(endtrial), endtrial = header.nTrials; end; if isempty(begsample), begsample = 1; end; if isempty(endsample), endsample = header.nSamples; end; dat = dat(:,begsample:endsample,begtrial:endtrial); if ~isempty(chanindx) % select the desired channels dat = dat(chanindx,:,:); end
github
philippboehmsturm/antx-master
read_biosemi_bdf.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_biosemi_bdf.m
10,824
utf_8
c299fc321e8529aed582e5e6e746d24f
function dat = read_biosemi_bdf(filename, hdr, begsample, endsample, chanindx); % READ_BIOSEMI_BDF reads specified samples from a BDF continous datafile % It neglects all trial boundaries as if the data was acquired in % non-continous mode. % % Use as % [hdr] = read_biosemi_bdf(filename); % where % filename name of the datafile, including the .bdf extension % This returns a header structure with the following elements % hdr.Fs sampling frequency % hdr.nChans number of channels % hdr.nSamples number of samples per trial % hdr.nSamplesPre number of pre-trigger samples in each trial % hdr.nTrials number of trials % hdr.label cell-array with labels of each channel % hdr.orig detailled EDF header information % % Or use as % [dat] = read_biosemi_bdf(filename, hdr, begsample, endsample, chanindx); % where % filename name of the datafile, including the .bdf extension % hdr header structure, see above % begsample index of the first sample to read % endsample index of the last sample to read % chanindx index of channels to read (optional, default is all) % This returns a Nchans X Nsamples data matrix % Copyright (C) 2006, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_biosemi_bdf.m 7123 2012-12-06 21:21:38Z roboos $ if nargin==1 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the header, this code is from EEGLAB's openbdf %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FILENAME = filename; % defines Seperator for Subdirectories SLASH='/'; BSLASH=char(92); cname=computer; if cname(1:2)=='PC' SLASH=BSLASH; end; fid=fopen(FILENAME,'r','ieee-le'); if fid<0 fprintf(2,['Error LOADEDF: File ' FILENAME ' not found\n']); return; end; EDF.FILE.FID=fid; EDF.FILE.OPEN = 1; EDF.FileName = FILENAME; PPos=min([max(find(FILENAME=='.')) length(FILENAME)+1]); SPos=max([0 find((FILENAME=='/') | (FILENAME==BSLASH))]); EDF.FILE.Ext = FILENAME(PPos+1:length(FILENAME)); EDF.FILE.Name = FILENAME(SPos+1:PPos-1); if SPos==0 EDF.FILE.Path = pwd; else EDF.FILE.Path = FILENAME(1:SPos-1); end; EDF.FileName = [EDF.FILE.Path SLASH EDF.FILE.Name '.' EDF.FILE.Ext]; H1=char(fread(EDF.FILE.FID,256,'char')'); % EDF.VERSION=H1(1:8); % 8 Byte Versionsnummer %if 0 fprintf(2,'LOADEDF: WARNING Version EDF Format %i',ver); end; EDF.PID = deblank(H1(9:88)); % 80 Byte local patient identification EDF.RID = deblank(H1(89:168)); % 80 Byte local recording identification %EDF.H.StartDate = H1(169:176); % 8 Byte %EDF.H.StartTime = H1(177:184); % 8 Byte EDF.T0=[str2num(H1(168+[7 8])) str2num(H1(168+[4 5])) str2num(H1(168+[1 2])) str2num(H1(168+[9 10])) str2num(H1(168+[12 13])) str2num(H1(168+[15 16])) ]; % Y2K compatibility until year 2090 if EDF.VERSION(1)=='0' if EDF.T0(1) < 91 EDF.T0(1)=2000+EDF.T0(1); else EDF.T0(1)=1900+EDF.T0(1); end; else ; % in a future version, this is hopefully not needed end; EDF.HeadLen = str2num(H1(185:192)); % 8 Byte Length of Header % reserved = H1(193:236); % 44 Byte EDF.NRec = str2num(H1(237:244)); % 8 Byte # of data records EDF.Dur = str2num(H1(245:252)); % 8 Byte # duration of data record in sec EDF.NS = str2num(H1(253:256)); % 8 Byte # of signals EDF.Label = char(fread(EDF.FILE.FID,[16,EDF.NS],'char')'); EDF.Transducer = char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); EDF.PhysDim = char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'); EDF.PhysMin= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.PhysMax= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.DigMin = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.DigMax = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); % check validity of DigMin and DigMax if (length(EDF.DigMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Minimum\n'); EDF.DigMin = -(2^15)*ones(EDF.NS,1); end if (length(EDF.DigMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Maximum\n'); EDF.DigMax = (2^15-1)*ones(EDF.NS,1); end if (any(EDF.DigMin >= EDF.DigMax)) fprintf(2,'Warning OPENEDF: Digital Minimum larger than Maximum\n'); end % check validity of PhysMin and PhysMax if (length(EDF.PhysMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Minimum\n'); EDF.PhysMin = EDF.DigMin; end if (length(EDF.PhysMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Maximum\n'); EDF.PhysMax = EDF.DigMax; end if (any(EDF.PhysMin >= EDF.PhysMax)) fprintf(2,'Warning OPENEDF: Physical Minimum larger than Maximum\n'); EDF.PhysMin = EDF.DigMin; EDF.PhysMax = EDF.DigMax; end EDF.PreFilt= char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); % tmp = fread(EDF.FILE.FID,[8,EDF.NS],'char')'; % samples per data record EDF.SPR = str2num(char(tmp)); % samples per data record fseek(EDF.FILE.FID,32*EDF.NS,0); EDF.Cal = (EDF.PhysMax-EDF.PhysMin)./(EDF.DigMax-EDF.DigMin); EDF.Off = EDF.PhysMin - EDF.Cal .* EDF.DigMin; tmp = find(EDF.Cal < 0); EDF.Cal(tmp) = ones(size(tmp)); EDF.Off(tmp) = zeros(size(tmp)); EDF.Calib=[EDF.Off';(diag(EDF.Cal))]; %EDF.Calib=sparse(diag([1; EDF.Cal])); %EDF.Calib(1,2:EDF.NS+1)=EDF.Off'; EDF.SampleRate = EDF.SPR / EDF.Dur; EDF.FILE.POS = ftell(EDF.FILE.FID); if EDF.NRec == -1 % unknown record size, determine correct NRec fseek(EDF.FILE.FID, 0, 'eof'); endpos = ftell(EDF.FILE.FID); EDF.NRec = floor((endpos - EDF.FILE.POS) / (sum(EDF.SPR) * 2)); fseek(EDF.FILE.FID, EDF.FILE.POS, 'bof'); H1(237:244)=sprintf('%-8i',EDF.NRec); % write number of records end; EDF.Chan_Select=(EDF.SPR==max(EDF.SPR)); for k=1:EDF.NS if EDF.Chan_Select(k) EDF.ChanTyp(k)='N'; else EDF.ChanTyp(k)=' '; end; if findstr(upper(EDF.Label(k,:)),'ECG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EKG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EEG') EDF.ChanTyp(k)='E'; elseif findstr(upper(EDF.Label(k,:)),'EOG') EDF.ChanTyp(k)='O'; elseif findstr(upper(EDF.Label(k,:)),'EMG') EDF.ChanTyp(k)='M'; end; end; EDF.AS.spb = sum(EDF.SPR); % Samples per Block %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert the header to Fieldtrip-style %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(EDF.SampleRate~=EDF.SampleRate(1)) error('channels with different sampling rate not supported'); end hdr.Fs = EDF.SampleRate(1); hdr.nChans = EDF.NS; hdr.label = cellstr(EDF.Label); % it is continuous data, therefore append all records in one trial hdr.nTrials = 1; hdr.nSamples = EDF.NRec * EDF.Dur * EDF.SampleRate(1); hdr.nSamplesPre = 0; hdr.orig = EDF; % return the header dat = hdr; else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % retrieve the original header EDF = hdr.orig; % determine the trial containing the begin and end sample epochlength = EDF.Dur * EDF.SampleRate(1); begepoch = floor((begsample-1)/epochlength) + 1; endepoch = floor((endsample-1)/epochlength) + 1; nepochs = endepoch - begepoch + 1; nchans = EDF.NS; if nargin<5 chanindx = 1:nchans; end % allocate memory to hold the data dat = zeros(length(chanindx),nepochs*epochlength); % read and concatenate all required data epochs for i=begepoch:endepoch offset = EDF.HeadLen + (i-1)*epochlength*nchans*3; if length(chanindx)==1 % this is more efficient if only one channel has to be read, e.g. the status channel offset = offset + (chanindx-1)*epochlength*3; buf = readLowLevel(filename, offset, epochlength); % see below in subfunction dat(:,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf; else % read the data from all channels and then select the desired channels buf = readLowLevel(filename, offset, epochlength*nchans); % see below in subfunction buf = reshape(buf, epochlength, nchans); dat(:,((i-begepoch)*epochlength+1):((i-begepoch+1)*epochlength)) = buf(:,chanindx)'; end end % select the desired samples begsample = begsample - (begepoch-1)*epochlength; % correct for the number of bytes that were skipped endsample = endsample - (begepoch-1)*epochlength; % correct for the number of bytes that were skipped dat = dat(:, begsample:endsample); % Calibrate the data calib = diag(EDF.Cal(chanindx)); if length(chanindx)>1 % using a sparse matrix speeds up the multiplication dat = sparse(calib) * dat; else % in case of one channel the sparse multiplication would result in a sparse array dat = calib * dat; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION for reading the 24 bit values %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function buf = readLowLevel(filename, offset, numwords); if offset < 2*1024^3 % use the external mex file, only works for <2GB buf = read_24bit(filename, offset, numwords); % this would be the only difference between the bdf and edf implementation % buf = read_16bit(filename, offset, numwords); else % use plain matlab, thanks to Philip van der Broek fp = fopen(filename,'r','ieee-le'); status = fseek(fp, offset, 'bof'); if status error(['failed seeking ' filename]); end [buf,num] = fread(fp,numwords,'bit24=>double'); fclose(fp); if (num<numwords) error(['failed opening ' filename]); return end end
github
philippboehmsturm/antx-master
read_ctf_ascii.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_ctf_ascii.m
3,218
utf_8
ed3ebfd532e8ac61a7237dede21d739b
function [file] = read_ctf_ascii(filename); % READ_CTF_ASCII reads general data from an CTF configuration file % % The file should be formatted like % Group % { % item1 : value1a value1b value1c % item2 : value2a value2b value2c % item3 : value3a value3b value3c % item4 : value4a value4b value4c % } % % This fileformat structure is used in % params.avg % default.hdm % multiSphere.hdm % processing.cfg % and maybe for other files as well. % Copyright (C) 2003, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_ctf_ascii.m 7123 2012-12-06 21:21:38Z roboos $ fid = fopen(filename, 'r'); if fid==-1 error(sprintf('could not open file %s', filename)); end line = ''; while ischar(line) line = cleanline(fgetl(fid)); if isempty(line) || (length(line)==1 && all(line==-1)) continue end % the line is not empty, which means that we have encountered a chunck of information subline = cleanline(fgetl(fid)); % read the { subline = cleanline(fgetl(fid)); % read the first item while isempty(findstr(subline, '}')) if ~isempty(subline) [item, value] = strtok(subline, ':'); value(1) = ' '; % remove the : value = strtrim(value); item = strtrim(item); % turn warnings off ws = warning('off'); % the item name should be a real string, otherwise I cannot put it into the structure if strcmp(sprintf('%d', str2num(deblank(item))), deblank(item)) % add something to the start of the string to distinguish it from a number item = ['item_' item]; end % the value can be either a number or a string, and is put into the structure accordingly if isempty(str2num(value)) % the value appears to be a string eval(sprintf('file.%s.%s = [ ''%s'' ];', line, item, value)); else % the value appears to be a number or a list of numbers eval(sprintf('file.%s.%s = [ %s ];', line, item, value)); end % revert to previous warning state warning(ws); end subline = cleanline(fgetl(fid)); % read the first item end end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function line = cleanline(line) if isempty(line) || (length(line)==1 && all(line==-1)) return end comment = findstr(line, '//'); if ~isempty(comment) line(min(comment):end) = ' '; end line = strtrim(line);
github
philippboehmsturm/antx-master
read_mpi_dap.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_mpi_dap.m
7,085
utf_8
a51b5774d3dc46b048015b2b12e95e76
function [dap] = read_mpi_dap(filename) % READ_MPI_DAP read the analog channels from a DAP file % and returns the values in microvolt (uV) % % Use as % [dap] = read_mpi_dap(filename) % Copyright (C) 2005-2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_mpi_dap.m 7123 2012-12-06 21:21:38Z roboos $ fid = fopen(filename, 'rb', 'ieee-le'); % read the file header filehdr = readheader(fid); analog = {}; analoghdr = {}; analogsweephdr = {}; spike = {}; spikehdr = {}; spikesweephdr = {}; W = filehdr.nexps; S = filehdr.nsweeps; for w=1:filehdr.nexps % read the experiment header exphdr{w} = readheader(fid); if filehdr.nanalog if filehdr.analogmode==-1 % record mode for s=1:filehdr.nsweeps % read the analogsweepheader analogsweephdr{s} = readheader(fid); for j=1:filehdr.nanalog % read the analog header analoghdr{w,s,j} = readheader(fid); % read the analog data analog{w,s,j} = fread(fid, analoghdr{w,s,j}.datasize, 'int16'); % calibrate the analog data analog{w,s,j} = analog{w,s,j} * 2.5/2048; end end % for s=1:S elseif filehdr.analogmode==0 % average mode s = 1; for j=1:filehdr.nanalog % read the analog header analoghdr{w,s,j} = readheader(fid); % read the analog data analog{w,s,j} = fread(fid, analoghdr{w,s,j}.datasize, 'int16'); % calibrate the analog data analog{w,s,j} = analog{w,s,j} * 2.5/2048; end else error('unknown analog mode'); end end if filehdr.nspike for s=1:filehdr.nsweeps spikesweephdr{s} = readheader(fid); for j=1:filehdr.nspike % read the spike header spikehdr{w,s,j} = readheader(fid); % read the spike data spike{w,s,j} = fread(fid, spikehdr{w,s,j}.datasize, 'int16'); end end % for s=1:S end end % for w=1:W dap.filehdr = filehdr; dap.exphdr = exphdr; dap.analogsweephdr = analogsweephdr; dap.analoghdr = analoghdr; dap.analog = analog; dap.spikesweephdr = spikesweephdr; dap.spikehdr = spikehdr; dap.spike = spike; fclose(fid); return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = readheader(fid); % determine the header type, header size and data size hdr.headertype = fread(fid, 1, 'uchar'); dummy = fread(fid, 1, 'uchar'); hdr.headersize = fread(fid, 1, 'int16') + 1; % expressed in words, not bytes hdr.datasize = fread(fid, 1, 'int16'); % expressed in words, not bytes % read the header details switch hdr.headertype case 1 % fileheader % fprintf('fileheader at %d\n' ,ftell(fid)-6); dummy = fread(fid, 1, 'uchar')'; % 6 hdr.nexps = fread(fid, 1, 'uchar')'; % 7 hdr.progname = fread(fid, 7, 'uchar')'; % 8-14 hdr.version = fread(fid, 1, 'uchar')'; % 15 hdr.progversion = fread(fid, 2, 'uchar')'; % 16-17 hdr.fileversion = fread(fid, 2, 'uchar')'; % 18-19 hdr.date = fread(fid, 1, 'int16'); % 20-21 hdr.time = fread(fid, 1, 'int16'); % 22-23 hdr.nanalog = fread(fid, 1, 'uint8'); % 24 hdr.nspike = fread(fid, 1, 'uint8'); % 25 hdr.nbins = fread(fid, 1, 'int16'); % 26-27 hdr.binwidth = fread(fid, 1, 'int16'); % 28-29 dummy = fread(fid, 1, 'int16'); % 30-31 hdr.nsweeps = fread(fid, 1, 'int16'); % 32-33 hdr.analogmode = fread(fid, 1, 'uchar')'; % 34 "0 for average, -1 for record" dummy = fread(fid, 1, 'uchar')'; % 35 dummy = fread(fid, 1, 'int16'); % 36-37 dummy = fread(fid, 1, 'int16'); % 38-39 dummy = fread(fid, 1, 'int16'); % 40-41 case 65 % expheader % fprintf('expheader at %d\n' ,ftell(fid)-6); hdr.time = fread(fid, 1, 'int16'); % 6-7 hdr.parallel = fread(fid, 1, 'int16'); % 8-9 hdr.id = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 case 129 % analogchannelheader % fprintf('analogchannelheader at %d\n' ,ftell(fid)-6); dummy = fread(fid, 1, 'int16'); % 6-7 hdr.channum = fread(fid, 1, 'uchar'); % 8 dummy = fread(fid, 1, 'uchar'); % 9 dummy = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 case 161 % spikechannelheader % fprintf('spikechannelheader at %d\n' ,ftell(fid)-6); dummy = fread(fid, 1, 'int16'); % 6-7 hdr.channum = fread(fid, 1, 'uchar'); % 8 dummy = fread(fid, 1, 'uchar'); % 9 dummy = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 case 137 % analogsweepheader % fprintf('analogsweepheader at %d\n' ,ftell(fid)-6); hdr.sweepnum = fread(fid, 1, 'int16'); % 6-7 hdr.parallel = fread(fid, 1, 'int16'); % 8-9 dummy = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 case 169 % spikesweepheader % fprintf('spikesweepheader at %d\n' ,ftell(fid)-6); hdr.sweepnum = fread(fid, 1, 'int16'); % 6-7 hdr.parallel = fread(fid, 1, 'int16'); % 8-9 dummy = fread(fid, 1, 'int16'); % 10-11 dummy = fread(fid, 1, 'int16'); % 12-13 dummy = fread(fid, 1, 'int16'); % 14-15 dummy = fread(fid, 1, 'int16'); % 16-17 otherwise error(sprintf('unsupported format for header (%d)', hdr.headertype)); end
github
philippboehmsturm/antx-master
read_neuralynx_bin.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_neuralynx_bin.m
6,705
utf_8
1851b52bfcf664aadb50e417bd3ab74b
function [dat] = read_neuralynx_bin(filename, begsample, endsample); % READ_NEURALYNX_BIN % % Use as % hdr = read_neuralynx_bin(filename) % or % dat = read_neuralynx_bin(filename, begsample, endsample) % % This is not a formal Neuralynx file format, but at the % F.C. Donders Centre we use it in conjunction with Neuralynx, % SPIKESPLITTING and SPIKEDOWNSAMPLE. % % The first version of this file format contained in the first 8 bytes the % channel label as string. Subsequently it contained 32 bit integer values. % % The second version of this file format starts with 8 bytes describing (as % a space-padded string) the data type. The channel label is contained in % the filename as dataset.chanlabel.bin. % % The third version of this file format starts with 7 bytes describing (as % a zero-padded string) the data type, followed by the 8th byte which % describes the downscaling for the 8 and 16 bit integer representations. % The downscaling itself is represented as uint8 and should be interpreted as % the number of bits to shift. The channel label is contained in the % filename as dataset.chanlabel.bin. % Copyright (C) 2007-2008, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_neuralynx_bin.m 7123 2012-12-06 21:21:38Z roboos $ needhdr = (nargin==1); needdat = (nargin>=2); % this is used for backward compatibility oldformat = false; % the first 8 bytes contain the header fid = fopen(filename, 'rb', 'ieee-le'); magic = fread(fid, 8, 'uint8=>char')'; % the header describes the format of the subsequent samples subtype = []; if strncmp(magic, 'uint8', length('uint8')) format = 'uint8'; samplesize = 1; elseif strncmp(magic, 'int8', length('int8')) format = 'int8'; samplesize = 1; elseif strncmp(magic, 'uint16', length('uint16')) format = 'uint16'; samplesize = 2; elseif strncmp(magic, 'int16', length('int16')) format = 'int16'; samplesize = 2; elseif strncmp(magic, 'uint32', length('uint32')) format = 'uint32'; samplesize = 4; elseif strncmp(magic, 'int32', length('int32')) format = 'int32'; samplesize = 4; elseif strncmp(magic, 'uint64', length('uint64')) format = 'uint64'; samplesize = 8; elseif strncmp(magic, 'int64', length('int64')) format = 'int64'; samplesize = 8; elseif strncmp(magic, 'float32', length('float32')) format = 'float32'; samplesize = 4; elseif strncmp(magic, 'float64', length('float64')) format = 'float64'; samplesize = 8; else warning('could not detect sample format, assuming file format subtype 1 with ''int32'''); subtype = 1; % the file format is version 1 format = 'int32'; samplesize = 4; end % determine whether the file format is version 2 or 3 if isempty(subtype) if all(magic((length(format)+1):end)==' ') subtype = 2; else subtype = 3; end end % determine the channel name switch subtype case 1 % the first 8 bytes of the file contain the channel label (padded with spaces) label = strtrim(magic); case {2, 3} % the filename is formatted like "dataset.chanlabel.bin" [p, f, x1] = fileparts(filename); [p, f, x2] = fileparts(f); if isempty(x2) warning('could not determine channel label'); label = 'unknown'; else label = x2(2:end); end clear p f x1 x2 otherwise error('unknown file format subtype'); end % determine the downscale factor, i.e. the number of bits that the integer representation has to be shifted back to the left switch subtype case 1 % these never contained a multiplication factor but always corresponded % to the lowest N bits of the original 32 bit integer downscale = 0; case 2 % these might contain a multiplication factor but that factor cannot be retrieved from the file warning('downscale factor is unknown for ''%s'', assuming that no downscaling was applied', filename); downscale = 0; case 3 downscale = double(magic(8)); otherwise error('unknown file format subtype'); end [p1, f1, x1] = fileparts(filename); [p2, f2, x2] = fileparts(f1); headerfile = fullfile(p1, [f2, '.txt']); if exist(headerfile, 'file') orig = neuralynx_getheader(headerfile); % construct the header from the accompanying text file hdr = []; hdr.Fs = orig.SamplingFrequency; hdr.nChans = 1; hdr.nSamples = (filesize(filename)-8)/samplesize; hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.label = {label}; else % construct the header from the hard-coded defaults hdr = []; hdr.Fs = 32556; hdr.nChans = 1; hdr.nSamples = (filesize(filename)-8)/samplesize; hdr.nSamplesPre = 0; hdr.nTrials = 1; hdr.label = {label}; end if ~needdat % also return the file details hdr.orig.subtype = subtype; hdr.orig.magic = magic; hdr.orig.format = format; hdr.orig.downscale = downscale; % return only the header details dat = hdr; else % read and return the data if begsample<1 begsample = 1; end if isinf(endsample) endsample = hdr.nSamples; end fseek(fid, 8+(begsample-1)*samplesize, 'bof'); % skip to the beginning of the interesting data format = sprintf('%s=>%s', format, format); dat = fread(fid, [1 endsample-begsample+1], format); if downscale>1 % the data was downscaled with 2^N, i.e. shifted N bits to the right in case of integer representations % now it should be upscaled again with the same amount dat = dat.*(2^downscale); end if length(dat)<(endsample-begsample+1) error('could not read the requested data'); end end % needdat fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to determine the file size in bytes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [siz] = filesize(filename) l = dir(filename); if l.isdir error(sprintf('"%s" is not a file', filename)); end siz = l.bytes;
github
philippboehmsturm/antx-master
inifile.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/inifile.m
23,578
utf_8
f647125ffa71c22e44a119c27e73d460
function readsett = inifile(fileName,operation,keys,style) %readsett = INIFILE(fileName,operation,keys,style) % Creates, reads, or writes data from/to ini (ascii) file. % % - fileName: ini file name % - operation: can be one of the following: % 'new' (rewrites an existing or creates a new, empty file), % 'deletekeys'(deletes keys and their values - if they exist), % 'read' (reads values as strings), % 'write' (writes values given as strings), % - keys: cell array of STRINGS; max 5 columns, min % 3 columns. Each row has the same number of columns. The columns are: % 'section': section name string (the root is considered if empty or not given) % 'subsection': subsection name string (the root is considered if empty or not given) % 'key': name of the field to write/read from (given as a string). % 'value': (optional) string-value to write to the ini file in case of 'write' operation % 'defaultValue': (optional) value that is returned when the key is not found when reading ('read' operation) % - style: 'tabbed' writes sections, subsections and keys in a tabbed style % to get a more readable file. The 'plain' style is the % default style. This only affects the keys that will be written/rewritten. % % - readsett: read setting in the case of the 'read' operation. If % the keys are not found, the default values are returned % as strings (if given in the 5-th column). % % EXAMPLE: % Suppose we want a new ini file, test1.ini with 3 fields. % We can write them into the file using: % % inifile('test1.ini','new'); % writeKeys = {'measurement','person','name','Primoz Cermelj';... % 'measurement','protocol','id','1';... % 'application','','description','some...'}; % inifile('test1.ini','write',writeKeys,'plain'); % % Later, you can read them out. Additionally, if any of them won't % exist, a default value will be returned (if the 5-th column is given as below). % % readKeys = {'measurement','person','name','','John Doe';... % 'measurement','protocol','id','','0';... % 'application','','description','','none'}; % readSett = inifile('test1.ini','read',readKeys); % % % NOTES: When the operation is 'new', only the first 2 parameters are % required. If the operation is 'write' and the file is empty or does not exist, % a new file is created. When writing and if any of the section or subsection or key does not exist, % it creates (adds) a new one. % Everything but value is NOT case sensitive. Given keys and values % will be trimmed (leading and trailing spaces will be removed). % Any duplicates (section, subsection, and keys) are ignored. Empty section and/or % subsection can be given as an empty string, '', but NOT as an empty matrix, []. % % This function was tested on the win32 platform only but it should % also work on Unix/Linux platforms. Since some short-circuit operators % are used, at least Matlab 6.5 should be used. % % FREE SOFTWARE - please refer the source % Copyright (c) 2003 by Primoz Cermelj % First release on 29.01.2003 % Primoz Cermelj, Slovenia % Contact: [email protected] % Download location: http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=2976&objectType=file % % Version: 1.1.0 % Last revision: 04.02.2004 % % Bug reports, questions, etc. can be sent to the e-mail given above. % % This programme is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or any later version. % % This programme is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. %-------------------------------------------------------------------------- %---------------- % INIFILE history %---------------- % % [v.1.1.0] 04.02.2004 % - FIX: 'writetext' option removed (there was a bug previously) % % [v.1.01b] 19.12.2003 % - NEW: A new concept - multiple keys can now be read, written, or deleted % ALL AT ONCE which makes this function much faster. For example, to % write 1000 keys, using previous versions it took 157 seconds on a % 1.5 GHz machine, with this new version it took only 1.83 seconds. % In general, the speed improvement is greater when larger number of % read/written keys are considered. % - NEW: The format of the input parameters has changed. See above. % % [v.0.97] 19.11.2003 % - NEW: Additional m-function, strtrim, is no longer needed % % [v.0.96] 16.10.2003 % - FIX: Detects empty keys % % [v.0.95] 04.07.2003 % - NEW: 'deletekey' option/operation added % - FIX: A major file refinement to obtain a more compact utility -> additional operations can "easily" be implemented % % [v.0.91-0.94] % - FIX: Some minor refinements % % [v.0.90] 29.01.2003 % - NEW: First release of this tool % %---------------- global NL_CHAR; % Checks the input arguments if nargin < 2 error('Not enough input arguments'); end if (strcmpi(operation,'read')) | (strcmpi(operation,'deletekeys')) if nargin < 3 error('Not enough input arguments.'); end if ~exist(fileName) error(['File ' fileName ' does not exist.']); end [m,n] = size(keys); if n > 5 error('Keys argument has too many columns'); end for ii=1:m if isempty(keys(ii,3)) | ~ischar(keys{ii,3}) error('Empty or non-char keys are not allowed.'); end end elseif (strcmpi(operation,'write')) | (strcmpi(operation,'writetext')) if nargin < 3 error('Not enough input arguments'); end [m,n] = size(keys); for ii=1:m if isempty(keys(ii,3)) | ~ischar(keys{ii,3}) error('Empty or non-char keys are not allowed.'); end end elseif (~strcmpi(operation,'new')) error(['Unknown inifile operation: ''' operation '''']); end if nargin >= 3 for ii=1:m for jj=1:n if ~ischar(keys{ii,jj}) error('All cells from keys must be given as strings, even the empty ones.'); end end end end if nargin < 4 || isempty(style) style = 'plain'; else if ~(strcmpi(style,'plain') | strcmpi(style,'tabbed')) | ~ischar(style) error('Unsupported style given or style not given as a string'); end end % Sets new-line character (string) if ispc NL_CHAR = '\r\n'; else NL_CHAR = '\n'; end %---------------------------- % CREATES a new, empty file (rewrites an existing one) %---------------------------- if strcmpi(operation,'new') fh = fopen(fileName,'w'); if fh == -1 error(['File: ''' fileName ''' can not be (re)created']); end fclose(fh); return %---------------------------- % READS key-value pairs out %---------------------------- elseif (strcmpi(operation,'read')) if n < 5 defaultValues = cellstrings(m,1); else defaultValues = keys(:,5); end readsett = defaultValues; keysIn = keys(:,1:3); [secsExist,subsecsExist,keysExist,readValues,so,eo] = findkeys(fileName,keysIn); ind = find(keysExist); if ~isempty(ind) readsett(ind) = readValues(ind); end return %---------------------------- % WRITES key-value pairs to an existing or non-existing % file (file can even be empty) %---------------------------- elseif (strcmpi(operation,'write')) if m < 1 error('At least one key is needed when writing keys'); end if ~exist(fileName) inifile(fileName,'new'); end writekeys(fileName,keys,style); return %---------------------------- % DELETES key-value pairs out %---------------------------- elseif (strcmpi(operation,'deletekeys')) deletekeys(fileName,keys); else error('Unknown operation for INIFILE.'); end %-------------------------------------------------- %%%%%%%%%%%%% SUBFUNCTIONS SECTION %%%%%%%%%%%%%%%% %-------------------------------------------------- %------------------------------------ function [secsExist,subSecsExist,keysExist,values,startOffsets,endOffsets] = findkeys(fileName,keysIn) % This function parses ini file for keys as given by keysIn. keysIn is a cell % array of strings having 3 columns; section, subsection and key in each row. % section and/or subsection can be empty (root section or root subsection) % but the key can not be empty. The startOffsets and endOffsets are start and % end bytes that each key occuppies, respectively. If any of the keys doesn't exist, % startOffset and endOffset for this key are the same. A special case is % when the key that doesn't exist also corresponds to a non-existing % section and non-existing subsection. In such a case, the startOffset and % endOffset have values of -1. nKeys = size(keysIn,1); % number of keys nKeysLocated = 0; % number of keys located secsExist = zeros(nKeys,1); % if section exists (and is non-empty) subSecsExist = zeros(nKeys,1); % if subsection... keysExist = zeros(nKeys,1); % if key that we are looking for exists keysLocated = keysExist; % if the key's position (existing or non-existing) is LOCATED values = cellstrings(nKeys,1); % read values of keys (strings) startOffsets = -ones(nKeys,1); % start byte-position of the keys endOffsets = -ones(nKeys,1); % end byte-position of the keys keyInd = find(strcmpi(keysIn(:,1),'')); % key indices having [] section (root section) line = []; currSection = ''; currSubSection = ''; fh = fopen(fileName,'r'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try %--- Searching for the keys - their values and start and end locations in bytes while 1 pos1 = ftell(fh); line = fgetl(fh); if line == -1 % end of file, exit line = []; break end [status,readValue,readKey] = processiniline(line); if (status == 1) % (new) section found % Keys that were found as belonging to any previous section % are now assumed as located (because another % section is found here which could even be a repeated one) keyInd = find( ~keysLocated & strcmpi(keysIn(:,1),currSection) ); if length(keyInd) keysLocated(keyInd) = 1; nKeysLocated = nKeysLocated + length(keyInd); end currSection = readValue; currSubSection = ''; % Indices to non-located keys belonging to current section keyInd = find( ~keysLocated & strcmpi(keysIn(:,1),currSection) ); if ~isempty(keyInd) secsExist(keyInd) = 1; end pos2 = ftell(fh); startOffsets(keyInd) = pos2+1; endOffsets(keyInd) = pos2+1; elseif (status == 2) % (new) subsection found % Keys that were found as belonging to any PREVIOUS section % and/or subsection are now assumed as located (because another % subsection is found here which could even be a repeated one) keyInd = find( ~keysLocated & strcmpi(keysIn(:,1),currSection) & ~keysLocated & strcmpi(keysIn(:,2),currSubSection)); if length(keyInd) keysLocated(keyInd) = 1; nKeysLocated = nKeysLocated + length(keyInd); end currSubSection = readValue; % Indices to non-located keys belonging to current section and subsection at the same time keyInd = find( ~keysLocated & strcmpi(keysIn(:,1),currSection) & ~keysLocated & strcmpi(keysIn(:,2),currSubSection)); if ~isempty(keyInd) subSecsExist(keyInd) = 1; end pos2 = ftell(fh); startOffsets(keyInd) = pos2+1; endOffsets(keyInd) = pos2+1; elseif (status == 3) % key found if isempty(keyInd) continue % no keys from 'keys' - from section-subsection par currently in end currKey = readValue; pos2 = ftell(fh); % the last-byte position of the read key - the total sum of chars read so far for ii=1:length(keyInd) if strcmpi( keysIn(keyInd(ii),3),readKey ) & ~keysLocated(keyInd(ii)) keysExist(keyInd(ii)) = 1; startOffsets(keyInd(ii)) = pos1+1; endOffsets(keyInd(ii)) = pos2; values{keyInd(ii)} = currKey; keysLocated(keyInd(ii)) = 1; nKeysLocated = nKeysLocated + 1; else if ~keysLocated(keyInd(ii)) startOffsets(keyInd(ii)) = pos2+1; endOffsets(keyInd(ii)) = pos2+1; end end end if nKeysLocated >= nKeys % if all the keys are located break end else % general text found (even empty line(s)) end %--- End searching end fclose(fh); catch fclose(fh); error(['Error parsing the file for keys: ' fileName ': ' lasterr]); end %------------------------------------ %------------------------------------ function writekeys(fileName,keys,style) % Writes keys to the section and subsection pair % If any of the keys doesn't exist, a new key is added to % the end of the section-subsection pair otherwise the key is updated (changed). % Keys is a 4-column cell array of strings. global NL_CHAR; RETURN = sprintf('\r'); NEWLINE = sprintf('\n'); [m,n] = size(keys); if n < 4 error('Keys to be written are given in an invalid format.'); end % Get keys position first using findkeys keysIn = keys; [secsExist,subSecsExist,keysExist,readValues,so,eo] = findkeys(fileName,keys(:,1:3)); % Read the whole file's contents out fh = fopen(fileName,'r'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try dataout = fscanf(fh,'%c'); catch fclose(fh); error(lasterr); end fclose(fh); %--- Rewriting the file -> writing the refined contents fh = fopen(fileName,'w'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try tab1 = []; if strcmpi(style,'tabbed') tab1 = sprintf('\t'); end % Proper sorting of keys is cruical at this point in order to avoid % inproper key-writing. % Find keys with -1 offsets - keys with non-existing section AND % subsection - keys that will be added to the end of the file fs = length(dataout); % file size in bytes nAddedKeys = 0; ind = find(so==-1); if ~isempty(ind) so(ind) = (fs+10); % make sure these keys will come to the end when sorting eo(ind) = (fs+10); nAddedKeys = length(ind); end % Sort keys according to start- and end-offsets [dummy,ind] = sort(so,1); so = so(ind); eo = eo(ind); keysIn = keysIn(ind,:); keysExist = keysExist(ind); secsExist = secsExist(ind); subSecsExist = subSecsExist(ind); readValues = readValues(ind); values = keysIn(:,4); % Find keys with equal start offset (so) and additionally sort them % (locally). These are non-existing keys, including the ones whose % section and subsection will also be added. nKeys = size(so,1); fullInd = 1:nKeys; ii = 1; while ii < nKeys ind = find(so==so(ii)); if ~isempty(ind) && length(ind) > 1 n = length(ind); from = ind(1); to = ind(end); tmpKeys = keysIn( ind,: ); [tmpKeys,ind2] = sortrows( lower(tmpKeys) ); fullInd(from:to) = ind(ind2); ii = ii + n; else ii = ii + 1; end end % Final (re)sorting so = so(fullInd); eo = eo(fullInd); keysIn = keysIn(fullInd,:); keysExist = keysExist(fullInd); secsExist = secsExist(fullInd); subSecsExist = subSecsExist(fullInd); readValues = readValues(fullInd); values = keysIn(:,4); % Refined data - datain datain = []; for ii=1:nKeys % go through all the keys, existing and non-existing ones if ii==1 from = 1; % from byte-offset of original data (dataout) else from = eo(ii-1); if keysExist(ii-1) from = from + 1; end end to = min(so(ii)-1,fs); % to byte-offset of original data (dataout) if ~isempty(dataout) datain = [datain dataout(from:to)]; % the lines before the key end if length(datain) & (~(datain(end)==RETURN | datain(end)==NEWLINE)) datain = [datain, sprintf(NL_CHAR)]; end tab = []; if ~keysExist(ii) if ~secsExist(ii) && ~isempty(keysIn(ii,1)) if ~isempty(keysIn{ii,1}) datain = [datain sprintf(['%s' NL_CHAR],['[' keysIn{ii,1} ']'])]; end % Key-indices with the same section as this, ii-th key (even empty sections are considered) ind = find( strcmpi( keysIn(:,1), keysIn(ii,1)) ); % This section exists at all keys corresponding to the same section from know on (even the empty ones) secsExist(ind) = 1; end if ~subSecsExist(ii) && ~isempty(keysIn(ii,2)) if ~isempty( keysIn{ii,2}) if secsExist(ii); tab = tab1; end; datain = [datain sprintf(['%s' NL_CHAR],[tab '{' keysIn{ii,2} '}'])]; end % Key-indices with the same section AND subsection as this, ii-th key (even empty sections and subsections are considered) ind = find( strcmpi( keysIn(:,1), keysIn(ii,1)) & strcmpi( keysIn(:,2), keysIn(ii,2)) ); % This subsection exists at all keys corresponding to the same section and subsection from know on (even the empty ones) subSecsExist(ind) = 1; end end if secsExist(ii) & (~isempty(keysIn{ii,1})); tab = tab1; end; if subSecsExist(ii) & (~isempty(keysIn{ii,2})); tab = [tab tab1]; end; datain = [datain sprintf(['%s' NL_CHAR],[tab keysIn{ii,3} ' = ' values{ii}])]; end from = eo(ii); if keysExist(ii) from = from + 1; end to = length(dataout); if from < to datain = [datain dataout(from:to)]; end fprintf(fh,'%c',datain); catch fclose(fh); error(['Error writing keys to file: ''' fileName ''' : ' lasterr]); end fclose(fh); %------------------------------------ %------------------------------------ function deletekeys(fileName,keys) % Deletes keys and their values out; keys must have at least 3 columns: % section, subsection, and key [m,n] = size(keys); if n < 3 error('Keys to be deleted are given in an invalid format.'); end % Get keys position first keysIn = keys; [secsExist,subSecsExist,keysExist,readValues,so,eo] = findkeys(fileName,keys(:,1:3)); % Read the whole file's contents out fh = fopen(fileName,'r'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try dataout = fscanf(fh,'%c'); catch fclose(fh); error(lasterr); end fclose(fh); %--- Rewriting the file -> writing the refined contents fh = fopen(fileName,'w'); if fh == -1 error(['File: ''' fileName ''' does not exist or can not be opened.']); end try ind = find(keysExist); nExistingKeys = length(ind); datain = dataout; if nExistingKeys % Filtering - retain only the existing keys... fs = length(dataout); % file size in bytes so = so(ind); eo = eo(ind); keysIn = keysIn(ind,:); % ...and sorting [so,ind] = sort(so); eo = eo(ind); keysIn = keysIn(ind,:); % Refined data - datain datain = []; for ii=1:nExistingKeys % go through all the existing keys if ii==1 from = 1; % from byte-offset of original data (dataout) else from = eo(ii-1)+1; end to = so(ii)-1; % to byte-offset of original data (dataout) if ~isempty(dataout) datain = [datain dataout(from:to)]; % the lines before the key end end from = eo(ii)+1; to = length(dataout); if from < to datain = [datain dataout(from:to)]; end end fprintf(fh,'%c',datain); catch fclose(fh); error(['Error deleting keys from file: ''' fileName ''' : ' lasterr]); end fclose(fh); %------------------------------------ %------------------------------------ function [status,value,key] = processiniline(line) % Processes a line read from the ini file and % returns the following values: % - status: 0 => empty line or unknown string % 1 => section found % 2 => subsection found % 3 => key-value pair found % - value: value-string of a key, section, or subsection % - key: key-string status = 0; value = []; key = []; line = strim(line); % removes any leading and trailing spaces if isempty(line) % empty line return end if (line(1) == '[') & (line(end) == ']')... % section found & (length(line) >= 3) value = lower(line(2:end-1)); status = 1; elseif (line(1) == '{') &... % subsection found (line(end) == '}') & (length(line) >= 3) value = lower(line(2:end-1)); status = 2; else pos = findstr(line,'='); if ~isempty(pos) % key-value pair found status = 3; key = lower(line(1:pos-1)); value = line(pos+1:end); key = strim(key); % removes any leading and trailing spaces value = strim(value); % removes any leading and trailing spaces if isempty(key) % empty keys are not allowed status = 0; key = []; value = []; end end end %------------------------------------ %------------------------------------ function outstr = strim(str) % Removes leading and trailing spaces (spaces, tabs, endlines,...) % from the str string. if isnumeric(str); outstr = str; return end ind = find( ~isspace(str) ); % indices of the non-space characters in the str if isempty(ind) outstr = []; else outstr = str( ind(1):ind(end) ); end %------------------------------------ function cs = cellstrings(m,n) % Creates a m x n cell array of empty strings - '' cs = cell(m,n); for ii=1:m for jj=1:n cs{ii,jj} = ''; end end
github
philippboehmsturm/antx-master
yokogawa2grad_new.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/yokogawa2grad_new.m
9,123
utf_8
a05c043b59134bedb201bba241ad57ef
function grad = yokogawa2grad_new(hdr) % YOKOGAWA2GRAD_NEW converts the position and weights of all coils that % compromise a gradiometer system into a structure that can be used % by FieldTrip. This implementation uses the new "yokogawa_meg_reader" % toolbox. % % See also FT_READ_HEADER, CTF2GRAD, BTI2GRAD, FIF2GRAD, YOKOGAWA2GRAD % Copyright (C) 2005-2012, Robert Oostenveld % Copyright (C) 2010, Tilmann Sander-Thoemmes % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: yokogawa2grad_new.m 7123 2012-12-06 21:21:38Z roboos $ % The following line is only a safety measure: No function of the toolbox % is actually called in this routine. if ~ft_hastoolbox('yokogawa_meg_reader') error('cannot determine whether Yokogawa toolbox is present'); end if isfield(hdr, 'label') label = hdr.label; % keep for later use end if isfield(hdr, 'orig') hdr = hdr.orig; % use the original header, not the FieldTrip header end % The "channel_info.channel(i)" structure contains, s. sepcifications in % Yokogawa MEG Reader Toolbox 1.4 specifications.pdf. % type, type of sensor % data.x (in m, inner coil) % data.y (in m, inner coil) % data.z (in m, inner coil) % data.size (in m, coil diameter) % for gradiometers % data.baseline (in m) % for axial gradiometers and magnetometers % data.zdir orientation of inner coil (theta in deg: angle to z-axis) % data.xdir orientation of inner coil (phi in deg: angle to x-axis) % for planar gradiometers % Note, that Yokogawa planar gradiometers contain two coils perpendicular to % the sphere, i.e. the planar gradiometers normal is the spheres tangential. % Therefore the definition of an inner coil makes sense here in contrast to % planar gradiometers from Neuromag, where the gradiometer normal is radial. % data.zdir1 orientation of inner coil (theta in deg: angle to z-axis) % data.xdir1 orientation of inner coil (phi in deg: angle to x-axis) % data.zdir2 baseline orientation from inner coil (theta in deg: angle to z-axis) % data.xdir2 baseline orientation from inner coil (phi in deg: angle to x-axis) % % The code below is not written for speed or elegance, but for readability. % % shorten names ch_info = hdr.channel_info.channel; type = [ch_info.type]; handles = definehandles; % get all axial grads, planar grads, and magnetometers. % reference channels without position information are excluded. grad_ind = [1:hdr.channel_count]; isgrad = (type==handles.AxialGradioMeter | type==handles.PlannerGradioMeter | ... type==handles.MagnetoMeter); isref = (type==handles.RefferenceAxialGradioMeter | type==handles.RefferencePlannerGradioMeter | ... type==handles.RefferenceMagnetoMeter); for i = 1: hdr.channel_count if isref(i) && sum( ch_info( i ).data.x^2 + ch_info( i ).data.y^2 + ch_info( i ).data.z^2 ) > 0.0, isgrad(i) = 1; end; end grad_ind = grad_ind(isgrad); grad_nr = size(grad_ind,2); grad = []; grad.coilpos = zeros(2*grad_nr,3); grad.coilori = zeros(2*grad_nr,3); % define gradiometer and magnetometer for i = 1:grad_nr ch_ind = grad_ind(i); grad.coilpos(i,1) = ch_info(ch_ind).data.x*100; % cm grad.coilpos(i,2) = ch_info(ch_ind).data.y*100; % cm grad.coilpos(i,3) = ch_info(ch_ind).data.z*100; % cm grad.chanpos = grad.coilpos(1:grad_nr,:); if ch_info(ch_ind).type==handles.AxialGradioMeter || ch_info(ch_ind).type==handles.RefferenceAxialGradioMeter baseline = ch_info(ch_ind).data.baseline; ori_1st = [ch_info(ch_ind).data.zdir ch_info(ch_ind).data.xdir ]; % polar to x,y,z coordinates ori_1st = ... [sin(ori_1st(:,1)/180*pi).*cos(ori_1st(:,2)/180*pi) ... sin(ori_1st(:,1)/180*pi).*sin(ori_1st(:,2)/180*pi) ... cos(ori_1st(:,1)/180*pi)]; grad.coilori(i,:) = ori_1st; grad.coilpos(i+grad_nr,:) = [grad.coilpos(i,:)+ori_1st*baseline*100]; grad.coilori(i+grad_nr,:) = -ori_1st; elseif ch_info(ch_ind).type==handles.PlannerGradioMeter || ch_info(ch_ind).type==handles.RefferencePlannerGradioMeter baseline = ch_info(ch_ind).data.baseline; ori_1st = [ch_info(ch_ind).data.zdir1 ch_info(ch_ind).data.xdir1 ]; % polar to x,y,z coordinates ori_1st = ... [sin(ori_1st(:,1)/180*pi).*cos(ori_1st(:,2)/180*pi) ... sin(ori_1st(:,1)/180*pi).*sin(ori_1st(:,2)/180*pi) ... cos(ori_1st(:,1)/180*pi)]; grad.coilori(i,:) = ori_1st; ori_1st_to_2nd = [ch_info(ch_ind).data.zdir2 ch_info(ch_ind).data.xdir2 ]; % polar to x,y,z coordinates ori_1st_to_2nd = ... [sin(ori_1st_to_2nd(:,1)/180*pi).*cos(ori_1st_to_2nd(:,2)/180*pi) ... sin(ori_1st_to_2nd(:,1)/180*pi).*sin(ori_1st_to_2nd(:,2)/180*pi) ... cos(ori_1st_to_2nd(:,1)/180*pi)]; grad.coilpos(i+grad_nr,:) = [grad.coilpos(i,:)+ori_1st_to_2nd*baseline*100]; grad.coilori(i+grad_nr,:) = -ori_1st; else % magnetometer ori_1st = [ch_info(ch_ind).data.zdir ch_info(ch_ind).data.xdir ]; % polar to x,y,z coordinates ori_1st = ... [sin(ori_1st(:,1)/180*pi).*cos(ori_1st(:,2)/180*pi) ... sin(ori_1st(:,1)/180*pi).*sin(ori_1st(:,2)/180*pi) ... cos(ori_1st(:,1)/180*pi)]; grad.coilori(i,:) = ori_1st; grad.coilpos(i+grad_nr,:) = [0 0 0]; grad.coilori(i+grad_nr,:) = [0 0 0]; end grad.chanori = grad.coilori(1:grad_nr,:); end % Define the pair of 1st and 2nd coils for each gradiometer grad.tra = repmat(diag(ones(1,grad_nr),0),1,2); % for mangetometers change tra as there is no second coil for i = 1:grad_nr ch_ind = grad_ind(i); if ch_info(ch_ind).type==handles.MagnetoMeter grad.tra(i,grad_nr+i) = 0; end end % the gradiometer labels should be consistent with the channel labels in % read_yokogawa_header, the predefined list of channel names in ft_senslabel % and with ft_channelselection: % but it is ONLY consistent with read_yokogawa_header as NO FIXED relation % between channel index and type of channel exists for Yokogawa systems. % Therefore all have individual label sequences: Support in ft_senslabel % is only partial. if ~isempty(label) grad.label = label(grad_ind)'; else % this is only backup, if something goes wrong above. label = cell(grad_nr,1); for i=1:length(label) label{i,1} = sprintf('AG%03d', i); end grad.label = label; end grad.unit = 'cm'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles; handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % ????4.0mm???????` handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % ???a15.5mm???~?? handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % ????12.0mm???????` handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
philippboehmsturm/antx-master
read_besa_avr.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_besa_avr.m
3,929
utf_8
91f2ee59d1af564811511e0e7f201ba4
function [avr] = read_besa_avr(filename) % READ_BESA_AVR reads average EEG data in BESA format % % Use as % [avr] = read_besa_avr(filename) % % This will return a structure with the header information in % avr.npnt % avr.tsb % avr.di % avr.sb % avr.sc % avr.Nchan (optional) % avr.label (optional) % and the ERP data is contained in the Nchan X Nsamples matrix % avr.data % Copyright (C) 2003-2006, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_besa_avr.m 7123 2012-12-06 21:21:38Z roboos $ fid = fopen(filename, 'rt'); % the first line contains header information headstr = fgetl(fid); ok = 0; if ~ok try buf = sscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f Nchan= %f SegmentName= %s\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); avr.Nchan = buf(6); avr.SegmentName = buf(7); ok = 1; catch ok = 0; end end if ~ok try buf = fscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f Nchan= %f\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); avr.Nchan = buf(6); ok = 1; catch ok = 0; end end if ~ok try buf = sscanf(headstr, 'Npts= %d TSB= %f DI= %f SB= %f SC= %f\n'); avr.npnt = buf(1); avr.tsb = buf(2); avr.di = buf(3); avr.sb = buf(4); avr.sc = buf(5); ok = 1; catch ok = 0; end end if ~ok error('Could not interpret the header information.'); end % rewind to the beginning of the file, skip the header line fseek(fid, 0, 'bof'); fgetl(fid); % the second line may contain channel names chanstr = fgetl(fid); chanstr = deblank(fliplr(deblank(fliplr(chanstr)))); if (chanstr(1)>='A' && chanstr(1)<='Z') || (chanstr(1)>='a' && chanstr(1)<='z') haschan = 1; avr.label = str2cell(strrep(deblank(chanstr), '''', ''))'; else [root, name] = fileparts(filename); haschan = 0; elpfile = fullfile(root, [name '.elp']); elafile = fullfile(root, [name '.ela']); if exist(elpfile, 'file') % read the channel names from the accompanying ELP file lbl = importdata(elpfile); avr.label = strrep(lbl.textdata(:,2) ,'''', ''); elseif exist(elafile, 'file') % read the channel names from the accompanying ELA file lbl = importdata(elafile); lbl = strrep(lbl ,'MEG ', ''); % remove the channel type lbl = strrep(lbl ,'EEG ', ''); % remove the channel type avr.label = lbl; else warning('Could not create channels labels.'); end end % seek to the beginning of the data fseek(fid, 0, 'bof'); fgetl(fid); % skip the header line if haschan fgetl(fid); % skip the channel name line end buf = fscanf(fid, '%f'); nchan = length(buf)/avr.npnt; avr.data = reshape(buf, avr.npnt, nchan)'; fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to cut a string into pieces at the spaces %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function c = str2cell(s) c = {}; [t, r] = strtok(s, ' '); while ~isempty(t) c{end+1} = t; [t, r] = strtok(r, ' '); end