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
xml2struct.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/xml2struct.m
8,612
utf_8
3d883353ccb551f2dcd554835610a565
function [ s ] = xml2struct( file ) %Convert xml file into a MATLAB structure % [ s ] = xml2struct( file ) % % A file containing: % <XMLname attrib1="Some value"> % <Element>Some text</Element> % <DifferentElement attrib2="2">Some more text</DifferentElement> % <DifferentElement attrib3="2" attrib4="1">Even more text</DifferentElement> % </XMLname> % % Used to produce: % s.XMLname.Attributes.attrib1 = "Some value"; % s.XMLname.Element.Text = "Some text"; % s.XMLname.DifferentElement{1}.Attributes.attrib2 = "2"; % s.XMLname.DifferentElement{1}.Text = "Some more text"; % s.XMLname.DifferentElement{2}.Attributes.attrib3 = "2"; % s.XMLname.DifferentElement{2}.Attributes.attrib4 = "1"; % s.XMLname.DifferentElement{2}.Text = "Even more text"; % % Will produce (gp: to matche the output of xml2struct in XML4MAT, but note that Element(2) is empty): % Element: Some text % DifferentElement: % attrib2: 2 % DifferentElement: Some more text % attrib1: Some value % % Element: % DifferentElement: % attrib3: 2 % attrib4: 1 % DifferentElement: Even more text % attrib1: % % Note the characters : - and . are not supported in structure fieldnames and % are replaced by _ % % Written by W. Falkena, ASTI, TUDelft, 21-08-2010 % Attribute parsing speed increased by 40% by A. Wanner, 14-6-2011 % 2011/12/14 giopia: changes in the main function to make more similar to xml2struct of the XML4MAT toolbox, bc it's used by fieldtrip % 2012/04/04 roboos: added the original license clause, see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=645#c11 % 2012/04/04 roboos: don't print the filename that is being read %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Copyright (c) 2010, Wouter Falkena % All rights reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are % met: % % * Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % * Redistributions in binary form must reproduce the above copyright % notice, this list of conditions and the following disclaimer in % the documentation and/or other materials provided with the distribution % % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE % ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE % LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS % INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN % CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) % ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE % POSSIBILITY OF SUCH DAMAGE. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if (nargin < 1) clc; help xml2struct return end %check for existance if (exist(file,'file') == 0) %Perhaps the xml extension was omitted from the file name. Add the %extension and try again. if (isempty(strfind(file,'.xml'))) file = [file '.xml']; end if (exist(file,'file') == 0) error(['The file ' file ' could not be found']); end end %fprintf('xml2struct reading %s\n', file); % gp 11/12/15 %read the xml file xDoc = xmlread(file); %parse xDoc into a MATLAB structure s = parseChildNodes(xDoc); fn = fieldnames(s); s = s.(fn{1}); % gp 11/12/15: output is compatible with xml2struct of xml2mat end % ----- Subfunction parseChildNodes ----- function [children,ptext] = parseChildNodes(theNode) % Recurse over node children. children = struct; ptext = []; if theNode.hasChildNodes childNodes = theNode.getChildNodes; numChildNodes = childNodes.getLength; for count = 1:numChildNodes theChild = childNodes.item(count-1); [text,name,attr,childs] = getNodeData(theChild); if (~strcmp(name,'#text') && ~strcmp(name,'#comment')) %XML allows the same elements to be defined multiple times, %put each in a different cell if (isfield(children,name)) % if 0 % numel(children) > 1 % gp 11/12/15: (~iscell(children.(name))) % %put existsing element into cell format % children.(name) = {children.(name)}; % end index = length(children)+1; % gp 11/12/15: index = length(children.(name))+1; else index = 1; % gp 11/12/15: new field end %add new element children(index).(name) = childs; if isempty(attr) if(~isempty(text)) children(index).(name) = text; end else fn = fieldnames(attr); for f = 1:numel(fn) children(index).(name)(1).(fn{f}) = attr.(fn{f}); % gp 11/12/15: children.(name){index}.('Attributes') = attr; end if(~isempty(text)) children(index).(name).(name) = text; % gp 11/12/15: children.(name){index}.('Text') = text; end end % else % gp 11/12/15: cleaner code, don't reuse the same code % %add previously unknown new element to the structure % children.(name) = childs; % if(~isempty(text)) % children.(name) = text; % gp 11/12/15: children.(name).('Text') = text; % end % if(~isempty(attr)) % children.('Attributes') = attr; % gp 11/12/15 children.(name).('Attributes') = attr; % end % end elseif (strcmp(name,'#text')) %this is the text in an element (i.e. the parentNode) if (~isempty(regexprep(text,'[\s]*',''))) if (isempty(ptext)) ptext = text; else %what to do when element data is as follows: %<element>Text <!--Comment--> More text</element> %put the text in different cells: % if (~iscell(ptext)) ptext = {ptext}; end % ptext{length(ptext)+1} = text; %just append the text ptext = [ptext text]; end end end end end end % ----- Subfunction getNodeData ----- function [text,name,attr,childs] = getNodeData(theNode) % Create structure of node info. %make sure name is allowed as structure name name = regexprep(char(theNode.getNodeName),'[-:.]','_'); attr = parseAttributes(theNode); if (isempty(fieldnames(attr))) attr = []; end %parse child nodes [childs,text] = parseChildNodes(theNode); if (isempty(fieldnames(childs))) %get the data of any childless nodes try %faster then if any(strcmp(methods(theNode), 'getData')) text = char(theNode.getData); catch %no data end end end % ----- Subfunction parseAttributes ----- function attributes = parseAttributes(theNode) % Create attributes structure. attributes = struct; if theNode.hasAttributes theAttributes = theNode.getAttributes; numAttributes = theAttributes.getLength; for count = 1:numAttributes %attrib = theAttributes.item(count-1); %attr_name = regexprep(char(attrib.getName),'[-:.]','_'); %attributes.(attr_name) = char(attrib.getValue); %Suggestion of Adrian Wanner str = theAttributes.item(count-1).toString.toCharArray()'; k = strfind(str,'='); attr_name = regexprep(str(1:(k(1)-1)),'[-:.]','_'); attributes.(attr_name) = str((k(1)+2):(end-1)); end end end
github
philippboehmsturm/antx-master
nanstd.m
.m
antx-master/xspm8/external/fieldtrip/fileio/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
read_eeglabdata.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_eeglabdata.m
3,193
utf_8
33c4ab48f49c3929347fee8295589fbc
% read_eeglabdata() - import EEGLAB dataset files % % Usage: % >> dat = read_eeglabdata(filename); % % Inputs: % filename - [string] file name % % Optional inputs: % 'begtrial' - [integer] first trial to read % 'endtrial' - [integer] last trial to read % 'chanindx' - [integer] list with channel indices to read % 'header' - FILEIO structure header % % Outputs: % dat - data over the specified range % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2008- %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function dat = read_eeglabdata(filename, varargin); if nargin < 1 help read_eeglabdata; return; end; header = 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_eeglabheader(filename); end if ischar(header.orig.data) if strcmpi(header.orig.data(end-2:end), 'set'), header.ori = load('-mat', filename); else % assuming that the data file is in the current directory fid = fopen(header.orig.data); % assuming the .dat and .set files are located in the same directory if fid == -1 pathstr = fileparts(filename); fid = fopen(fullfile(pathstr, header.orig.data)); end if fid == -1 fid = fopen(fullfile(header.orig.filepath, header.orig.data)); % end if fid == -1, error(['Cannot not find data file: ' header.orig.data]); end; % only read the desired trials if strcmpi(header.orig.data(end-2:end), 'dat') dat = fread(fid,[header.nSamples*header.nTrials header.nChans],'float32')'; else dat = fread(fid,[header.nChans header.nSamples*header.nTrials],'float32'); end; dat = reshape(dat, header.nChans, header.nSamples, header.nTrials); fclose(fid); end; else dat = header.orig.data; dat = reshape(dat, header.nChans, header.nSamples, header.nTrials); end; if isempty(begtrial), begtrial = 1; end; if isempty(endtrial), endtrial = header.nTrials; end; if isempty(begsample), begsample = 1; end; if isempty(endsample), endsample = header.nSamples; end; dat = dat(:,begsample:endsample,begtrial:endtrial); if ~isempty(chanindx) % select the desired channels dat = dat(chanindx,:,:); end
github
philippboehmsturm/antx-master
readbdf.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/readbdf.m
3,632
utf_8
9c94d90dc0c8728b0b46e5276747e847
% readbdf() - Loads selected Records of an EDF or BDF File (European Data Format % for Biosignals) into MATLAB % Usage: % >> [DAT,signal] = readedf(EDF_Struct,Records,Mode); % Notes: % Records - List of Records for Loading % Mode - 0 Default % 1 No AutoCalib % 2 Concatenated (channels with lower sampling rate % if more than 1 record is loaded) % Output: % DAT - EDF data structure % signal - output signal % % Author: Alois Schloegl, 03.02.1998, updated T.S. Lorig Sept 6, 2002 for BDF read % % See also: openbdf(), sdfopen(), sdfread(), eeglab() % Version 2.11 % 03.02.1998 % Copyright (c) 1997,98 by Alois Schloegl % [email protected] % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % This program has been modified from the original version for .EDF files % The modifications are to the number of bytes read on line 53 (from 2 to % 3) and to the type of data read - line 54 (from int16 to bit24). Finally the name % was changed from readedf to readbdf % T.S. Lorig Sept 6, 2002 % % Header modified for eeglab() compatibility - Arnaud Delorme 12/02 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [DAT,S]=readbdf(DAT,Records,Mode) if nargin<3 Mode=0; end; EDF=DAT.Head; RecLen=max(EDF.SPR); S=nan(RecLen,EDF.NS); DAT.Record=zeros(length(Records)*RecLen,EDF.NS); DAT.Valid=uint8(zeros(1,length(Records)*RecLen)); DAT.Idx=Records(:)'; for nrec=1:length(Records), NREC=(DAT.Idx(nrec)-1); if NREC<0 fprintf(2,'Warning READEDF: invalid Record Number %i \n',NREC);end; fseek(EDF.FILE.FID,(EDF.HeadLen+NREC*EDF.AS.spb*3),'bof'); [s, count]=fread(EDF.FILE.FID,EDF.AS.spb,'bit24'); try, S(EDF.AS.IDX2)=s; catch, error('File is incomplete (try reading begining of file)'); end; %%%%% Test on Over- (Under-) Flow % V=sum([(S'==EDF.DigMax(:,ones(RecLen,1))) + (S'==EDF.DigMin(:,ones(RecLen,1)))])==0; V=sum([(S(:,EDF.Chan_Select)'>=EDF.DigMax(EDF.Chan_Select,ones(RecLen,1))) + ... (S(:,EDF.Chan_Select)'<=EDF.DigMin(EDF.Chan_Select,ones(RecLen,1)))])==0; EDF.ERROR.DigMinMax_Warning(find(sum([(S'>EDF.DigMax(:,ones(RecLen,1))) + (S'<EDF.DigMin(:,ones(RecLen,1)))]')>0))=1; % invalid=[invalid; find(V==0)+l*k]; if floor(Mode/2)==1 for k=1:EDF.NS, DAT.Record(nrec*EDF.SPR(k)+(1-EDF.SPR(k):0),k)=S(1:EDF.SPR(k),k); end; else DAT.Record(nrec*RecLen+(1-RecLen:0),:)=S; end; DAT.Valid(nrec*RecLen+(1-RecLen:0))=V; end; if rem(Mode,2)==0 % Autocalib DAT.Record=[ones(RecLen*length(Records),1) DAT.Record]*EDF.Calib; end; DAT.Record=DAT.Record'; return;
github
philippboehmsturm/antx-master
warning_once.m
.m
antx-master/xspm8/external/fieldtrip/fileio/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
ft_hastoolbox.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/ft_hastoolbox.m
21,701
utf_8
7141791b922e3b46334b4d5888532adf
function [status] = ft_hastoolbox(toolbox, autoadd, silent) % FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally % it will try to determine the path to the toolbox and install it % automatically. % % Use as % [status] = ft_hastoolbox(toolbox, autoadd, silent) % % autoadd = 0 means that it will not be added % autoadd = 1 means that give an error if it cannot be added % autoadd = 2 means that give a warning if it cannot be added % autoadd = 3 means that it remains silent if it cannot be added % % silent = 0 means that it will give some feedback about adding the toolbox % silent = 1 means that it will not give feedback % Copyright (C) 2005-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_hastoolbox.m 7172 2012-12-13 11:50:49Z roboos $ % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before % persistent previous previouspath % % if ~isequal(previouspath, path) % previous = []; % end % % if isempty(previous) % previous = struct; % elseif isfield(previous, fixname(toolbox)) % status = previous.(fixname(toolbox)); % return % end % this points the user to the website where he/she can download the toolbox url = { 'AFNI' 'see http://afni.nimh.nih.gov' 'DSS' 'see http://www.cis.hut.fi/projects/dss' 'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab' 'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox' 'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm' 'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd' 'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com' 'BIOSIG' 'see http://biosig.sourceforge.net' 'EEG' 'see http://eeg.sourceforge.net' 'EEGSF' 'see http://eeg.sourceforge.net' % alternative name 'MRI' 'see http://eeg.sourceforge.net' % alternative name 'NEUROSHARE' 'see http://www.neuroshare.org' 'BESA' 'see http://www.megis.de, or contact Karsten Hoechstetter' 'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde' 'YOKOGAWA' 'this is deprecated, please use YOKOGAWA_MEG_READER instead' 'YOKOGAWA_MEG_READER' 'see http://www.yokogawa.com/me/me-login-en.htm' 'BEOWULF' 'see http://robertoostenveld.nl, or contact Robert Oostenveld' 'MENTAT' 'see http://robertoostenveld.nl, or contact Robert Oostenveld' 'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth' '4D-VERSION' 'contact Christian Wienbruch' 'SIGNAL' 'see http://www.mathworks.com/products/signal' 'OPTIM' 'see http://www.mathworks.com/products/optim' 'IMAGE' 'see http://www.mathworks.com/products/image' % Mathworks refers to this as IMAGES 'SPLINES' 'see http://www.mathworks.com/products/splines' 'DISTCOMP' 'see http://www.mathworks.nl/products/parallel-computing/' 'COMPILER' 'see http://www.mathworks.com/products/compiler' 'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica' 'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm' 'FILEIO' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PREPROC' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'FORWARD' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'INVERSE' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'SPECEST' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'REALTIME' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'SPIKE' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'CONNECTIVITY' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PEER' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne' 'BCI2000' 'see http://bci2000.org' 'NLXNETCOM' 'see http://www.neuralynx.com' 'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external' 'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php' 'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydesaeter' 'BEMCP' 'contact Christophe Phillips' 'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435' 'PRTOOLS' 'see http://www.prtools.org' 'ITAB' 'contact Stefania Della Penna' 'BSMART' 'see http://www.brain-smart.org' 'PEER' 'see http://fieldtrip.fcdonders.nl/development/peer' 'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki' 'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page' 'VGRID' 'see http://www.rheinahrcampus.de/~medsim/vgrid/manual.html' 'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS' 'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti' 'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0' 'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab' 'BCT' 'see http://www.brain-connectivity-toolbox.net/' 'CCA' 'see http://www.imt.liu.se/~magnus/cca or contact Magnus Borga' 'EGI_MFF' 'see http://www.egi.com/ or contact either Phan Luu or Colin Davey at EGI' 'TOOLBOX_GRAPH' 'see http://www.mathworks.com/matlabcentral/fileexchange/5355-toolbox-graph or contact Gabriel Peyre' 'NETCDF' 'see http://www.mathworks.com/matlabcentral/fileexchange/15177' 'MYSQL' 'see http://www.mathworks.com/matlabcentral/fileexchange/8663-mysql-database-connector' 'ISO2MESH' 'see http://iso2mesh.sourceforge.net/cgi-bin/index.cgi?Home or contact Qianqian Fang' 'DATAHASH' 'see http://www.mathworks.com/matlabcentral/fileexchange/31272' 'IBTB' 'see http://www.ibtb.org' 'ICASSO' 'see http://www.cis.hut.fi/projects/ica/icasso' 'XUNIT' 'see http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework' 'PLEXON' 'available from http://www.plexon.com/assets/downloads/sdk/ReadingPLXandDDTfilesinMatlab-mexw.zip' }; if nargin<2 % default is not to add the path automatically autoadd = 0; end if nargin<3 % default is not to be silent silent = 0; end % determine whether the toolbox is installed toolbox = upper(toolbox); % set fieldtrip trunk path, used for determining ft-subdirs are on path fttrunkpath = unixpath(fileparts(which('ft_defaults'))); switch toolbox case 'AFNI' status = (exist('BrikLoad') && exist('BrikInfo')); case 'DSS' status = exist('denss', 'file') && exist('dss_create_state', 'file'); case 'EEGLAB' status = exist('runica', 'file'); case 'NWAY' status = exist('parafac', 'file'); case 'SPM' status = exist('spm.m'); % any version of SPM is fine case 'SPM99' status = exist('spm.m') && strcmp(spm('ver'),'SPM99'); case 'SPM2' status = exist('spm.m') && strcmp(spm('ver'),'SPM2'); case 'SPM5' status = exist('spm.m') && strcmp(spm('ver'),'SPM5'); case 'SPM8' status = exist('spm.m') && strncmp(spm('ver'),'SPM8', 4); case 'SPM12' status = exist('spm.m') && strncmp(spm('ver'),'SPM12', 5); case 'MEG-PD' status = (exist('rawdata') && exist('channames')); case 'MEG-CALC' status = (exist('megmodel') && exist('megfield') && exist('megtrans')); case 'BIOSIG' status = (exist('sopen') && exist('sread')); case 'EEG' status = (exist('ctf_read_res4') && exist('ctf_read_meg4')); case 'EEGSF' % alternative name status = (exist('ctf_read_res4') && exist('ctf_read_meg4')); case 'MRI' % other functions in the mri section status = (exist('avw_hdr_read') && exist('avw_img_read')); case 'NEUROSHARE' status = (exist('ns_OpenFile') && exist('ns_SetLibrary') && exist('ns_GetAnalogData')); case 'BESA' status = (exist('readBESAtfc') && exist('readBESAswf')); case 'EEPROBE' status = (exist('read_eep_avr') && exist('read_eep_cnt')); case 'YOKOGAWA' status = hasyokogawa('16bitBeta6'); case 'YOKOGAWA12BITBETA3' status = hasyokogawa('12bitBeta3'); case 'YOKOGAWA16BITBETA3' status = hasyokogawa('16bitBeta3'); case 'YOKOGAWA16BITBETA6' status = hasyokogawa('16bitBeta6'); case 'YOKOGAWA_MEG_READER' status = hasyokogawa('1.4'); case 'BEOWULF' status = (exist('evalwulf') && exist('evalwulf') && exist('evalwulf')); case 'MENTAT' status = (exist('pcompile') && exist('pfor') && exist('peval')); case 'SON2' status = (exist('SONFileHeader') && exist('SONChanList') && exist('SONGetChannel')); case '4D-VERSION' status = (exist('read4d') && exist('read4dhdr')); case {'STATS', 'STATISTICS'} status = license('checkout', 'statistics_toolbox'); % also check the availability of a toolbox license case {'OPTIM', 'OPTIMIZATION'} status = license('checkout', 'optimization_toolbox'); % also check the availability of a toolbox license case {'SPLINES', 'CURVE_FITTING'} status = license('checkout', 'curve_fitting_toolbox'); % also check the availability of a toolbox license case 'SIGNAL' status = license('checkout', 'signal_toolbox'); % also check the availability of a toolbox license case 'IMAGE' status = license('checkout', 'image_toolbox'); % also check the availability of a toolbox license case {'DCT', 'DISTCOMP'} status = license('checkout', 'distrib_computing_toolbox'); % also check the availability of a toolbox license case 'COMPILER' status = license('checkout', 'compiler'); % also check the availability of a toolbox license case 'FASTICA' status = exist('fpica', 'file'); case 'BRAINSTORM' status = exist('bem_xfer'); case 'DENOISE' status = (exist('tsr', 'file') && exist('sns', 'file')); case 'CTF' status = (exist('getCTFBalanceCoefs') && exist('getCTFdata')); case 'BCI2000' status = exist('load_bcidat'); case 'NLXNETCOM' status = (exist('MatlabNetComClient', 'file') && exist('NlxConnectToServer', 'file') && exist('NlxGetNewCSCData', 'file')); case 'DIPOLI' status = exist('dipoli.maci', 'file'); case 'MNE' status = (exist('fiff_read_meas_info', 'file') && exist('fiff_setup_read_raw', 'file')); case 'TCP_UDP_IP' status = (exist('pnet', 'file') && exist('pnet_getvar', 'file') && exist('pnet_putvar', 'file')); case 'BEMCP' status = (exist('bem_Cij_cog', 'file') && exist('bem_Cij_lin', 'file') && exist('bem_Cij_cst', 'file')); case 'OPENMEEG' status = exist('om_save_tri.m', 'file'); case 'PRTOOLS' status = (exist('prversion', 'file') && exist('dataset', 'file') && exist('svc', 'file')); case 'ITAB' status = (exist('lcReadHeader', 'file') && exist('lcReadData', 'file')); case 'BSMART' status = exist('bsmart'); case 'FREESURFER' status = exist('MRIread', 'file') && exist('vox2ras_0to1', 'file'); case 'FNS' status = exist('elecsfwd', 'file'); case 'SIMBIO' status = exist('calc_stiff_matrix_val', 'file') && exist('sb_transfer', 'file'); case 'VGRID' status = exist('vgrid.m', 'file'); case 'GIFTI' status = exist('gifti', 'file'); case 'XML4MAT' status = exist('xml2struct.m', 'file') && exist('xml2whos.m', 'file'); case 'SQDPROJECT' status = exist('sqdread.m', 'file') && exist('sqdwrite.m', 'file'); case 'BCT' status = exist('macaque71.mat', 'file') && exist('motif4funct_wei.m', 'file'); case 'CCA' status = exist('ccabss.m', 'file'); case 'EGI_MFF' status = exist('mff_getObject.m', 'file') && exist('mff_getSummaryInfo.m', 'file'); case 'TOOLBOX_GRAPH' status = exist('toolbox_graph'); case 'NETCDF' status = exist('netcdf'); case 'MYSQL' status = exist(['mysql.' mexext], 'file'); % this only consists of a single mex file case 'ISO2MESH' status = exist('vol2surf.m', 'file') && exist('qmeshcut.m', 'file'); case 'QSUB' status = exist('qsubfeval.m', 'file') && exist('qsubcellfun.m', 'file'); case 'ENGINE' status = exist('enginefeval.m', 'file') && exist('enginecellfun.m', 'file'); case 'DATAHASH' status = exist('DataHash.m', 'file'); case 'IBTB' status = exist('make_ibtb.m', 'file') && exist('binr.m', 'file'); case 'ICASSO' status = exist('icassoEst.m', 'file'); case 'XUNIT' status = exist('initTestSuite.m', 'file') && exist('runtests.m', 'file'); case 'PLEXON' status = exist('plx_adchan_gains.m', 'file') && exist('mexPlex'); % the following are fieldtrip modules/toolboxes case 'FILEIO' status = (exist('ft_read_header', 'file') && exist('ft_read_data', 'file') && exist('ft_read_event', 'file') && exist('ft_read_sens', 'file')); case 'FORWARD' status = (exist('ft_compute_leadfield', 'file') && exist('ft_prepare_vol_sens', 'file')); case 'PLOTTING' status = (exist('ft_plot_topo', 'file') && exist('ft_plot_mesh', 'file') && exist('ft_plot_matrix', 'file')); case 'PEER' status = exist('peerslave', 'file') && exist('peermaster', 'file'); case 'CONNECTIVITY' status = exist('ft_connectivity_corr', 'file') && exist('ft_connectivity_granger', 'file'); case 'SPIKE' status = exist('ft_spiketriggeredaverage.m', 'file') && exist('ft_spiketriggeredspectrum.m', 'file'); % these were missing, added them using the below style, see bug 1804 - roevdmei case 'INVERSE' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/inverse'], 'once')); % INVERSE is not added above, consider doing it there -roevdmei case 'REALTIME' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/realtime'], 'once')); % REALTIME is not added above, consider doing it there -roevdmei case 'SPECEST' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/specest'], 'once')); % SPECEST is not added above, consider doing it there -roevdmei case 'PREPROC' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/preproc'], 'once')); % PREPROC is not added above, consider doing it there -roevdmei % the following are not proper toolboxes, but only subdirectories in the fieldtrip toolbox % these are added in ft_defaults and are specified with unix-style forward slashes case 'COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/compat'], 'once')); case 'STATFUN' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/statfun'], 'once')); case 'TRIALFUN' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/trialfun'], 'once')); case 'UTILITIES/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/utilities/compat'], 'once')); case 'FILEIO/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/fileio/compat'], 'once')); case 'PREPROC/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/preproc/compat'], 'once')); case 'FORWARD/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/forward/compat'], 'once')); case 'PLOTTING/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/plotting/compat'], 'once')); case 'TEMPLATE/LAYOUT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/layout'], 'once')); case 'TEMPLATE/ANATOMY' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/anatomy'], 'once')); case 'TEMPLATE/HEADMODEL' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/headmodel'], 'once')); case 'TEMPLATE/ELECTRODE' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/electrode'], 'once')); case 'TEMPLATE/NEIGHBOURS' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/neighbours'], 'once')); case 'TEMPLATE/SOURCEMODEL' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/sourcemodel'], 'once')); otherwise if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end status = 0; end % it should be a boolean value status = (status~=0); % try to determine the path of the requested toolbox if autoadd>0 && ~status % for core fieldtrip modules prefix = fileparts(which('ft_defaults')); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for external fieldtrip modules prefix = fullfile(fileparts(which('ft_defaults')), 'external'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for contributed fieldtrip extensions prefix = fullfile(fileparts(which('ft_defaults')), 'contrib'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for linux computers in the Donders Centre for Cognitive Neuroimaging prefix = '/home/common/matlab'; if ~status && isunix status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for windows computers in the Donders Centre for Cognitive Neuroimaging prefix = 'h:\common\matlab'; if ~status && ispc status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % use the matlab subdirectory in your homedirectory, this works on linux and mac prefix = fullfile(getenv('HOME'), 'matlab'); if ~status && isdir(prefix) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end if ~status % the toolbox is not on the path and cannot be added sel = find(strcmp(url(:,1), toolbox)); if ~isempty(sel) msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2}); else msg = sprintf('the %s toolbox is not installed', toolbox); end if autoadd==1 error(msg); elseif autoadd==2 warning(msg); else % fail silently end end end % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before if status previous.(fixname(toolbox)) = status; end % remember the previous path, allows us to determine on the next call % whether the path has been modified outise of this function previouspath = path; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = myaddpath(toolbox, silent) if isdeployed warning('cannot change path settings for %s in a compiled application', toolbox); elseif exist(toolbox, 'dir') if ~silent, ws = warning('backtrace', 'off'); warning('adding %s toolbox to your Matlab path', toolbox); warning(ws); % return to the previous warning level end addpath(toolbox); status = 1; else status = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function path = unixpath(path) path(path=='\') = '/'; % replace backward slashes with forward slashes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = hasfunction(funname, toolbox) try % call the function without any input arguments, which probably is inapropriate feval(funname); % it might be that the function without any input already works fine status = true; catch % either the function returned an error, or the function is not available % availability is influenced by the function being present and by having a % license for the function, i.e. in a concurrent licensing setting it might % be that all toolbox licenses are in use m = lasterror; if strcmp(m.identifier, 'MATLAB:license:checkouterror') if nargin>1 warning('the %s toolbox is available, but you don''t have a license for it', toolbox); else warning('the function ''%s'' is available, but you don''t have a license for it', funname); end status = false; elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction') status = false; else % the function seems to be available and it gave an unknown error, % which is to be expected with inappropriate input arguments status = true; end end
github
philippboehmsturm/antx-master
read_yokogawa_data_new.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_yokogawa_data_new.m
5,691
utf_8
0f379a92d07b29f6a231c357f4f02920
function [dat] = read_yokogawa_data_new(filename, hdr, begsample, endsample, chanindx) % READ_YOKAGAWA_DATA_NEW reads continuous, epoched or averaged MEG data % that has been generated by the Yokogawa MEG system and software % and allows that data to be used in combination with FieldTrip. % % Use as % [dat] = read_yokogawa_data_new(filename, hdr, begsample, endsample, chanindx) % % This is a wrapper function around the function % getYkgwData % % See also READ_YOKOGAWA_HEADER_NEW, READ_YOKOGAWA_EVENT % Copyright (C) 2005, Robert Oostenveld and 2010, Tilmann Sander-Thoemmes % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_yokogawa_data_new.m 7123 2012-12-06 21:21:38Z roboos $ if ~ft_hastoolbox('yokogawa_meg_reader') error('cannot determine whether Yokogawa toolbox is present'); end % hdr = read_yokogawa_header(filename); hdr = hdr.orig; % use the original Yokogawa header, not the FieldTrip header % default is to select all channels if nargin<5 chanindx = 1:hdr.channel_count; end handles = definehandles; switch hdr.acq_type case handles.AcqTypeEvokedAve % dat is returned as double start_sample = begsample - 1; % samples start at 0 sample_length = endsample - begsample + 1; epoch_count = 1; start_epoch = 0; dat = getYkgwData(filename, start_sample, sample_length); case handles.AcqTypeContinuousRaw % dat is returned as double start_sample = begsample - 1; % samples start at 0 sample_length = endsample - begsample + 1; epoch_count = 1; start_epoch = 0; dat = getYkgwData(filename, start_sample, sample_length); case handles.AcqTypeEvokedRaw % dat is returned as double begtrial = ceil(begsample/hdr.sample_count); endtrial = ceil(endsample/hdr.sample_count); if begtrial<1 error('cannot read before the begin of the file'); elseif endtrial>hdr.actual_epoch_count error('cannot read beyond the end of the file'); end epoch_count = endtrial-begtrial+1; start_epoch = begtrial-1; % read all the neccessary trials that contain the desired samples dat = getYkgwData(filename, start_epoch, epoch_count); if size(dat,2)~=epoch_count*hdr.sample_count error('could not read all epochs'); end rawbegsample = begsample - (begtrial-1)*hdr.sample_count; rawendsample = endsample - (begtrial-1)*hdr.sample_count; sample_length = rawendsample - rawbegsample + 1; % select the desired samples from the complete trials dat = dat(:,rawbegsample:rawendsample); otherwise error('unknown data type'); end if size(dat,1)~=hdr.channel_count error('could not read all channels'); elseif size(dat,2)~=(endsample-begsample+1) error('could not read all samples'); end % select only the desired channels dat = dat(chanindx,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.eegchannel_ch_no = []; handles.sqd.eegchannel_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
philippboehmsturm/antx-master
read_plexon_nex.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_plexon_nex.m
7,633
utf_8
64b3b2124d2af848afb0d1746f422818
function [varargout] = read_plexon_nex(filename, varargin) % READ_PLEXON_NEX reads header or data from a Plexon *.nex file, which % is a file containing action-potential (spike) timestamps and waveforms % (spike channels), event timestamps (event channels), and continuous % variable data (continuous A/D channels). % % LFP and spike waveform data that is returned by this function is % expressed in microVolt. % % Use as % [hdr] = read_plexon_nex(filename) % [dat] = read_plexon_nex(filename, ...) % [dat1, dat2, dat3, hdr] = read_plexon_nex(filename, ...) % % Optional arguments should be specified in key-value pairs and can be % header structure with header information % feedback 0 or 1 % tsonly 0 or 1, read only the timestamps and not the waveforms % channel number, or list of numbers (that will result in multiple outputs) % begsample number (for continuous only) % endsample number (for continuous only) % % See also READ_PLEXON_PLX, READ_PLEXON_DDT % Copyright (C) 2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_plexon_nex.m 7123 2012-12-06 21:21:38Z roboos $ % parse the optional input arguments hdr = ft_getopt(varargin, 'header'); channel = ft_getopt(varargin, 'channel'); feedback = ft_getopt(varargin, 'feedback', false); tsonly = ft_getopt(varargin, 'tsonly', false); begsample = ft_getopt(varargin, 'begsample', 1); endsample = ft_getopt(varargin, 'endsample', inf); % start with empty return values and empty data varargout = {}; % read header info from file, use Matlabs for automatic byte-ordering fid = fopen(filename, 'r', 'ieee-le'); fseek(fid, 0, 'eof'); siz = ftell(fid); fseek(fid, 0, 'bof'); if isempty(hdr) if feedback, fprintf('reading header from %s\n', filename); end % a NEX file consists of a file header, followed by a number of variable headers % sizeof(NexFileHeader) = 544 % sizeof(NexVarHeader) = 208 hdr.FileHeader = NexFileHeader(fid); if hdr.FileHeader.NumVars<1 error('no channels present in file'); end hdr.VarHeader = NexVarHeader(fid, hdr.FileHeader.NumVars); end for i=1:length(channel) chan = channel(i); vh = hdr.VarHeader(chan); clear buf fseek(fid, vh.DataOffset, 'bof'); switch vh.Type case 0 % Neurons, only timestamps buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); case 1 % Events, only timestamps buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); case 2 % Interval variables buf.begs = fread(fid, [1 vh.Count], 'int32=>int32'); buf.ends = fread(fid, [1 vh.Count], 'int32=>int32'); case 3 % Waveform variables buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); if ~tsonly buf.dat = fread(fid, [vh.NPointsWave vh.Count], 'int16'); % convert the AD values to miliVolt, subsequently convert from miliVolt to microVolt buf.dat = buf.dat * (vh.ADtoMV * 1000); end case 4 % Population vector error('population vectors are not supported'); case 5 % Continuously recorded variables buf.ts = fread(fid, [1 vh.Count], 'int32=>int32'); buf.indx = fread(fid, [1 vh.Count], 'int32=>int32'); if vh.Count>1 && (begsample~=1 || endsample~=inf) error('reading selected samples from multiple AD segments is not supported'); end if ~tsonly numsample = min(endsample - begsample + 1, vh.NPointsWave); fseek(fid, (begsample-1)*2, 'cof'); buf.dat = fread(fid, [1 numsample], 'int16'); % convert the AD values to miliVolt, subsequently convert from miliVolt to microVolt buf.dat = buf.dat * (vh.ADtoMV * 1000); end case 6 % Markers ts = fread(fid, [1 vh.Count], 'int32=>int32'); for j=1:vh.NMarkers buf.MarkerNames{j,1} = fread(fid, [1 64], 'uint8=>char'); for k=1:vh.Count buf.MarkerValues{j,k} = fread(fid, [1 vh.MarkerLength], 'uint8=>char'); end end otherwise error('incorrect channel type'); end % switch channel type % return the data of this channel varargout{i} = buf; end % for channel % always return the header as last varargout{end+1} = hdr; fclose(fid); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = NexFileHeader(fid); hdr.NexFileHeader = fread(fid,4,'uint8=>char')'; % string NEX1 hdr.Version = fread(fid,1,'int32'); hdr.Comment = fread(fid,256,'uint8=>char')'; hdr.Frequency = fread(fid,1,'double'); % timestamped freq. - tics per second hdr.Beg = fread(fid,1,'int32'); % usually 0 hdr.End = fread(fid,1,'int32'); % maximum timestamp + 1 hdr.NumVars = fread(fid,1,'int32'); % number of variables in the first batch hdr.NextFileHeader = fread(fid,1,'int32'); % position of the next file header in the file, not implemented yet Padding = fread(fid,256,'uint8=>char')'; % future expansion %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = NexVarHeader(fid, numvar); for varlop=1:numvar hdr(varlop).Type = fread(fid,1,'int32'); % 0 - neuron, 1 event, 2- interval, 3 - waveform, 4 - pop. vector, 5 - continuously recorded hdr(varlop).Version = fread(fid,1,'int32'); % 100 hdr(varlop).Name = fread(fid,64,'uint8=>char')'; % variable name hdr(varlop).DataOffset = fread(fid,1,'int32'); % where the data array for this variable is located in the file hdr(varlop).Count = fread(fid,1,'int32'); % number of events, intervals, waveforms or weights hdr(varlop).WireNumber = fread(fid,1,'int32'); % neuron only, not used now hdr(varlop).UnitNumber = fread(fid,1,'int32'); % neuron only, not used now hdr(varlop).Gain = fread(fid,1,'int32'); % neuron only, not used now hdr(varlop).Filter = fread(fid,1,'int32'); % neuron only, not used now hdr(varlop).XPos = fread(fid,1,'double'); % neuron only, electrode position in (0,100) range, used in 3D hdr(varlop).YPos = fread(fid,1,'double'); % neuron only, electrode position in (0,100) range, used in 3D hdr(varlop).WFrequency = fread(fid,1,'double'); % waveform and continuous vars only, w/f sampling frequency hdr(varlop).ADtoMV = fread(fid,1,'double'); % waveform continuous vars only, coeff. to convert from A/D values to Millivolts hdr(varlop).NPointsWave = fread(fid,1,'int32'); % waveform only, number of points in each wave hdr(varlop).NMarkers = fread(fid,1,'int32'); % how many values are associated with each marker hdr(varlop).MarkerLength = fread(fid,1,'int32'); % how many characters are in each marker value Padding = fread(fid,68,'uint8=>char')'; end
github
philippboehmsturm/antx-master
read_bti_m4d.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_bti_m4d.m
5,505
utf_8
1c319e059794d81ea2fe302a09a2ba73
function [msi] = read_bti_m4d(filename) % READ_BTI_M4D % % Use as % msi = read_bti_m4d(filename) % Copyright (C) 2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_bti_m4d.m 7123 2012-12-06 21:21:38Z roboos $ [p, f, x] = fileparts(filename); if ~strcmp(x, '.m4d') % add the extension of the header filename = [filename '.m4d']; end fid = fopen(filename, 'r'); if fid==-1 error(sprintf('could not open file %s', filename)); end % start with an empty header structure msi = struct; % these header elements contain strings and should be converted in a cell-array strlist = { 'MSI.ChannelOrder' }; % these header elements contain numbers and should be converted in a numeric array % 'MSI.ChannelScale' % 'MSI.ChannelGain' % 'MSI.FileType' % 'MSI.TotalChannels' % 'MSI.TotalEpochs' % 'MSI.SamplePeriod' % 'MSI.SampleFrequency' % 'MSI.FirstLatency' % 'MSI.SlicesPerEpoch' % the conversion to numeric arrays is implemented in a general fashion % and all the fields above are automatically converted numlist = {}; line = ''; msi.grad.label = {}; msi.grad.coilpos = zeros(0,3); msi.grad.coilori = zeros(0,3); while ischar(line) line = cleanline(fgetl(fid)); if isempty(line) || (length(line)==1 && all(line==-1)) continue end sep = strfind(line, ':'); if length(sep)==1 key = line(1:(sep-1)); val = line((sep+1):end); elseif length(sep)>1 % assume that the first separator is the relevant one, and that the % next ones are part of the value string (e.g. a channel with a ':' in % its name sep = sep(1); key = line(1:(sep-1)); val = line((sep+1):end); elseif length(sep)<1 % this is not what I would expect error('unexpected content in m4d file'); end if ~isempty(strfind(line, 'Begin')) sep = strfind(key, '.'); sep = sep(end); key = key(1:(sep-1)); % if the key ends with begin and there is no value, then there is a block % of numbers following that relates to the magnetometer/gradiometer information. % All lines in that Begin-End block should be treated seperately val = {}; lab = {}; num = {}; ind = 0; while isempty(strfind(line, 'End')) line = cleanline(fgetl(fid)); if isempty(line) || (length(line)==1 && all(line==-1)) || ~isempty(strfind(line, 'End')) continue end ind = ind+1; % remember the line itself, and also cut it into pieces val{ind} = line; % the line is tab-separated and looks like this % A68 0.0873437 -0.075789 0.0891512 0.471135 -0.815532 0.336098 sep = find(line==9); % the ascii value of a tab is 9 sep = sep(1); lab{ind} = line(1:(sep-1)); num{ind} = str2num(line((sep+1):end)); end % parsing Begin-End block val = val(:); lab = lab(:); num = num(:); num = cell2mat(num); % the following is FieldTrip specific if size(num,2)==6 msi.grad.label = [msi.grad.label; lab(:)]; % the numbers represent position and orientation of each magnetometer coil msi.grad.coilpos = [msi.grad.coilpos; num(:,1:3)]; msi.grad.coilori = [msi.grad.coilori; num(:,4:6)]; else error('unknown gradiometer design') end end % the key looks like 'MSI.fieldname.subfieldname' fieldname = key(5:end); % remove spaces from the begin and end of the string val = strtrim(val); % try to convert the value string into something more usefull if ~iscell(val) % the value can contain a variety of elements, only some of which are decoded here if ~isempty(strfind(key, 'Index')) || ~isempty(strfind(key, 'Count')) || any(strcmp(key, numlist)) % this contains a single number or a comma-separated list of numbers val = str2num(val); elseif ~isempty(strfind(key, 'Names')) || any(strcmp(key, strlist)) % this contains a comma-separated list of strings val = tokenize(val, ','); else tmp = str2num(val); if ~isempty(tmp) val = tmp; end end end % assign this header element to the structure msi = setsubfield(msi, fieldname, val); end % while ischar(line) % each coil weighs with a value of 1 into each channel msi.grad.tra = eye(size(msi.grad.coilpos,1)); msi.grad.unit = 'm'; fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION to remove spaces from the begin and end % and to remove comments from the lines %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function line = cleanline(line) if isempty(line) || (length(line)==1 && all(line==-1)) return end comment = findstr(line, '//'); if ~isempty(comment) line(min(comment):end) = ' '; end line = strtrim(line);
github
philippboehmsturm/antx-master
read_asa.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_asa.m
3,857
utf_8
bd6525da96c296723f6a29b027b2445e
function [val] = read_asa(filename, elem, format, number, token) % READ_ASA reads a specified element from an ASA file % % val = read_asa(filename, element, type, number) % % where the element is a string such as % NumberSlices % NumberPositions % Rows % Columns % etc. % % and format specifies the datatype according to % %d (integer value) % %f (floating point value) % %s (string) % % number is optional to specify how many lines of data should be read % The default is 1 for strings and Inf for numbers. % % token is optional to specifiy a character that separates the values from % anything not wanted. % Copyright (C) 2002-2012, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_asa.m 7123 2012-12-06 21:21:38Z roboos $ fid = fopen(filename, 'rt'); if fid==-1 error(sprintf('could not open file %s', filename)); end if nargin<4 if strcmp(format, '%s') number = 1; else number = Inf; end end if nargin<5 token = ''; end val = []; elem = strtrim(lower(elem)); while (1) line = fgetl(fid); if ~isempty(line) && isequal(line, -1) % prematurely reached end of file fclose(fid); return end line = strtrim(line); lower_line = lower(line); if strmatch(elem, lower_line) data = line((length(elem)+1):end); break end end while isempty(data) line = fgetl(fid); if isequal(line, -1) % prematurely reached end of file fclose(fid); return end data = strtrim(line); end if strcmp(format, '%s') if number==1 % interpret the data as a single string, create char-array val = detoken(strtrim(data), token); if val(1)=='=' val = val(2:end); % remove the trailing = end fclose(fid); return end % interpret the data as a single string, create cell-array val{1} = detoken(strtrim(data), token); count = 1; % read the remaining strings while count<number line = fgetl(fid); if ~isempty(line) && isequal(line, -1) fclose(fid); return end tmp = sscanf(line, format); if isempty(tmp) fclose(fid); return else count = count + 1; val{count} = detoken(strtrim(line), token); end end else % interpret the data as numeric, create numeric array count = 1; data = sscanf(detoken(data, token), format)'; if isempty(data), fclose(fid); return else val(count,:) = data; end % read remaining numeric data while count<number line = fgetl(fid); if ~isempty(line) && isequal(line, -1) fclose(fid); return end data = sscanf(detoken(line, token), format)'; if isempty(data) fclose(fid); return else count = count+1; val(count,:) = data; end end end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [out] = detoken(in, token) if isempty(token) out = in; return; end [tok rem] = strtok(in, token); if isempty(rem) out = in; return; else out = strtok(rem, token); return end
github
philippboehmsturm/antx-master
nanmean.m
.m
antx-master/xspm8/external/fieldtrip/fileio/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
ft_checkdata.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/ft_checkdata.m
68,446
utf_8
826e5a3878076ce68bb166d5afbfe9fd
function [data] = ft_checkdata(data, varargin) % FT_CHECKDATA checks the input data of the main FieldTrip functions, e.g. whether % the type of data strucure corresponds with the required data. If neccessary % and possible, this function will adjust the data structure to the input % requirements (e.g. change dimord, average over trials, convert inside from % index into logical). % % If the input data does NOT correspond to the requirements, this function % is supposed to give a elaborate warning message and if applicable point % the user to external documentation (link to website). % % Use as % [data] = ft_checkdata(data, ...) % % Optional input arguments should be specified as key-value pairs and can include % feedback = yes, no % datatype = raw, freq, timelock, comp, spike, source, dip, volume, segmentation, parcellation % dimord = any combination of time, freq, chan, refchan, rpt, subj, chancmb, rpttap, pos % senstype = ctf151, ctf275, ctf151_planar, ctf275_planar, neuromag122, neuromag306, bti148, bti248, bti248_planar, magnetometer, electrode % inside = logical, index % ismeg = yes, no % hastrials = yes, no % hasunits = yes, no % hassampleinfo = yes, no, ifmakessense (only applies to raw data) % hascumtapcnt = yes, no (only applies to freq data) % hasdim = yes, no % hasdof = yes, no % cmbrepresentation = sparse, full (applies to covariance and cross-spectral density) % fsample = sampling frequency to use to go from SPIKE to RAW representation % segmentationstyle = indexed, probabilistic (only applies to segmentation) % parcellationstyle = indexed, probabilistic (only applies to parcellation) % hasbrain = yes, no (only applies to segmentation) % % For some options you can specify multiple values, e.g. % [data] = ft_checkdata(data, 'senstype', {'ctf151', 'ctf275'}), e.g. in megrealign % [data] = ft_checkdata(data, 'datatype', {'timelock', 'freq'}), e.g. in sourceanalysis % Copyright (C) 2007-2012, Robert Oostenveld % Copyright (C) 2010-2012, Martin Vinck % % 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_checkdata.m 7394 2013-01-23 14:33:30Z jorhor $ % in case of an error this function could use dbstack for more detailled % user feedback % % this function should replace/encapsulate % fixdimord % fixinside % fixprecision % fixvolume % data2raw % raw2data % grid2transform % transform2grid % fourier2crsspctrm % freq2cumtapcnt % sensortype % time2offset % offset2time % fixsens -> this is kept a separate function because it should also be % called from other modules % % other potential uses for this function: % time -> offset in freqanalysis % average over trials % csd as matrix % get the optional input arguments feedback = ft_getopt(varargin, 'feedback', 'no'); dtype = ft_getopt(varargin, 'datatype'); % should not conflict with the ft_datatype function dimord = ft_getopt(varargin, 'dimord'); stype = ft_getopt(varargin, 'senstype'); % senstype is a function name which should not be masked ismeg = ft_getopt(varargin, 'ismeg'); inside = ft_getopt(varargin, 'inside'); % can be 'logical' or 'index' hastrials = ft_getopt(varargin, 'hastrials'); hasunits = ft_getopt(varargin, 'hasunits'); hassampleinfo = ft_getopt(varargin, 'hassampleinfo', 'ifmakessense'); hasdimord = ft_getopt(varargin, 'hasdimord', 'no'); hasdim = ft_getopt(varargin, 'hasdim'); hascumtapcnt = ft_getopt(varargin, 'hascumtapcnt'); hasdof = ft_getopt(varargin, 'hasdof', 'no'); haspow = ft_getopt(varargin, 'haspow', 'no'); cmbrepresentation = ft_getopt(varargin, 'cmbrepresentation'); channelcmb = ft_getopt(varargin, 'channelcmb'); sourcedimord = ft_getopt(varargin, 'sourcedimord'); sourcerepresentation = ft_getopt(varargin, 'sourcerepresentation'); fsample = ft_getopt(varargin, 'fsample'); segmentationstyle = ft_getopt(varargin, 'segmentationstyle'); % this will be passed on to the corresponding ft_datatype_xxx function parcellationstyle = ft_getopt(varargin, 'parcellationstyle'); % this will be passed on to the corresponding ft_datatype_xxx function hasbrain = ft_getopt(varargin, 'hasbrain'); % check whether people are using deprecated stuff depHastrialdef = ft_getopt(varargin, 'hastrialdef'); if (~isempty(depHastrialdef)) warning_once('ft_checkdata option ''hastrialdef'' is deprecated; use ''hassampleinfo'' instead'); hassampleinfo = depHastrialdef; end if (~isempty(ft_getopt(varargin, 'hasoffset'))) warning_once('ft_checkdata option ''hasoffset'' has been removed and will be ignored'); end % determine the type of input data % this can be raw, freq, timelock, comp, spike, source, volume, dip israw = ft_datatype(data, 'raw'); isfreq = ft_datatype(data, 'freq'); istimelock = ft_datatype(data, 'timelock'); iscomp = ft_datatype(data, 'comp'); isspike = ft_datatype(data, 'spike'); isvolume = ft_datatype(data, 'volume'); issegmentation = ft_datatype(data, 'segmentation'); isparcellation = ft_datatype(data, 'parcellation'); issource = ft_datatype(data, 'source'); isdip = ft_datatype(data, 'dip'); ismvar = ft_datatype(data, 'mvar'); isfreqmvar = ft_datatype(data, 'freqmvar'); ischan = ft_datatype(data, 'chan'); % FIXME use the istrue function on ismeg and hasxxx options if ~isequal(feedback, 'no') if iscomp % it can be comp and raw at the same time, therefore this has to go first ncomp = length(data.label); nchan = length(data.topolabel); fprintf('the input is component data with %d components and %d original channels\n', ncomp, nchan); elseif israw nchan = length(data.label); ntrial = length(data.trial); fprintf('the input is raw data with %d channels and %d trials\n', nchan, ntrial); elseif istimelock nchan = length(data.label); ntime = length(data.time); fprintf('the input is timelock data with %d channels and %d timebins\n', nchan, ntime); elseif isfreq nchan = length(data.label); nfreq = length(data.freq); if isfield(data, 'time'), ntime = num2str(length(data.time)); else ntime = 'no'; end fprintf('the input is freq data with %d channels, %d frequencybins and %s timebins\n', nchan, nfreq, ntime); elseif isspike nchan = length(data.label); fprintf('the input is spike data with %d channels\n', nchan); elseif isvolume if issegmentation subtype = 'segmented volume'; else subtype = 'volume'; end fprintf('the input is %s data with dimensions [%d %d %d]\n', subtype, data.dim(1), data.dim(2), data.dim(3)); clear subtype elseif issource nsource = size(data.pos, 1); if isparcellation subtype = 'parcellated source'; else subtype = 'source'; end if isfield(data, 'dim') fprintf('the input is %s data with %d positions on a [%d %d %d] grid\n', subtype, nsource, data.dim(1), data.dim(2), data.dim(3)); elseif isfield(data, 'tri') fprintf('the input is %s data with %d vertex positions and %d triangles\n', subtype, nsource, size(data.tri, 1)); else fprintf('the input is %s data with %d positions\n', subtype, nsource); end clear subtype elseif isdip fprintf('the input is dipole data\n'); elseif ismvar fprintf('the input is mvar data\n'); elseif isfreqmvar fprintf('the input is freqmvar data\n'); elseif ischan nchan = length(data.label); fprintf('the input is chan data\n'); end end % give feedback if issource && isvolume % it should be either one or the other: the choice here is to % represent it as volume description since that is simpler to handle % the conversion is done by remove the grid positions data = rmfield(data, 'pos'); issource = false; end % the ft_datatype_XXX functions ensures the consistency of the XXX datatype % and provides a detailed description of the dataformat and its history if isfreq data = ft_datatype_freq(data); elseif istimelock data = ft_datatype_timelock(data); elseif isspike data = ft_datatype_spike(data); elseif iscomp % this should go before israw data = ft_datatype_comp(data, 'hassampleinfo', hassampleinfo); elseif israw data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); elseif issegmentation % this should go before isvolume data = ft_datatype_segmentation(data, 'segmentationstyle', segmentationstyle, 'hasbrain', hasbrain); elseif isvolume data = ft_datatype_volume(data); elseif isparcellation % this should go before issource data = ft_datatype_parcellation(data, 'parcellationstyle', parcellationstyle); elseif issource data = ft_datatype_source(data); elseif isdip data = ft_datatype_dip(data); elseif ismvar || isfreqmvar data = ft_datatype_mvar(data); end if ~isempty(dtype) if ~isa(dtype, 'cell') dtype = {dtype}; end okflag = 0; for i=1:length(dtype) % check that the data matches with one or more of the required ft_datatypes switch dtype{i} case 'raw' okflag = okflag + israw; case 'freq' okflag = okflag + isfreq; case 'timelock' okflag = okflag + istimelock; case 'comp' okflag = okflag + iscomp; case 'spike' okflag = okflag + isspike; case 'volume' okflag = okflag + isvolume; case 'source' okflag = okflag + issource; case 'dip' okflag = okflag + isdip; case 'mvar' okflag = okflag + ismvar; case 'freqmvar' okflag = okflag + isfreqmvar; case 'chan' okflag = okflag + ischan; case 'segmentation' okflag = okflag + issegmentation; case 'parcellation' okflag = okflag + isparcellation; end % switch dtype end % for dtype if ~okflag % try to convert the data for iCell = 1:length(dtype) if isequal(dtype(iCell), {'source'}) && isvolume data = volume2source(data); data = ft_datatype_source(data); isvolume = 0; issource = 1; okflag = 1; elseif isequal(dtype(iCell), {'volume'}) && issource data = source2volume(data); data = ft_datatype_volume(data); isvolume = 1; issource = 0; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && issource data = data2raw(data); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); issource = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && istimelock data = timelock2raw(data); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); istimelock = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'timelock'}) && iscomp % this should go before israw data = comp2raw(data); data = raw2timelock(data); data = ft_datatype_timelock(data); iscomp = 0; israw = 0; istimelock = 1; okflag = 1; elseif isequal(dtype(iCell), {'timelock'}) && israw data = raw2timelock(data); data = ft_datatype_timelock(data); israw = 0; istimelock = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && isfreq data = freq2raw(data); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); isfreq = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && iscomp % this is never executed, because when iscomp==true, then also israw==true data = comp2raw(data); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); iscomp = 0; israw = 1; okflag = 1; elseif isequal(dtype(iCell), {'timelock'}) && ischan data = chan2timelock(data); data = ft_datatype_timelock(data); ischan = 0; istimelock = 1; okflag = 1; elseif isequal(dtype(iCell), {'freq'}) && ischan data = chan2freq(data); data = ft_datatype_freq(data); ischan = 0; isfreq = 1; okflag = 1; elseif isequal(dtype(iCell), {'spike'}) && israw data = raw2spike(data); data = ft_datatype_spike(data); israw = 0; isspike = 1; okflag = 1; elseif isequal(dtype(iCell), {'raw'}) && isspike data = spike2raw(data,fsample); data = ft_datatype_raw(data, 'hassampleinfo', hassampleinfo); isspike = 0; israw = 1; okflag = 1; end end % for iCell end % if okflag if ~okflag % construct an error message if length(dtype)>1 str = sprintf('%s, ', dtype{1:(end-2)}); str = sprintf('%s%s or %s', str, dtype{end-1}, dtype{end}); else str = dtype{1}; end str = sprintf('This function requires %s data as input.', str); error(str); end % if okflag end if ~isempty(dimord) if ~isa(dimord, 'cell') dimord = {dimord}; end if isfield(data, 'dimord') okflag = any(strcmp(data.dimord, dimord)); else okflag = 0; end if ~okflag % construct an error message if length(dimord)>1 str = sprintf('%s, ', dimord{1:(end-2)}); str = sprintf('%s%s or %s', str, dimord{end-1}, dimord{end}); else str = dimord{1}; end str = sprintf('This function requires data with a dimord of %s.', str); error(str); end % if okflag end if ~isempty(stype) if ~isa(stype, 'cell') stype = {stype}; end if isfield(data, 'grad') || isfield(data, 'elec') if any(strcmp(ft_senstype(data), stype)); okflag = 1; else okflag = 0; end else okflag = 0; end if ~okflag % construct an error message if length(stype)>1 str = sprintf('%s, ', stype{1:(end-2)}); str = sprintf('%s%s or %s', str, stype{end-1}, stype{end}); else str = stype{1}; end str = sprintf('This function requires %s data as input, but you are giving %s data.', str, ft_senstype(data)); error(str); end % if okflag end if ~isempty(ismeg) if isequal(ismeg, 'yes') okflag = isfield(data, 'grad'); elseif isequal(ismeg, 'no') okflag = ~isfield(data, 'grad'); end if ~okflag && isequal(ismeg, 'yes') error('This function requires MEG data with a ''grad'' field'); elseif ~okflag && isequal(ismeg, 'no') error('This function should not be given MEG data with a ''grad'' field'); end % if okflag end if ~isempty(inside) % TODO absorb the fixinside function into this code data = fixinside(data, inside); okflag = isfield(data, 'inside'); if ~okflag % construct an error message error('This function requires data with an ''inside'' field.'); end % if okflag end %if isvolume % % ensure consistent dimensions of the volumetric data % % reshape each of the volumes that is found into a 3D array % param = parameterselection('all', data); % dim = data.dim; % for i=1:length(param) % tmp = getsubfield(data, param{i}); % tmp = reshape(tmp, dim); % data = setsubfield(data, param{i}, tmp); % end %end if isequal(hasunits, 'yes') && ~isfield(data, 'units') % calling convert_units with only the input data adds the units without converting data = ft_convert_units(data); end if issource || isvolume, % the following section is to make a dimord-consistent representation of % volume and source data, taking trials, time and frequency into account if isequal(hasdimord, 'yes') && (~isfield(data, 'dimord') || ~strcmp(data.dimord,sourcedimord)) % determine the size of the data if isfield(data, 'dimord'), dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('time', dimtok)), Ntime = length(data.time); else Ntime = 1; end if ~isempty(strmatch('freq', dimtok)), Nfreq = length(data.freq); else Nfreq = 1; end else Nfreq = 1; Ntime = 1; end %convert old style source representation into new style if isfield(data, 'avg') && isfield(data.avg, 'mom') && (isfield(data, 'freq') || isfield(data, 'frequency')) && strcmp(sourcedimord, 'rpt_pos'), %frequency domain source representation convert to single trial power Npos = size(data.pos,1); Nrpt = size(data.cumtapcnt,1); tmpmom = zeros(Npos, size(data.avg.mom{data.inside(1)},2)); tmpmom(data.inside,:) = cat(1,data.avg.mom{data.inside}); tmppow = zeros(Npos, Nrpt); tapcnt = [0;cumsum(data.cumtapcnt)]; for k = 1:Nrpt Ntap = tapcnt(k+1)-tapcnt(k); tmppow(data.inside,k) = sum(abs(tmpmom(data.inside,(tapcnt(k)+1):tapcnt(k+1))).^2,2)./Ntap; end data.pow = tmppow'; data = rmfield(data, 'avg'); if strcmp(inside, 'logical'), data = fixinside(data, 'logical'); data.inside = repmat(data.inside(:)',[Nrpt 1]); end elseif isfield(data, 'avg') && isfield(data.avg, 'mom') && (isfield(data, 'freq') || isfield(data, 'frequency')) && strcmp(sourcedimord, 'rpttap_pos'), %frequency domain source representation convert to single taper fourier coefficients Npos = size(data.pos,1); Nrpt = sum(data.cumtapcnt); data.fourierspctrm = complex(zeros(Nrpt, Npos), zeros(Nrpt, Npos)); data.fourierspctrm(:, data.inside) = transpose(cat(1, data.avg.mom{data.inside})); data = rmfield(data, 'avg'); elseif isfield(data, 'avg') && isfield(data.avg, 'mom') && isfield(data, 'time') && strcmp(sourcedimord, 'pos_time'), Npos = size(data.pos,1); Nrpt = 1; tmpmom = zeros(Npos, size(data.avg.mom{data.inside(1)},2)); tmpmom(data.inside,:) = cat(1,data.avg.mom{data.inside}); data.mom = tmpmom; if isfield(data.avg, 'noise'), tmpnoise = data.avg.noise(:); data.noise = tmpnoise(:,ones(1,size(tmpmom,2))); end data = rmfield(data, 'avg'); Ntime = length(data.time); elseif isfield(data, 'trial') && isfield(data.trial(1), 'mom') && isfield(data, 'time') && strcmp(sourcedimord, 'rpt_pos_time'), Npos = size(data.pos,1); Nrpt = length(data.trial); Ntime = length(data.time); tmpmom = zeros(Nrpt, Npos, Ntime); for k = 1:Nrpt tmpmom(k,data.inside,:) = cat(1,data.trial(k).mom{data.inside}); end data = rmfield(data, 'trial'); data.mom = tmpmom; elseif isfield(data, 'trial') && isstruct(data.trial) Nrpt = length(data.trial); else Nrpt = 1; end % start with an initial specification of the dimord and dim if (~isfield(data, 'dim') || ~isfield(data, 'dimord')) if issource % at least it should have a Nx3 pos data.dim = size(data.pos, 1); data.dimord = 'pos'; elseif isvolume % at least it should have a 1x3 dim data.dim = data.dim; data.dimord = 'dim1_dim2_dim3'; end end % add the additional dimensions if Nfreq>1 data.dimord = [data.dimord '_freq']; data.dim = [data.dim Nfreq]; end if Ntime>1 data.dimord = [data.dimord '_time']; data.dim = [data.dim Ntime]; end if Nrpt>1 && strcmp(sourcedimord, 'rpt_pos'), data.dimord = ['rpt_' data.dimord]; data.dim = [Nrpt data.dim ]; elseif Nrpt>1 && strcmp(sourcedimord, 'rpttap_pos'), data.dimord = ['rpttap_' data.dimord]; data.dim = [Nrpt data.dim ]; end % the nested trial structure is not compatible with dimord if isfield(data, 'trial') && isstruct(data.trial) param = fieldnames(data.trial); for i=1:length(param) if isa(data.trial(1).(param{i}), 'cell') concat = cell(data.dim(1), prod(data.dim(2:end))); else concat = zeros(data.dim(1), prod(data.dim(2:end))); end for j=1:length(data.trial) tmp = data.trial(j).(param{i}); concat(j,:) = tmp(:); end % for each trial data.trial = rmfield(data.trial, param{i}); data.(param{i}) = reshape(concat, data.dim); end % for each param data = rmfield(data, 'trial'); end end % ensure consistent dimensions of the source reconstructed data % reshape each of the source reconstructed parameters if issource && isfield(data, 'dim') && prod(data.dim)==size(data.pos,1) dim = [prod(data.dim) 1]; %elseif issource && any(~cellfun('isempty',strfind(fieldnames(data), 'dimord'))) % dim = [size(data.pos,1) 1]; %sparsely represented source structure new style elseif isfield(data, 'dim'), dim = [data.dim 1]; elseif issource && ~isfield(data, 'dimord') dim = [size(data.pos,1) 1]; elseif isfield(data, 'dimord'), %HACK dimtok = tokenize(data.dimord, '_'); for i=1:length(dimtok) if strcmp(dimtok(i), 'pos') dim(1,i) = size(getsubfield(data,dimtok{i}),1); elseif strcmp(dimtok(i), 'rpt') dim(1,i) = nan; else dim(1,i) = length(getsubfield(data,dimtok{i})); end end i = find(isnan(dim)); if ~isempty(i) n = fieldnames(data); for ii=1:length(n) numels(1,ii) = numel(getfield(data,n{ii})); end nrpt = numels./prod(dim(setdiff(1:length(dim),i))); nrpt = nrpt(nrpt==round(nrpt)); dim(i) = max(nrpt); end if numel(dim)==1, dim(1,2) = 1; end; end % these fields should not be reshaped exclude = {'cfg' 'fwhm' 'leadfield' 'q' 'rough' 'pos'}; if ~isempty(inside) && ~strcmp(inside, 'logical') % also exclude the inside/outside from being reshaped exclude = cat(2, exclude, {'inside' 'outside'}); end param = setdiff(parameterselection('all', data), exclude); for i=1:length(param) if any(param{i}=='.') % the parameter is nested in a substructure, which can have multiple elements (e.g. source.trial(1).pow, source.trial(2).pow, ...) % loop over the substructure array and reshape for every element tok = tokenize(param{i}, '.'); sub1 = tok{1}; % i.e. this would be 'trial' sub2 = tok{2}; % i.e. this would be 'pow' tmp1 = getfield(data, sub1); for j=1:numel(tmp1) tmp2 = getfield(tmp1(j), sub2); if prod(dim)==numel(tmp2) tmp2 = reshape(tmp2, dim); end tmp1(j) = setfield(tmp1(j), sub2, tmp2); end data = setfield(data, sub1, tmp1); else tmp = getfield(data, param{i}); if prod(dim)==numel(tmp) tmp = reshape(tmp, dim); end data = setfield(data, param{i}, tmp); end end end if isequal(hastrials, 'yes') okflag = isfield(data, 'trial'); if ~okflag && isfield(data, 'dimord') % instead look in the dimord for rpt or subj okflag = ~isempty(strfind(data.dimord, 'rpt')) || ... ~isempty(strfind(data.dimord, 'rpttap')) || ... ~isempty(strfind(data.dimord, 'subj')); end if ~okflag error('This function requires data with a ''trial'' field'); end % if okflag end if isequal(hasdim, 'yes') && ~isfield(data, 'dim') data.dim = pos2dim(data.pos); elseif isequal(hasdim, 'no') && isfield(data, 'dim') data = rmfield(data, 'dim'); end % if hasdim if isequal(hascumtapcnt, 'yes') && ~isfield(data, 'cumtapcnt') error('This function requires data with a ''cumtapcnt'' field'); elseif isequal(hascumtapcnt, 'no') && isfield(data, 'cumtapcnt') data = rmfield(data, 'cumtapcnt'); end % if hascumtapcnt if isequal(hasdof, 'yes') && ~isfield(data, 'hasdof') error('This function requires data with a ''dof'' field'); elseif isequal(hasdof, 'no') && isfield(data, 'hasdof') data = rmfield(data, 'cumtapcnt'); end % if hasdof if ~isempty(cmbrepresentation) if istimelock data = fixcov(data, cmbrepresentation); elseif isfreq data = fixcsd(data, cmbrepresentation, channelcmb); elseif isfreqmvar data = fixcsd(data, cmbrepresentation, channelcmb); else error('This function requires data with a covariance, coherence or cross-spectrum'); end end % cmbrepresentation if issource && ~isempty(sourcerepresentation) data = fixsource(data, 'type', sourcerepresentation); end if issource && ~strcmp(haspow, 'no') data = fixsource(data, 'type', sourcerepresentation, 'haspow', haspow); end if isfield(data, 'grad') % ensure that the gradiometer balancing is specified if ~isfield(data.grad, 'balance') || ~isfield(data.grad.balance, 'current') data.grad.balance.current = 'none'; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % represent the covariance matrix in a particular manner %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = fixcov(data, desired) if isfield(data, 'cov') && ~isfield(data, 'labelcmb') current = 'full'; elseif isfield(data, 'cov') && isfield(data, 'labelcmb') current = 'sparse'; else error('Could not determine the current representation of the covariance matrix'); end if isequal(current, desired) % nothing to do elseif strcmp(current, 'full') && strcmp(desired, 'sparse') % FIXME should be implemented error('not yet implemented'); elseif strcmp(current, 'sparse') && strcmp(desired, 'full') % FIXME should be implemented error('not yet implemented'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % represent the cross-spectral density matrix in a particular manner %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = fixcsd(data, desired, channelcmb) % FIXCSD converts univariate frequency domain data (fourierspctrm) into a bivariate % representation (crsspctrm), or changes the representation of bivariate frequency % domain data (sparse/full/sparsewithpow, sparsewithpow only works for crsspctrm or % fourierspctrm) % Copyright (C) 2010, Jan-Mathijs Schoffelen, Robert Oostenveld if isfield(data, 'crsspctrm') && isfield(data, 'powspctrm') current = 'sparsewithpow'; elseif isfield(data, 'powspctrm') current = 'sparsewithpow'; elseif isfield(data, 'fourierspctrm') && ~isfield(data, 'labelcmb') current = 'fourier'; elseif ~isfield(data, 'labelcmb') current = 'full'; elseif isfield(data, 'labelcmb') current = 'sparse'; else error('Could not determine the current representation of the %s matrix', param); end % first go from univariate fourier to the required bivariate representation if strcmp(current, 'fourier') && strcmp(desired, 'fourier') % nothing to do elseif strcmp(current, 'fourier') && strcmp(desired, 'sparsewithpow') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpttap', dimtok)), nrpt = size(data.cumtapcnt,1); flag = 0; else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1)); flag = nrpt==1; % needed to truncate the singleton dimension upfront %create auto-spectra nchan = length(data.label); if fastflag % all trials have the same amount of tapers powspctrm = zeros(nrpt,nchan,nfrq,ntim); ntap = data.cumtapcnt(1); for p = 1:ntap powspctrm = powspctrm + abs(data.fourierspctrm(p:ntap:end,:,:,:,:)).^2; end powspctrm = powspctrm./ntap; else % different amount of tapers powspctrm = zeros(nrpt,nchan,nfrq,ntim)+i.*zeros(nrpt,nchan,nfrq,ntim); sumtapcnt = [0;cumsum(data.cumtapcnt(:))]; for p = 1:nrpt indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat = data.fourierspctrm(indx,:,:,:); powspctrm(p,:,:,:) = (sum(tmpdat.*conj(tmpdat),1))./data.cumtapcnt(p); end end %create cross-spectra if ~isempty(channelcmb), ncmb = size(channelcmb,1); cmbindx = zeros(ncmb,2); labelcmb = cell(ncmb,2); for k = 1:ncmb ch1 = find(strcmp(data.label, channelcmb(k,1))); ch2 = find(strcmp(data.label, channelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(k,:) = [ch1 ch2]; labelcmb(k,:) = data.label([ch1 ch2])'; end end crsspctrm = zeros(nrpt,ncmb,nfrq,ntim)+i.*zeros(nrpt,ncmb,nfrq,ntim); if fastflag for p = 1:ntap tmpdat1 = data.fourierspctrm(p:ntap:end,cmbindx(:,1),:,:,:); tmpdat2 = data.fourierspctrm(p:ntap:end,cmbindx(:,2),:,:,:); crsspctrm = crsspctrm + tmpdat1.*conj(tmpdat2); end crsspctrm = crsspctrm./ntap; else for p = 1:nrpt indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:); tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:); crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p); end end data.crsspctrm = crsspctrm; data.labelcmb = labelcmb; end data.powspctrm = powspctrm; data = rmfield(data, 'fourierspctrm'); if ntim>1, data.dimord = 'chan_freq_time'; else data.dimord = 'chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end if flag, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end elseif strcmp(current, 'fourier') && strcmp(desired, 'sparse') if isempty(channelcmb), error('no channel combinations are specified'); end dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpttap', dimtok)), nrpt = size(data.cumtapcnt,1); flag = 0; else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end flag = nrpt==1; % flag needed to squeeze first dimension if singleton ncmb = size(channelcmb,1); cmbindx = zeros(ncmb,2); labelcmb = cell(ncmb,2); for k = 1:ncmb ch1 = find(strcmp(data.label, channelcmb(k,1))); ch2 = find(strcmp(data.label, channelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(k,:) = [ch1 ch2]; labelcmb(k,:) = data.label([ch1 ch2])'; end end sumtapcnt = [0;cumsum(data.cumtapcnt(:))]; fastflag = all(data.cumtapcnt(:)==data.cumtapcnt(1)); if fastflag && nrpt>1 ntap = data.cumtapcnt(1); % compute running sum across tapers siz = [size(data.fourierspctrm) 1]; for p = 1:ntap indx = p:ntap:nrpt*ntap; if p==1. tmpc = zeros(numel(indx), size(cmbindx,1), siz(3), siz(4)) + ... 1i.*zeros(numel(indx), size(cmbindx,1), siz(3), siz(4)); end for k = 1:size(cmbindx,1) tmpc(:,k,:,:) = data.fourierspctrm(indx,cmbindx(k,1),:,:).* ... conj(data.fourierspctrm(indx,cmbindx(k,2),:,:)); end if p==1 crsspctrm = tmpc; else crsspctrm = tmpc + crsspctrm; end end crsspctrm = crsspctrm./ntap; else crsspctrm = zeros(nrpt, ncmb, nfrq, ntim); for p = 1:nrpt indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat1 = data.fourierspctrm(indx,cmbindx(:,1),:,:); tmpdat2 = data.fourierspctrm(indx,cmbindx(:,2),:,:); crsspctrm(p,:,:,:) = (sum(tmpdat1.*conj(tmpdat2),1))./data.cumtapcnt(p); end end data.crsspctrm = crsspctrm; data.labelcmb = labelcmb; data = rmfield(data, 'fourierspctrm'); data = rmfield(data, 'label'); if ntim>1, data.dimord = 'chan_freq_time'; else data.dimord = 'chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end if flag, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end elseif strcmp(current, 'fourier') && strcmp(desired, 'full') % this is how it is currently and the desired functionality of prepare_freq_matrices dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpttap', dimtok)), nrpt = size(data.cumtapcnt, 1); flag = 0; else nrpt = 1; flag = 1; end if ~isempty(strmatch('rpttap',dimtok)), nrpt=size(data.cumtapcnt, 1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=length(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=length(data.time); else ntim = 1; end if any(data.cumtapcnt(1,:) ~= data.cumtapcnt(1,1)), error('this only works when all frequencies have the same number of tapers'); end nchan = length(data.label); crsspctrm = zeros(nrpt,nchan,nchan,nfrq,ntim); sumtapcnt = [0;cumsum(data.cumtapcnt(:,1))]; for k = 1:ntim for m = 1:nfrq for p = 1:nrpt %FIXME speed this up in the case that all trials have equal number of tapers indx = (sumtapcnt(p)+1):sumtapcnt(p+1); tmpdat = transpose(data.fourierspctrm(indx,:,m,k)); crsspctrm(p,:,:,m,k) = (tmpdat*tmpdat')./data.cumtapcnt(p); clear tmpdat; end end end data.crsspctrm = crsspctrm; data = rmfield(data, 'fourierspctrm'); if ntim>1, data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end % remove first singleton dimension if flag || nrpt==1, siz = size(data.crsspctrm); data.crsspctrm = reshape(data.crsspctrm, siz(2:end)); end elseif strcmp(current, 'fourier') && strcmp(desired, 'fullfast'), dimtok = tokenize(data.dimord, '_'); nrpt = size(data.fourierspctrm, 1); nchn = numel(data.label); nfrq = numel(data.freq); if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end data.fourierspctrm = reshape(data.fourierspctrm, [nrpt nchn nfrq*ntim]); data.fourierspctrm(~isfinite(data.fourierspctrm)) = 0; crsspctrm = complex(zeros(nchn,nchn,nfrq*ntim)); for k = 1:nfrq*ntim tmp = transpose(data.fourierspctrm(:,:,k)); n = sum(tmp~=0,2); crsspctrm(:,:,k) = tmp*tmp'./n(1); end data = rmfield(data, 'fourierspctrm'); data.crsspctrm = reshape(crsspctrm, [nchn nchn nfrq ntim]); if isfield(data, 'time'), data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end if isfield(data, 'trialinfo'), data = rmfield(data, 'trialinfo'); end; if isfield(data, 'sampleinfo'), data = rmfield(data, 'sampleinfo'); end; if isfield(data, 'cumsumcnt'), data = rmfield(data, 'cumsumcnt'); end; if isfield(data, 'cumtapcnt'), data = rmfield(data, 'cumtapcnt'); end; end % convert to the requested bivariate representation % from one bivariate representation to another if isequal(current, desired) % nothing to do elseif (strcmp(current, 'full') && strcmp(desired, 'fourier')) || ... (strcmp(current, 'sparse') && strcmp(desired, 'fourier')) || ... (strcmp(current, 'sparsewithpow') && strcmp(desired, 'fourier')) % this is not possible error('converting the cross-spectrum into a Fourier representation is not possible'); elseif strcmp(current, 'full') && strcmp(desired, 'sparsewithpow') error('not yet implemented'); elseif strcmp(current, 'sparse') && strcmp(desired, 'sparsewithpow') % convert back to crsspctrm/powspctrm representation: useful for plotting functions etc indx = labelcmb2indx(data.labelcmb); autoindx = indx(indx(:,1)==indx(:,2), 1); cmbindx = setdiff([1:size(indx,1)]', autoindx); if strcmp(data.dimord(1:3), 'rpt') data.powspctrm = data.crsspctrm(:, autoindx, :, :); data.crsspctrm = data.crsspctrm(:, cmbindx, :, :); else data.powspctrm = data.crsspctrm(autoindx, :, :); data.crsspctrm = data.crsspctrm(cmbindx, :, :); end data.label = data.labelcmb(autoindx,1); data.labelcmb = data.labelcmb(cmbindx, :); if isempty(cmbindx) data = rmfield(data, 'crsspctrm'); data = rmfield(data, 'labelcmb'); end elseif strcmp(current, 'full') && strcmp(desired, 'sparse') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end nchan = length(data.label); ncmb = nchan*nchan; labelcmb = cell(ncmb, 2); cmbindx = zeros(nchan, nchan); k = 1; for j=1:nchan for m=1:nchan labelcmb{k, 1} = data.label{m}; labelcmb{k, 2} = data.label{j}; cmbindx(m,j) = k; k = k+1; end end % reshape all possible fields fn = fieldnames(data); for ii=1:numel(fn) if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim; if nrpt>1, data.(fn{ii}) = reshape(data.(fn{ii}), nrpt, ncmb, nfrq, ntim); else data.(fn{ii}) = reshape(data.(fn{ii}), ncmb, nfrq, ntim); end end end % remove obsolete fields data = rmfield(data, 'label'); try, data = rmfield(data, 'dof'); end % replace updated fields data.labelcmb = labelcmb; if ntim>1, data.dimord = 'chancmb_freq_time'; else data.dimord = 'chancmb_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end elseif strcmp(current, 'sparsewithpow') && strcmp(desired, 'sparse') % this representation for sparse data contains autospectra % as e.g. {'A' 'A'} in labelcmb if isfield(data, 'crsspctrm'), dimtok = tokenize(data.dimord, '_'); catdim = match_str(dimtok, {'chan' 'chancmb'}); data.crsspctrm = cat(catdim, data.powspctrm, data.crsspctrm); data.labelcmb = [data.label(:) data.label(:); data.labelcmb]; data = rmfield(data, 'powspctrm'); else data.crsspctrm = data.powspctrm; data.labelcmb = [data.label(:) data.label(:)]; data = rmfield(data, 'powspctrm'); end data = rmfield(data, 'label'); elseif strcmp(current, 'sparse') && strcmp(desired, 'full') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end if ~isfield(data, 'label') % ensure that the bivariate spectral factorization results can be % processed. FIXME this is experimental and will not work if the user % did something weird before for k = 1:numel(data.labelcmb) tmp = tokenize(data.labelcmb{k}, '['); data.labelcmb{k} = tmp{1}; end data.label = unique(data.labelcmb(:)); end nchan = length(data.label); ncmb = size(data.labelcmb,1); cmbindx = zeros(nchan,nchan); for k = 1:size(data.labelcmb,1) ch1 = find(strcmp(data.label, data.labelcmb(k,1))); ch2 = find(strcmp(data.label, data.labelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(ch1,ch2) = k; end end complete = all(cmbindx(:)~=0); fn = fieldnames(data); for ii=1:numel(fn) if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim; if nrpt==1, data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]); end tmpall = nan(nrpt,nchan,nchan,nfrq,ntim); for j = 1:nrpt for k = 1:ntim for m = 1:nfrq tmpdat = nan(nchan,nchan); indx = find(cmbindx); if ~complete % this realizes the missing combinations to be represented as the % conjugate of the corresponding combination across the diagonal tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]); tmpdat = ctranspose(tmpdat); end tmpdat(indx) = reshape(data.(fn{ii})(j,cmbindx(indx),m,k),[numel(indx) 1]); tmpall(j,:,:,m,k) = tmpdat; end % for m end % for k end % for j % replace the data in the old representation with the new representation if nrpt>1, data.(fn{ii}) = tmpall; else data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]); end end % if numel end % for ii % remove obsolete fields try, data = rmfield(data, 'powspctrm'); end try, data = rmfield(data, 'labelcmb'); end try, data = rmfield(data, 'dof'); end if ntim>1, data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end if nrpt>1, data.dimord = ['rpt_',data.dimord]; end elseif strcmp(current, 'sparse') && strcmp(desired, 'fullfast') dimtok = tokenize(data.dimord, '_'); if ~isempty(strmatch('rpt', dimtok)), nrpt=size(data.cumtapcnt,1); else nrpt = 1; end if ~isempty(strmatch('freq', dimtok)), nfrq=numel(data.freq); else nfrq = 1; end if ~isempty(strmatch('time', dimtok)), ntim=numel(data.time); else ntim = 1; end if ~isfield(data, 'label') data.label = unique(data.labelcmb(:)); end nchan = length(data.label); ncmb = size(data.labelcmb,1); cmbindx = zeros(nchan,nchan); for k = 1:size(data.labelcmb,1) ch1 = find(strcmp(data.label, data.labelcmb(k,1))); ch2 = find(strcmp(data.label, data.labelcmb(k,2))); if ~isempty(ch1) && ~isempty(ch2), cmbindx(ch1,ch2) = k; end end complete = all(cmbindx(:)~=0); fn = fieldnames(data); for ii=1:numel(fn) if numel(data.(fn{ii})) == nrpt*ncmb*nfrq*ntim; if nrpt==1, data.(fn{ii}) = reshape(data.(fn{ii}), [nrpt ncmb nfrq ntim]); end tmpall = nan(nchan,nchan,nfrq,ntim); for k = 1:ntim for m = 1:nfrq tmpdat = nan(nchan,nchan); indx = find(cmbindx); if ~complete % this realizes the missing combinations to be represented as the % conjugate of the corresponding combination across the diagonal tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]); tmpdat = ctranspose(tmpdat); end tmpdat(indx) = reshape(nanmean(data.(fn{ii})(:,cmbindx(indx),m,k)),[numel(indx) 1]); tmpall(:,:,m,k) = tmpdat; end % for m end % for k % replace the data in the old representation with the new representation if nrpt>1, data.(fn{ii}) = tmpall; else data.(fn{ii}) = reshape(tmpall, [nchan nchan nfrq ntim]); end end % if numel end % for ii % remove obsolete fields try, data = rmfield(data, 'powspctrm'); end try, data = rmfield(data, 'labelcmb'); end try, data = rmfield(data, 'dof'); end if ntim>1, data.dimord = 'chan_chan_freq_time'; else data.dimord = 'chan_chan_freq'; end elseif strcmp(current, 'sparsewithpow') && strcmp(desired, 'full') % this is how is currently done in prepare_freq_matrices data = ft_checkdata(data, 'cmbrepresentation', 'sparse'); data = ft_checkdata(data, 'cmbrepresentation', 'full'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert to new source representation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [output] = fixsource(input, varargin) % FIXSOURCE converts old style source structures into new style source structures and the % other way around % % Use as: % fixsource(input, type) % where input is a source structure, % % Typically, old style source structures contain % avg.XXX or trial.XXX fields % % The new style source structure contains: % source.pos % source.dim (optional, if the list of positions describes a 3D volume % source.XXX the old style subfields in avg/trial % source.XXXdimord string how to interpret the respective XXX field: % e.g. source.leadfield = cell(1,Npos), source.leadfielddimord = '{pos}_chan_ori' % source.mom = cell(1,Npos), source.momdimord = '{pos}_ori_rpttap' type = ft_getopt(varargin, 'type'); haspow = ft_getopt(varargin, 'haspow'); if isempty(type), type = 'old'; end if isempty(haspow), haspow = 'no'; end fnames = fieldnames(input); tmp = cell2mat(strfind(fnames, 'dimord')); %get dimord like fields if any(tmp>1), current = 'new'; elseif any(tmp==1), %don't know what to do yet data is JM's own invention current = 'old'; else current = 'old'; end if strcmp(current, type), %do nothing output = input; %return elseif strcmp(current, 'old') && strcmp(type, 'new'), %go from old to new if isfield(input, 'avg'), stuff = getfield(input, 'avg'); output = rmfield(input, 'avg'); elseif isfield(input, 'trial'), stuff = getfield(input, 'trial'); output = rmfield(input, 'trial'); else %this could occur later in the pipeline, e.g. when doing group statistics using individual subject %descriptive statistics error('the input does not contain an avg or trial field'); end %------------------------------------------------- %remove and rename the specified fields if present removefields = {'xgrid';'ygrid';'zgrid';'method'}; renamefields = {'frequency' 'freq'; 'csdlabel' 'orilabel'}; fnames = fieldnames(output); for k = 1:numel(fnames) ix = strmatch(fnames{k}, removefields); if ~isempty(ix), output = rmfield(output, fnames{k}); end ix = strmatch(fnames{k}, renamefields(:,1), 'exact'); if ~isempty(ix), output = setfield(output, renamefields{ix,2}, ... getfield(output, renamefields{ix,1})); output = rmfield(output, fnames{k}); end end %---------------------------------------------------------------------- %put the stuff originally in avg or trial one level up in the structure fnames = fieldnames(stuff(1)); npos = size(input.pos,1); nrpt = numel(stuff); for k = 1:numel(fnames) if nrpt>1, %multiple trials %(or subjects FIXME not yet implemented, nor tested) tmp = getfield(stuff(1), fnames{k}); siz = size(tmp); if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom') %pcc based mom is orixrpttap %tranpose to keep manageable for kk = 1:numel(input.inside) indx = input.inside(kk); tmp{indx} = permute(tmp{indx}, [2 1 3]); end nrpttap = sum(input.cumtapcnt); sizvox = [size(tmp{input.inside(1)}) 1]; sizvox = [nrpttap sizvox(2:end)]; elseif strcmp(fnames{k}, 'mom'), %this is then probably not a frequency based mom nrpttap = numel(stuff); sizvox = [size(tmp{input.inside(1)}) 1]; sizvox = [nrpttap sizvox]; elseif iscell(tmp) nrpttap = numel(stuff); sizvox = [size(tmp{input.inside(1)}) 1]; sizvox = [nrpttap sizvox]; end if siz(1) ~= npos && siz(2) ==npos, tmp = transpose(tmp); end if iscell(tmp) %allocate memory for cell-array tmpall = cell(npos,1); for n = 1:numel(input.inside) tmpall{input.inside(n)} = zeros(sizvox); end else %allocate memory for matrix tmpall = zeros([npos nrpt siz(2:end)]); end cnt = 0; for m = 1:nrpt tmp = getfield(stuff(m), fnames{k}); siz = size(tmp); if siz(1) ~= npos && siz(2) ==npos, tmp = transpose(tmp); end if ~iscell(tmp), tmpall(:,m,:,:,:) = tmp; else for n = 1:numel(input.inside) indx = input.inside(n); tmpdat = tmp{indx}; if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom'), if n==1, siz1 = size(tmpdat,2); end else if n==1, siz1 = 1; end end tmpall{indx}(cnt+[1:siz1],:,:,:,:) = tmpdat; if n==numel(input.inside), cnt = cnt + siz1; end end end end output = setfield(output, fnames{k}, tmpall); newdimord = createdimord(output, fnames{k}, 1); if ~isempty(newdimord) output = setfield(output, [fnames{k},'dimord'], newdimord); end else tmp = getfield(stuff, fnames{k}); siz = size(tmp); if isfield(input, 'cumtapcnt') && strcmp(fnames{k}, 'mom') %pcc based mom is orixrpttap %tranpose to keep manageable for kk = 1:numel(input.inside) indx = input.inside(kk); tmp{indx} = permute(tmp{indx}, [2 1 3]); end end if siz(1) ~= npos && siz(2) ==npos, tmp = transpose(tmp); end output = setfield(output, fnames{k}, tmp); newdimord = createdimord(output, fnames{k}); if ~isempty(newdimord) output = setfield(output, [fnames{k},'dimord'], newdimord); end end end if isfield(output, 'csdlabel') output = setfield(output, 'orilabel', getfield(output, 'csdlabel')); output = rmfield(output, 'csdlabel'); end if isfield(output, 'leadfield') % add dimord to leadfield as well. since the leadfield is not in % the original .avg or .trial field it has not yet been taken care of output.leadfielddimord = createdimord(output, 'leadfield'); end if isfield(output, 'ori') % convert cell-array ori into matrix ori = nan(3,npos); try, ori(:,output.inside) = cat(2, output.ori{output.inside}); catch %when oris are in wrong orientation (row rather than column) for k = 1:numel(output.inside) ori(:,output.inside(k)) = output.ori{output.inside(k)}'; end end output.ori = ori; end current = 'new'; elseif strcmp(current, 'new') && strcmp(type, 'old') %go from new to old error('not implemented yet'); end if strcmp(current, 'new') && strcmp(haspow, 'yes'), %---------------------------------------------- %convert mom into pow if requested and possible convert = 0; if isfield(output, 'mom') && size(output.mom{output.inside(1)},2)==1, convert = 1; else warning('conversion from mom to pow is not possible, either because there is no mom in the data, or because the dimension of mom>1. in that case call ft_sourcedescriptives first with cfg.projectmom'); end if isfield(output, 'cumtapcnt') convert = 1 & convert; else warning('conversion from mom to pow will not be done, because cumtapcnt is missing'); end if convert, npos = size(output.pos,1); nrpt = size(output.cumtapcnt,1); tmpmom = cat(2,output.mom{output.inside}); tmppow = zeros(npos, nrpt); tapcnt = [0;cumsum(output.cumtapcnt(:))]; for k = 1:nrpt ntap = tapcnt(k+1)-tapcnt(k); tmppow(output.inside,k) = sum(abs(tmpmom((tapcnt(k)+1):tapcnt(k+1),:)).^2,1)./ntap; end output.pow = tmppow; output.powdimord = ['pos_rpt_freq']; end elseif strcmp(current, 'old') && strcmp(haspow, 'yes') warning('construction of single trial power estimates is not implemented here using old style source representation'); end %-------------------------------------------------------- function [dimord] = createdimord(output, fname, rptflag); if nargin==2, rptflag = 0; end tmp = getfield(output, fname); dimord = ''; dimnum = 1; hasori = isfield(output, 'ori'); %if not, this is probably singleton and not relevant at the end if iscell(tmp) && (size(output.pos,1)==size(tmp,dimnum) || size(output.pos,1)==size(tmp,2)) dimord = [dimord,'{pos}']; dimnum = dimnum + 1; elseif ~iscell(tmp) && size(output.pos,1)==size(tmp,dimnum) dimord = [dimord,'pos']; dimnum = dimnum + 1; end switch fname case 'cov' if hasori, dimord = [dimord,'_ori_ori']; end; case 'csd' if hasori, dimord = [dimord,'_ori_ori']; end; case 'csdlabel' dimord = dimord; case 'filter' dimord = [dimord,'_ori_chan']; case 'leadfield' %if hasori, dimord = [dimord,'_chan_ori']; %else % dimord = [dimord,'_chan']; %end case 'mom' if isfield(output, 'cumtapcnt') && sum(output.cumtapcnt)==size(tmp{output.inside(1)},1) if hasori, dimord = [dimord,'_rpttap_ori']; else dimord = [dimord,'_rpttap']; end elseif isfield(output, 'time') if rptflag, dimord = [dimord,'_rpt']; dimnum = dimnum + 1; end if numel(output.time)==size(tmp{output.inside(1)},dimnum) dimord = [dimord,'_ori_time']; end end if isfield(output, 'freq') && numel(output.freq)>1, dimord = [dimord,'_freq']; end case 'nai' if isfield(output, 'freq') && numel(output.freq)==size(tmp,dimnum) dimord = [dimord,'_freq']; end case 'noise' if isfield(output, 'freq') && numel(output.freq)==size(tmp,dimnum) dimord = [dimord,'_freq']; end case 'noisecsd' if hasori, dimord = [dimord,'_ori_ori']; end case 'ori' dimord = ''; case 'pow' if isfield(output, 'cumtapcnt') && size(output.cumtapcnt,1)==size(tmp,dimnum) dimord = [dimord,'_rpt']; dimnum = dimnum + 1; end if isfield(output, 'freq') && numel(output.freq)>1 && numel(output.freq)==size(tmp,dimnum) dimord = [dimord,'_freq']; dimnum = dimnum+1; end if isfield(output, 'time') && numel(output.time)>1 && numel(output.time)==size(tmp,dimnum) dimord = [dimord,'_time']; dimnum = dimnum+1; end otherwise warning('skipping unknown fieldname %s', fname); %error(sprintf('unknown fieldname %s', fname)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = comp2raw(data) % remove the fields that are specific to the comp representation fn = fieldnames(data); fn = intersect(fn, {'topo' 'topolabel' 'unmixing'}); data = rmfield(data, fn); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = volume2source(data) if isfield(data, 'dimord') % it is a modern source description else % it is an old-fashioned source description xgrid = 1:data.dim(1); ygrid = 1:data.dim(2); zgrid = 1:data.dim(3); [x y z] = ndgrid(xgrid, ygrid, zgrid); data.pos = warp_apply(data.transform, [x(:) y(:) z(:)]); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = source2volume(data) if isfield(data, 'dimord') % it is a modern source description %this part depends on the assumption that the list of positions is describing a full 3D volume in %an ordered way which allows for the extraction of a transformation matrix %i.e. slice by slice try, if isfield(data, 'dim'), data.dim = pos2dim(data.pos, data.dim); else data.dim = pos2dim(data); end catch end end if isfield(data, 'dim') && length(data.dim)>=3, % it is an old-fashioned source description, or the source describes a regular 3D volume in pos xgrid = 1:data.dim(1); ygrid = 1:data.dim(2); zgrid = 1:data.dim(3); [x y z] = ndgrid(xgrid, ygrid, zgrid); ind = [x(:) y(:) z(:)]; % these are the positions expressed in voxel indices along each of the three axes pos = data.pos; % these are the positions expressed in head coordinates % represent the positions in a manner that is compatible with the homogeneous matrix multiplication, % i.e. pos = H * ind ind = ind'; ind(4,:) = 1; pos = pos'; pos(4,:) = 1; % recompute the homogeneous transformation matrix data.transform = pos / ind; end % remove the unwanted fields if isfield(data, 'pos'), data = rmfield(data, 'pos'); end if isfield(data, 'xgrid'), data = rmfield(data, 'xgrid'); end if isfield(data, 'ygrid'), data = rmfield(data, 'ygrid'); end if isfield(data, 'zgrid'), data = rmfield(data, 'zgrid'); end % make inside a volume data = fixinside(data, 'logical'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function data = freq2raw(freq) if strcmp(freq.dimord, 'rpt_chan_freq_time') dat = freq.powspctrm; elseif strcmp(freq.dimord, 'rpttap_chan_freq_time') warning('converting fourier representation into raw data format. this is experimental code'); dat = freq.fourierspctrm; else error('this only works for dimord=''rpt_chan_freq_time'''); end nrpt = size(dat,1); nchan = size(dat,2); nfreq = size(dat,3); ntime = size(dat,4); data = []; % create the channel labels like "MLP11@12Hz"" k = 0; for i=1:nfreq for j=1:nchan k = k+1; data.label{k} = sprintf('%s@%dHz', freq.label{j}, freq.freq(i)); end end % reshape and copy the data as if it were timecourses only for i=1:nrpt data.time{i} = freq.time; data.trial{i} = reshape(dat(i,:,:,:), nchan*nfreq, ntime); if any(isnan(data.trial{i}(1,:))), tmp = data.trial{i}(1,:); begsmp = find(isfinite(tmp),1, 'first'); endsmp = find(isfinite(tmp),1, 'last' ); data.trial{i} = data.trial{i}(:, begsmp:endsmp); data.time{i} = data.time{i}(begsmp:endsmp); end end nsmp = cellfun('size',data.time,2); seln = find(nsmp>1,1, 'first'); if isfield(freq, 'trialinfo'), data.trialinfo = freq.trialinfo; end; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = raw2timelock(data) nsmp = cellfun('size',data.time,2); data = ft_checkdata(data, 'hassampleinfo', 'yes'); ntrial = numel(data.trial); nchan = numel(data.label); if ntrial==1 data.time = data.time{1}; data.avg = data.trial{1}; data = rmfield(data, 'trial'); data.dimord = 'chan_time'; else begtime = cellfun(@min,data.time); endtime = cellfun(@max,data.time); % this part is just about the number of samples, not about the time-axis for i = 1:ntrial time = data.time{i}; mint = min([ 0, begtime(i)]); maxt = max([-max(abs(2*endtime)) * eps, endtime(i)]); % extrapolate so that we get near 0 if (mint==0) tmptime = -1*(fliplr(-maxt:mean(diff(time)):-mint)); else tmptime = mint:mean(diff(time)):maxt; end ix(i) = sum(tmptime<0); % number of samples pre-zero iy(i) = sum(tmptime>=0); % number of samples post-zero % account for strictly positive or negative time-axes by removing those % elements that are near 0 but should not be in the time-axis if ix(i)==0 ix(i) = 1-nearest(tmptime, begtime(i)); end if iy(i)==0 iy(i) = nearest(tmptime, endtime(i))-length(tmptime); end end [mx,ix2] = max(ix); [my,iy2] = max(iy); nsmp = mx+my; % create temporary time-axis time = linspace(min(begtime), max(endtime), nsmp); % remove any time-points before 0 iff not needed - see bug 1477 time(nearest(time, max(endtime))+1:end) = []; % concatenate all trials tmptrial = nan(ntrial, nchan, length(time)); for i=1:ntrial begsmp(i) = nearest(time, data.time{i}(1)); endsmp(i) = nearest(time, data.time{i}(end)); tmptrial(i,:,begsmp(i):endsmp(i)) = data.trial{i}; end % update the sampleinfo begpad = begsmp - min(begsmp); endpad = max(endsmp) - endsmp; if isfield(data, 'sampleinfo') data.sampleinfo = data.sampleinfo + [-begpad(:) endpad(:)]; end % construct the output timelocked data % data.avg = reshape(nanmean(tmptrial, 1), nchan, length(tmptime)); % data.var = reshape(nanvar (tmptrial, [], 1), nchan, length(tmptime)) % data.dof = reshape(sum(~isnan(tmptrial), 1), nchan, length(tmptime)); data.trial = tmptrial; data.time = time; data.dimord = 'rpt_chan_time'; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = timelock2raw(data) try nsmp = cellfun('size',data.time,2); catch nsmp = size(data.time,2); end switch data.dimord case 'chan_time' data.trial{1} = data.avg; data.time = {data.time}; data = rmfield(data, 'avg'); seln = find(nsmp>1,1, 'first'); case 'rpt_chan_time' tmptrial = {}; tmptime = {}; ntrial = size(data.trial,1); nchan = size(data.trial,2); ntime = size(data.trial,3); for i=1:ntrial tmptrial{i} = reshape(data.trial(i,:,:), [nchan, ntime]); tmptime{i} = data.time; end data = rmfield(data, 'trial'); data.trial = tmptrial; data.time = tmptime; seln = find(nsmp>1,1, 'first'); case 'subj_chan_time' tmptrial = {}; tmptime = {}; ntrial = size(data.individual,1); nchan = size(data.individual,2); ntime = size(data.individual,3); for i=1:ntrial tmptrial{i} = reshape(data.individual(i,:,:), [nchan, ntime]); tmptime{i} = data.time; end data = rmfield(data, 'individual'); data.trial = tmptrial; data.time = tmptime; seln = find(nsmp>1,1, 'first'); otherwise error('unsupported dimord'); end % remove the unwanted fields if isfield(data, 'avg'), data = rmfield(data, 'avg'); end if isfield(data, 'var'), data = rmfield(data, 'var'); end if isfield(data, 'cov'), data = rmfield(data, 'cov'); end if isfield(data, 'dimord'), data = rmfield(data, 'dimord'); end if isfield(data, 'numsamples'), data = rmfield(data, 'numsamples'); end if isfield(data, 'dof'), data = rmfield(data, 'dof'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = chan2freq(data) data.dimord = [data.dimord '_freq']; data.freq = 0; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = chan2timelock(data) data.dimord = [data.dimord '_time']; data.time = 0; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [spike] = raw2spike(data) fprintf('converting raw data into spike data\n'); nTrials = length(data.trial); [spikelabel] = detectspikechan(data); spikesel = match_str(data.label, spikelabel); nUnits = length(spikesel); if nUnits==0 error('cannot convert raw data to spike format since the raw data structure does not contain spike channels'); end trialTimes = zeros(nTrials,2); for iUnit = 1:nUnits unitIndx = spikesel(iUnit); spikeTimes = []; % we dont know how large it will be, so use concatenation inside loop trialInds = []; for iTrial = 1:nTrials % read in the spike times [spikeTimesTrial] = getspiketimes(data, iTrial, unitIndx); nSpikes = length(spikeTimesTrial); spikeTimes = [spikeTimes; spikeTimesTrial(:)]; trialInds = [trialInds; ones(nSpikes,1)*iTrial]; % get the begs and ends of trials hasNum = find(~isnan(data.time{iTrial})); if iUnit==1, trialTimes(iTrial,:) = data.time{iTrial}([hasNum(1) hasNum(end)]); end end spike.label{iUnit} = data.label{unitIndx}; spike.waveform{iUnit} = []; spike.time{iUnit} = spikeTimes(:)'; spike.trial{iUnit} = trialInds(:)'; if iUnit==1, spike.trialtime = trialTimes; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % sub function for detection channels %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [spikelabel, eeglabel] = detectspikechan(data) maxRate = 2000; % default on what we still consider a neuronal signal: this firing rate should never be exceeded % autodetect the spike channels ntrial = length(data.trial); nchans = length(data.label); spikechan = zeros(nchans,1); for i=1:ntrial for j=1:nchans hasAllInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:) == round(data.trial{i}(j,:))); hasAllPosInts = all(isnan(data.trial{i}(j,:)) | data.trial{i}(j,:)>=0); T = nansum(diff(data.time{i})); % total time fr = nansum(data.trial{i}(j,:)) ./ T; spikechan(j) = spikechan(j) + double(hasAllInts & hasAllPosInts & fr<=maxRate); end end spikechan = (spikechan==ntrial); spikelabel = data.label(spikechan); eeglabel = data.label(~spikechan); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [spikeTimes] = getspiketimes(data, trial, unit) spikeIndx = logical(data.trial{trial}(unit,:)); spikeCount = data.trial{trial}(unit,spikeIndx); spikeTimes = data.time{trial}(spikeIndx); if isempty(spikeTimes), return; end multiSpikes = find(spikeCount>1); % get the additional samples and spike times, we need only loop through the bins [addSamples, addTimes] = deal([]); for iBin = multiSpikes(:)' % looping over row vector addTimes = [addTimes ones(1,spikeCount(iBin))*spikeTimes(iBin)]; addSamples = [addSamples ones(1,spikeCount(iBin))*spikeIndx(iBin)]; end % before adding these times, first remove the old ones spikeTimes(multiSpikes) = []; spikeTimes = sort([spikeTimes(:); addTimes(:)]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % convert between datatypes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [data] = spike2raw(spike, fsample) if nargin<2 || isempty(fsample) timeDiff = abs(diff(sort([spike.time{:}]))); fsample = 1/min(timeDiff(timeDiff>0)); warning('Desired sampling rate for spike data not specified, automatically resampled to %f', fsample); end % get some sizes nUnits = length(spike.label); nTrials = size(spike.trialtime,1); % preallocate data.trial(1:nTrials) = {[]}; data.time(1:nTrials) = {[]}; for iTrial = 1:nTrials % make bins: note that the spike.time is already within spike.trialtime x = [spike.trialtime(iTrial,1):(1/fsample):spike.trialtime(iTrial,2)]; timeBins = [x x(end)+1/fsample] - (0.5/fsample); time = (spike.trialtime(iTrial,1):(1/fsample):spike.trialtime(iTrial,2)); % convert to continuous trialData = zeros(nUnits,length(time)); for iUnit = 1:nUnits % get the timestamps and only select those timestamps that are in the trial ts = spike.time{iUnit}; hasTrial = spike.trial{iUnit}==iTrial; ts = ts(hasTrial); N = histc(ts,timeBins); if isempty(N) N = zeros(1,length(timeBins)-1); else N(end) = []; end % store it in a matrix trialData(iUnit,:) = N; end data.trial{iTrial} = trialData; data.time{iTrial} = time; end % create the associated labels and other aspects of data such as the header data.label = spike.label; data.fsample = fsample; if isfield(spike,'hdr'), data.hdr = spike.hdr; end if isfield(spike,'cfg'), data.cfg = spike.cfg; end
github
philippboehmsturm/antx-master
nanvar.m
.m
antx-master/xspm8/external/fieldtrip/fileio/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
read_yokogawa_data.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_yokogawa_data.m
11,038
utf_8
aa2c8a06c417ada7e9af353f2307443e
function [dat] = read_yokogawa_data(filename, hdr, begsample, endsample, chanindx) % READ_YOKAGAWA_DATA reads continuous, epoched or averaged MEG data % that has been generated by the Yokogawa MEG system and software % and allows that data to be used in combination with FieldTrip. % % Use as % [dat] = read_yokogawa_data(filename, hdr, begsample, endsample, chanindx) % % This is a wrapper function around the functions % GetMeg160ContinuousRawDataM % GetMeg160EvokedAverageDataM % GetMeg160EvokedRawDataM % % See also READ_YOKOGAWA_HEADER, READ_YOKOGAWA_EVENT % Copyright (C) 2005, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_yokogawa_data.m 7123 2012-12-06 21:21:38Z roboos $ if ~ft_hastoolbox('yokogawa') error('cannot determine whether Yokogawa toolbox is present'); end % hdr = read_yokogawa_header(filename); hdr = hdr.orig; % use the original Yokogawa header, not the FieldTrip header % default is to select all channels if nargin<5 chanindx = 1:hdr.channel_count; end handles = definehandles; fid = fopen(filename, 'rb', 'ieee-le'); switch hdr.acq_type case handles.AcqTypeEvokedAve % Data is returned by double. start_sample = begsample - 1; % samples start at 0 sample_length = endsample - begsample + 1; epoch_count = 1; start_epoch = 0; dat = double(GetMeg160EvokedAverageDataM( fid, start_sample, sample_length )); % the first extra sample is the channel number channum = dat(:,1); dat = dat(:,2:end); case handles.AcqTypeContinuousRaw % Data is returned by int16. start_sample = begsample - 1; % samples start at 0 sample_length = endsample - begsample + 1; epoch_count = 1; start_epoch = 0; dat = double(GetMeg160ContinuousRawDataM( fid, start_sample, sample_length )); % the first extra sample is the channel number channum = dat(:,1); dat = dat(:,2:end); case handles.AcqTypeEvokedRaw % Data is returned by int16. begtrial = ceil(begsample/hdr.sample_count); endtrial = ceil(endsample/hdr.sample_count); if begtrial<1 error('cannot read before the begin of the file'); elseif endtrial>hdr.actual_epoch_count error('cannot read beyond the end of the file'); end epoch_count = endtrial-begtrial+1; start_epoch = begtrial-1; % read all the neccessary trials that contain the desired samples dat = double(GetMeg160EvokedRawDataM( fid, start_epoch, epoch_count )); % the first extra sample is the channel number channum = dat(:,1); dat = dat(:,2:end); if size(dat,2)~=epoch_count*hdr.sample_count error('could not read all epochs'); end rawbegsample = begsample - (begtrial-1)*hdr.sample_count; rawendsample = endsample - (begtrial-1)*hdr.sample_count; sample_length = rawendsample - rawbegsample + 1; % select the desired samples from the complete trials dat = dat(:,rawbegsample:rawendsample); otherwise error('unknown data type'); end fclose(fid); if size(dat,1)~=hdr.channel_count error('could not read all channels'); elseif size(dat,2)~=(endsample-begsample+1) error('could not read all samples'); end % Count of AxialGradioMeter ch_type = hdr.channel_info(:,2); index = find(ch_type==[handles.AxialGradioMeter]); axialgradiometer_index_tmp = index; axialgradiometer_ch_count = length(index); % Count of PlannerGradioMeter ch_type = hdr.channel_info(:,2); index = find(ch_type==[handles.PlannerGradioMeter]); plannergradiometer_index_tmp = index; plannergradiometer_ch_count = length(index); % Count of EegChannel ch_type = hdr.channel_info(:,2); index = find(ch_type==[handles.EegChannel]); eegchannel_index_tmp = index; eegchannel_ch_count = length(index); % Count of NullChannel ch_type = hdr.channel_info(:,2); index = find(ch_type==[handles.NullChannel]); nullchannel_index_tmp = index; nullchannel_ch_count = length(index); %%% Pulling out AxialGradioMeter and value conversion to physical units. if ~isempty(axialgradiometer_index_tmp) % Acquisition of channel information axialgradiometer_index = axialgradiometer_index_tmp; ch_info = hdr.channel_info; axialgradiometer_ch_info = ch_info(axialgradiometer_index, :); % Value conversion % B = ( ADValue * VoltRange / ADRange - Offset ) * Sensitivity / FLLGain calib = hdr.calib_info; amp_gain = hdr.amp_gain(1); tmp_ch_no = channum(axialgradiometer_index, 1); tmp_data = dat(axialgradiometer_index, 1:sample_length); tmp_offset = calib(axialgradiometer_index, 3) * ones(1,sample_length); ad_range = 5/2^(hdr.ad_bit-1); tmp_data = ( tmp_data * ad_range - tmp_offset ); clear tmp_offset; tmp_gain = calib(axialgradiometer_index, 2) * ones(1,sample_length); tmp_data = tmp_data .* tmp_gain / amp_gain; dat(axialgradiometer_index, 1:sample_length) = tmp_data; clear tmp_gain; % Deletion of Inf row index = find(axialgradiometer_ch_info(1,:) == Inf); axialgradiometer_ch_info(:,index) = []; % Deletion of channel_type row axialgradiometer_ch_info(:,2) = []; % Outputs to the global variable handles.sqd.axialgradiometer_ch_info = axialgradiometer_ch_info; handles.sqd.axialgradiometer_ch_no = tmp_ch_no; handles.sqd.axialgradiometer_data = [ tmp_ch_no tmp_data]; clear tmp_data; end %%% Pulling out PlannerGradioMeter and value conversion to physical units. if ~isempty(plannergradiometer_index_tmp) % Acquisition of channel information plannergradiometer_index = plannergradiometer_index_tmp; ch_info = hdr.channel_info; plannergradiometer_ch_info = ch_info(plannergradiometer_index, :); % Value conversion % B = ( ADValue * VoltRange / ADRange - Offset ) * Sensitivity / FLLGain calib = hdr.calib_info; amp_gain = hdr.amp_gain(1); tmp_ch_no = channum(plannergradiometer_index, 1); tmp_data = dat(plannergradiometer_index, 1:sample_length); tmp_offset = calib(plannergradiometer_index, 3) * ones(1,sample_length); ad_range = 5/2^(hdr.ad_bit-1); tmp_data = ( tmp_data * ad_range - tmp_offset ); clear tmp_offset; tmp_gain = calib(plannergradiometer_index, 2) * ones(1,sample_length); tmp_data = tmp_data .* tmp_gain / amp_gain; dat(plannergradiometer_index, 1:sample_length) = tmp_data; clear tmp_gain; % Deletion of Inf row index = find(plannergradiometer_ch_info(1,:) == Inf); plannergradiometer_ch_info(:,index) = []; % Deletion of channel_type row plannergradiometer_ch_info(:,2) = []; % Outputs to the global variable handles.sqd.plannergradiometer_ch_info = plannergradiometer_ch_info; handles.sqd.plannergradiometer_ch_no = tmp_ch_no; handles.sqd.plannergradiometer_data = [ tmp_ch_no tmp_data]; clear tmp_data; end %%% Pulling out EegChannel Channel and value conversion to Volt units. if ~isempty(eegchannel_index_tmp) % Acquisition of channel information eegchannel_index = eegchannel_index_tmp; % Value conversion % B = ADValue * VoltRange / ADRange tmp_ch_no = channum(eegchannel_index, 1); tmp_data = dat(eegchannel_index, 1:sample_length); ad_range = 5/2^(hdr.ad_bit-1); tmp_data = tmp_data * ad_range; dat(eegchannel_index, 1:sample_length) = tmp_data; % Outputs to the global variable handles.sqd.eegchannel_ch_no = tmp_ch_no; handles.sqd.eegchannel_data = [ tmp_ch_no tmp_data]; clear tmp_data; end %%% Pulling out Null Channel and value conversion to Volt units. if ~isempty(nullchannel_index_tmp) % Acquisition of channel information nullchannel_index = nullchannel_index_tmp; % Value conversion % B = ADValue * VoltRange / ADRange tmp_ch_no = channum(nullchannel_index, 1); tmp_data = dat(nullchannel_index, 1:sample_length); ad_range = 5/2^(hdr.ad_bit-1); tmp_data = tmp_data * ad_range; dat(nullchannel_index, 1:sample_length) = tmp_data; % Outputs to the global variable handles.sqd.nullchannel_ch_no = tmp_ch_no; handles.sqd.nullchannel_data = [ tmp_ch_no tmp_data]; clear tmp_data; end % select only the desired channels dat = dat(chanindx,:); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.eegchannel_ch_no = []; handles.sqd.eegchannel_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
philippboehmsturm/antx-master
read_biff.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_biff.m
5,857
utf_8
d71281c0e6be7868430597d71c166b5d
function [this] = read_biff(filename, opt) % READ_BIFF reads data and header information from a BIFF file % % This is a attemt for a reference implementation to read the BIFF % file format as defined by the Clinical Neurophysiology department of % the University Medical Centre, Nijmegen. % % read all data and information % [data] = read_biff(filename) % or read a selected top-level chunk % [chunk] = read_biff(filename, chunkID) % % known top-level chunk id's are % data : measured data (matrix) % dati : information on data (struct) % expi : information on experiment (struct) % pati : information on patient (struct) % evnt : event markers (struct) % Copyright (C) 2000, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_biff.m 7123 2012-12-06 21:21:38Z roboos $ define_biff; this = []; fid = fopen(filename, 'r'); fseek(fid,0,'eof'); eof = ftell(fid); fseek(fid,0,'bof'); [id, siz] = chunk_header(fid); switch id case 'SEMG' child = subtree(BIFF, id); this = read_biff_chunk(fid, id, siz, child); case 'LIST' fprintf('skipping unimplemented chunk id="%s" size=%4d\n', id, siz); case 'CAT ' fprintf('skipping unimplemented chunk id="%s" size=%4d\n', id, siz); otherwise fprintf('skipping unrecognized chunk id="%s" size=%4d\n', id, siz); fseek(fid, siz, 'cof'); end % switch fclose(fid); % close file %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION read_biff_chunk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function this = read_biff_chunk(fid, id, siz, chunk); % start with empty structure this = []; if strcmp(id, 'null') % this is an empty chunk fprintf('skipping empty chunk id="%s" size=%4d\n', id, siz); assert(~feof(fid)); fseek(fid, siz, 'cof'); elseif isempty(chunk) % this is an unrecognized chunk fprintf('skipping unrecognized chunk id="%s" size=%4d\n', id, siz); assert(~feof(fid)); fseek(fid, siz, 'cof'); else eoc = ftell(fid) + siz; name = char(chunk.desc(2)); type = char(chunk.desc(3)); fprintf('reading chunk id= "%s" size=%4d name="%s"\n', id, siz, name); switch type case 'group' while ~feof(fid) & ftell(fid)<eoc % read all subchunks [id, siz] = chunk_header(fid); child = subtree(chunk, id); if ~isempty(child) % read data and add subchunk data to chunk structure name = char(child.desc(2)); val = read_biff_chunk(fid, id, siz, child); this = setfield(this, name, val); else fprintf('skipping unrecognized chunk id="%s" size=%4d\n', id, siz); fseek(fid, siz, 'cof'); end end % while case 'string' this = char(fread(fid, siz, 'uchar')'); case {'char', 'uchar', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'float32', 'float64'} this = fread(fid, 1, type); case {'char', 'uchar', 'int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'float32', 'float64'} this = fread(fid, 1, type); case {'int8vec', 'int16vec', 'int32vec', 'int64vec', 'uint8vec', 'uint16vec', 'uint32vec', 'float32vec', 'float64vec'} ncol = fread(fid, 1, 'uint32'); this = fread(fid, ncol, type(1:(length(type)-3))); case {'int8mat', 'int16mat', 'int32mat', 'int64mat', 'uint8mat', 'uint16mat', 'uint32mat', 'float32mat', 'float64mat'} nrow = fread(fid, 1, 'uint32'); ncol = fread(fid, 1, 'uint32'); this = fread(fid, [nrow, ncol], type(1:(length(type)-3))); otherwise fseek(fid, siz, 'cof'); % skip this chunk sprintf('unimplemented data type "%s" in chunk "%s"', type, id); % warning(ans); end % switch chunk type end % else %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION subtree %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function child = subtree(parent, id); blank = findstr(id, ' '); while ~isempty(blank) id(blank) = '_'; blank = findstr(id, ' '); end elem = fieldnames(parent); % list of all subitems num = find(strcmp(elem, id)); % number in parent tree if size(num) == [1,1] child = getfield(parent, char(elem(num))); % child subtree else child = []; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION chunk_header %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [id, siz] = chunk_header(fid); id = char(fread(fid, 4, 'uchar')'); % read chunk ID siz = fread(fid, 1, 'uint32'); % read chunk size if strcmp(id, 'GRP ') | strcmp(id, 'BIFF') id = char(fread(fid, 4, 'uchar')'); % read real chunk ID siz = siz - 4; % reduce size by 4 end
github
philippboehmsturm/antx-master
read_eeglabheader.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_eeglabheader.m
2,255
utf_8
fe4446f32b250441d57acff9ebe691a2
% read_eeglabheader() - import EEGLAB dataset files % % Usage: % >> header = read_eeglabheader(filename); % % Inputs: % filename - [string] file name % % Outputs: % header - FILEIO toolbox type structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2008- %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function header = read_eeglabheader(filename) if nargin < 1 help read_eeglabheader; return; end; if ~isstruct(filename) load('-mat', filename); else EEG = filename; end; header.Fs = EEG.srate; header.nChans = EEG.nbchan; header.nSamples = EEG.pnts; header.nSamplesPre = -EEG.xmin*EEG.srate; header.nTrials = EEG.trials; try header.label = { EEG.chanlocs.labels }'; catch warning('creating default channel names'); for i=1:header.nChans header.label{i} = sprintf('chan%03d', i); end end ind = 1; for i = 1:length( EEG.chanlocs ) if isfield(EEG.chanlocs(i), 'X') && ~isempty(EEG.chanlocs(i).X) header.elec.label{ind, 1} = EEG.chanlocs(i).labels; % this channel has a position header.elec.pnt(ind,1) = EEG.chanlocs(i).X; header.elec.pnt(ind,2) = EEG.chanlocs(i).Y; header.elec.pnt(ind,3) = EEG.chanlocs(i).Z; ind = ind+1; end; end; % remove data % ----------- %if isfield(EEG, 'datfile') % if ~isempty(EEG.datfile) % EEG.data = EEG.datfile; % end; %else % EEG.data = 'in set file'; %end; EEG.icaact = []; header.orig = EEG;
github
philippboehmsturm/antx-master
read_ctf_svl.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_ctf_svl.m
3,812
utf_8
d3442d0a013cf5e0a8d4277d99e45206
% [data, hdr] = opensvl(filename) % % Reads a CTF SAM (.svl) file. function [data, hdr] = read_ctf_svl(filename) fid = fopen(filename, 'rb', 'ieee-be', 'ISO-8859-1'); if fid <= 0 error('Could not open SAM file: %s\n', filename); end % ---------------------------------------------------------------------- % Read header. hdr.identity = fread(fid, 8, '*char')'; % 'SAMIMAGE' hdr.version = fread(fid, 1, 'int32'); % SAM file version. hdr.setName = fread(fid, 256, '*char')'; % Dataset name. hdr.numChans = fread(fid, 1, 'int32'); hdr.numWeights = fread(fid, 1, 'int32'); % 0 for static image. if(hdr.numWeights ~= 0) warning('hdr.numWeights ~= 0'); end fread(fid,1,'int32'); % Padding to next 8 byte boundary. hdr.xmin = fread(fid, 1, 'double'); % Bounding box coordinates (m). hdr.xmax = fread(fid, 1, 'double'); hdr.ymin = fread(fid, 1, 'double'); hdr.ymax = fread(fid, 1, 'double'); hdr.zmin = fread(fid, 1, 'double'); hdr.zmax = fread(fid, 1, 'double'); hdr.stepSize = fread(fid, 1, 'double'); % m hdr.hpFreq = fread(fid, 1, 'double'); % High pass filtering frequency (Hz). hdr.lpFreq = fread(fid, 1, 'double'); % Low pass. hdr.bwFreq = fread(fid, 1, 'double'); % Bandwidth hdr.meanNoise = fread(fid, 1, 'double'); % Sensor noise (T). hdr.mriName = fread(fid, 256, '*char')'; hdr.fiducial.mri.nas = fread(fid, 3, 'int32'); % CTF MRI voxel coordinates? hdr.fiducial.mri.rpa = fread(fid, 3, 'int32'); hdr.fiducial.mri.lpa = fread(fid, 3, 'int32'); hdr.SAMType = fread(fid, 1, 'int32'); % 0: image, 1: weights array, 2: weights list. hdr.SAMUnit = fread(fid, 1, 'int32'); % Possible values: 0 coefficients Am/T, 1 moment Am, 2 power (Am)^2, 3 Z, % 4 F, 5 T, 6 probability, 7 MUSIC. fread(fid, 1, 'int32'); % Padding to next 8 byte boundary. if hdr.version > 1 % Version 2 has extra fields. hdr.fiducial.head.nas = fread(fid, 3, 'double'); % CTF head coordinates? hdr.fiducial.head.rpa = fread(fid, 3, 'double'); hdr.fiducial.head.lpa = fread(fid, 3, 'double'); hdr.SAMUnitName = fread(fid, 32, '*char')'; % Possible values: 'Am/T' SAM coefficients, 'Am' source strength, % '(Am)^2' source power, ('Z', 'F', 'T') statistics, 'P' probability. end % ---------------------------------------------------------------------- % Read image data. data = fread(fid, inf, 'double'); fclose(fid); % Raw image data is ordered as a C array with indices: [x][y][z], meaning % z changes fastest and x slowest. These x, y, z axes point to ALS % (anterior, left, superior) respectively in real world coordinates, % which means the voxels are in SLA order. % ---------------------------------------------------------------------- % Post processing. % Change from m to mm. hdr.xmin = hdr.xmin * 1000; hdr.ymin = hdr.ymin * 1000; hdr.zmin = hdr.zmin * 1000; hdr.xmax = hdr.xmax * 1000; hdr.ymax = hdr.ymax * 1000; hdr.zmax = hdr.zmax * 1000; hdr.stepSize = hdr.stepSize * 1000; % Number of voxels in each dimension. hdr.dim = [round((hdr.xmax - hdr.xmin)/hdr.stepSize) + 1, ... round((hdr.ymax - hdr.ymin)/hdr.stepSize) + 1, ... round((hdr.zmax - hdr.zmin)/hdr.stepSize) + 1]; data = reshape(data, hdr.dim([3, 2, 1])); % Build transformation matrix from raw voxel coordinates (indexed from 1) % to head coordinates in mm. Note that the bounding box is given in % these coordinates (in m, but converted above). % Apply scaling. hdr.transform = diag([hdr.stepSize * ones(1, 3), 1]); % Reorder directions. hdr.transform = hdr.transform(:, [3, 2, 1, 4]); % Apply translation. hdr.transform(1:3, 4) = [hdr.xmin; hdr.ymin; hdr.zmin] - hdr.stepSize; % -step is needed since voxels are indexed from 1. end
github
philippboehmsturm/antx-master
read_erplabevent.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_erplabevent.m
1,786
utf_8
40ece49ff6bd2afd6024b46f210e65fa
% read_erplabevent() - import ERPLAB dataset events % % Usage: % >> event = read_erplabevent(filename, ...); % % Inputs: % filename - [string] file name % % Optional inputs: % 'header' - FILEIO structure header % % Outputs: % event - FILEIO toolbox event structure % % Modified from read_eeglabevent %123456789012345678901234567890123456789012345678901234567890123456789012 % % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function event = read_erplabevent(filename, varargin) if nargin < 1 help read_erplabheader; return; end; hdr = ft_getopt(varargin, 'header'); if isempty(hdr) hdr = read_erplabheader(filename); end event = []; % these will be the output in FieldTrip format oldevent = hdr.orig.bindescr; % these are in ERPLAB format for index = 1:length(oldevent) event(end+1).type = 'trial'; event(end ).sample = (index-1)*hdr.nSamples + 1; event(end ).value = oldevent{index}; event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; end;
github
philippboehmsturm/antx-master
read_yokogawa_header_new.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_yokogawa_header_new.m
8,959
utf_8
654f373c60405e9a27c40d65ab0147dd
function hdr = read_yokogawa_header_new(filename) % READ_YOKOGAWA_HEADER_NEW reads the header information from continuous, % epoched or averaged MEG data that has been generated by the Yokogawa % MEG system and software and allows that data to be used in combination % with FieldTrip. % % Use as % [hdr] = read_yokogawa_header_new(filename) % % This is a wrapper function around the functions % getYkgwHdrSystem % getYkgwHdrChannel % getYkgwHdrAcqCond % getYkgwHdrCoregist % getYkgwHdrDigitize % getYkgwHdrSource % % See also READ_YOKOGAWA_DATA_NEW, READ_YOKOGAWA_EVENT % ** % Copyright (C) 2005, Robert Oostenveld and 2010, Tilmann Sander-Thoemmes % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_yokogawa_header_new.m 7123 2012-12-06 21:21:38Z roboos $ % FIXED % txt -> m % fopen iee-le if ~ft_hastoolbox('yokogawa_meg_reader') error('cannot determine whether Yokogawa toolbox is present'); end handles = definehandles; sys_info = getYkgwHdrSystem(filename); id = sys_info.system_id; ver = sys_info.version; rev = sys_info.revision; sys_name = sys_info.system_name; model_name = sys_info.model_name; clear('sys_info'); % remove structure as local variables are collected in the end channel_info = getYkgwHdrChannel(filename); channel_count = channel_info.channel_count; acq_cond = getYkgwHdrAcqCond(filename); acq_type = acq_cond.acq_type; % these depend on the data type sample_rate = []; sample_count = []; pretrigger_length = []; averaged_count = []; actual_epoch_count = []; switch acq_type case handles.AcqTypeContinuousRaw sample_rate = acq_cond.sample_rate; sample_count = acq_cond.sample_count; if isempty(sample_rate) | isempty(sample_count) error('invalid sample rate or sample count in ', filename); return; end pretrigger_length = 0; averaged_count = 1; case handles.AcqTypeEvokedAve sample_rate = acq_cond.sample_rate; sample_count = acq_cond.frame_length; pretrigger_length = acq_cond.pretrigger_length; averaged_count = acq_cond.average_count; if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(averaged_count) error('invalid sample rate or sample count or pretrigger length or average count in ', filename); return; end if acq_cond.multi_trigger.enable error('multi trigger mode not supported for ', filename); return; end case handles.AcqTypeEvokedRaw sample_rate = acq_cond.sample_rate; sample_count = acq_cond.frame_length; pretrigger_length = acq_cond.pretrigger_length; actual_epoch_count = acq_cond.average_count; if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(actual_epoch_count) error('invalid sample rate or sample count or pretrigger length or epoch count in ', filename); return; end if acq_cond.multi_trigger.enable error('multi trigger mode not supported for ', filename); return; end otherwise error('unknown data type'); end clear('acq_cond'); % remove structure as local variables are collected in the end coregist = getYkgwHdrCoregist(filename); digitize = getYkgwHdrDigitize(filename); source = getYkgwHdrSource(filename); % put all local variables into a structure, this is a bit unusual matlab programming style tmp = whos; orig = []; for i=1:length(tmp) if isempty(strmatch(tmp(i).name, {'tmp', 'ans', 'handles'})) orig = setfield(orig, tmp(i).name, eval(tmp(i).name)); end end % convert the original header information into something that FieldTrip understands hdr = []; hdr.orig = orig; % also store the original full header information hdr.Fs = orig.sample_rate; % sampling frequency hdr.nChans = orig.channel_count; % number of channels hdr.nSamples = []; % number of samples per trial hdr.nSamplesPre = []; % number of pre-trigger samples in each trial hdr.nTrials = []; % number of trials switch orig.acq_type case handles.AcqTypeEvokedAve hdr.nSamples = orig.sample_count; hdr.nSamplesPre = orig.pretrigger_length; hdr.nTrials = 1; % only the average, which can be considered as a single trial case handles.AcqTypeContinuousRaw hdr.nSamples = orig.sample_count; hdr.nSamplesPre = 0; % there is no fixed relation between triggers and data hdr.nTrials = 1; % the continuous data can be considered as a single very long trial case handles.AcqTypeEvokedRaw hdr.nSamples = orig.sample_count; hdr.nSamplesPre = orig.pretrigger_length; hdr.nTrials = orig.actual_epoch_count; otherwise error('unknown acquisition type'); end % construct a cell-array with labels of each channel for i=1:hdr.nChans % this should be consistent with the predefined list in ft_senslabel, % with yokogawa2grad_new and with ft_channelselection if hdr.orig.channel_info.channel(i).type == handles.NullChannel prefix = ''; elseif hdr.orig.channel_info.channel(i).type == handles.MagnetoMeter prefix = 'M'; elseif hdr.orig.channel_info.channel(i).type == handles.AxialGradioMeter prefix = 'AG'; elseif hdr.orig.channel_info.channel(i).type == handles.PlannerGradioMeter prefix = 'PG'; elseif hdr.orig.channel_info.channel(i).type == handles.RefferenceMagnetoMeter prefix = 'RM'; elseif hdr.orig.channel_info.channel(i).type == handles.RefferenceAxialGradioMeter prefix = 'RAG'; elseif hdr.orig.channel_info.channel(i).type == handles.RefferencePlannerGradioMeter prefix = 'RPG'; elseif hdr.orig.channel_info.channel(i).type == handles.TriggerChannel prefix = 'TRIG'; elseif hdr.orig.channel_info.channel(i).type == handles.EegChannel prefix = 'EEG'; elseif hdr.orig.channel_info.channel(i).type == handles.EcgChannel prefix = 'ECG'; elseif hdr.orig.channel_info.channel(i).type == handles.EtcChannel prefix = 'ETC'; end hdr.label{i} = sprintf('%s%03d', prefix, i); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles; handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.eegchannel_ch_no = []; handles.sqd.eegchannel_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
philippboehmsturm/antx-master
ft_datatype_raw.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/ft_datatype_raw.m
10,365
utf_8
8e666a629bcfec8802a49fc7d1eb4d8c
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 7217 2012-12-17 19:45:35Z 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
loadcnt.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/loadcnt.m
23,166
utf_8
3629cdf2a890ef76f423f15fff965b3a
% loadcnt() - Load a Neuroscan continuous signal file. % % Usage: % >> cnt = loadcnt(file, varargin) % % Inputs: % filename - name of the file with extension % % Optional inputs: % 't1' - start at time t1, default 0. Warning, events latency % might be innacurate (this is an open issue). % 'sample1' - start at sample1, default 0, overrides t1. Warning, % events latency might be innacurate. % 'lddur' - duration of segment to load, default = whole file % 'ldnsamples' - number of samples to load, default = whole file, % overrides lddur % 'scale' - ['on'|'off'] scale data to microvolt (default:'on') % 'dataformat' - ['int16'|'int32'] default is 'int16' for 16-bit data. % Use 'int32' for 32-bit data. % 'blockread' - [integer] by default it is automatically determined % from the file header, though sometimes it finds an % incorect value, so you may want to enter a value manually % here (1 is the most standard value). % 'memmapfile' - ['memmapfile_name'] use this option if the .cnt file % is too large to read in conventially. The suffix of % the memmapfile_name must be .fdt. The memmapfile % functions process files based on their suffix, and an % error will occur if you use a different suffix. % % Outputs: % cnt - structure with the continuous data and other informations % cnt.header % cnt.electloc % cnt.data % cnt.tag % % Authors: Sean Fitzgibbon, Arnaud Delorme, 2000- % % Note: function original name was load_scan41.m % % Known limitations: % For more see http://www.cnl.salk.edu/~arno/cntload/index.html % Copyright (C) 2000 Sean Fitzgibbon, <[email protected]> % Copyright (C) 2003 Arnaud Delorme, Salk Institute, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function [f,lab,ev2p] = loadcnt(filename,varargin) if ~isempty(varargin) r=struct(varargin{:}); else r = []; end; try, r.t1; catch, r.t1=0; end try, r.sample1; catch, r.sample1=[]; end try, r.lddur; catch, r.lddur=[]; end try, r.ldnsamples; catch, r.ldnsamples=[]; end try, r.scale; catch, r.scale='on'; end try, r.blockread; catch, r.blockread = []; end try, r.dataformat; catch, r.dataformat = 'auto'; end try, r.memmapfile; catch, r.memmapfile = ''; end sizeEvent1 = 8 ; %%% 8 bytes for Event1 sizeEvent2 = 19 ; %%% 19 bytes for Event2 sizeEvent3 = 19 ; %%% 19 bytes for Event3 type='cnt'; if nargin ==1 scan=0; end fid = fopen(filename,'r', 'l'); disp(['Loading file ' filename ' ...']) h.rev = fread(fid,12,'char'); h.nextfile = fread(fid,1,'long'); h.prevfile = fread(fid,1,'ulong'); h.type = fread(fid,1,'char'); h.id = fread(fid,20,'char'); h.oper = fread(fid,20,'char'); h.doctor = fread(fid,20,'char'); h.referral = fread(fid,20,'char'); h.hospital = fread(fid,20,'char'); h.patient = fread(fid,20,'char'); h.age = fread(fid,1,'short'); h.sex = fread(fid,1,'char'); h.hand = fread(fid,1,'char'); h.med = fread(fid,20, 'char'); h.category = fread(fid,20, 'char'); h.state = fread(fid,20, 'char'); h.label = fread(fid,20, 'char'); h.date = fread(fid,10, 'char'); h.time = fread(fid,12, 'char'); h.mean_age = fread(fid,1,'float'); h.stdev = fread(fid,1,'float'); h.n = fread(fid,1,'short'); h.compfile = fread(fid,38,'char'); h.spectwincomp = fread(fid,1,'float'); h.meanaccuracy = fread(fid,1,'float'); h.meanlatency = fread(fid,1,'float'); h.sortfile = fread(fid,46,'char'); h.numevents = fread(fid,1,'int'); h.compoper = fread(fid,1,'char'); h.avgmode = fread(fid,1,'char'); h.review = fread(fid,1,'char'); h.nsweeps = fread(fid,1,'ushort'); h.compsweeps = fread(fid,1,'ushort'); h.acceptcnt = fread(fid,1,'ushort'); h.rejectcnt = fread(fid,1,'ushort'); h.pnts = fread(fid,1,'ushort'); h.nchannels = fread(fid,1,'ushort'); h.avgupdate = fread(fid,1,'ushort'); h.domain = fread(fid,1,'char'); h.variance = fread(fid,1,'char'); h.rate = fread(fid,1,'ushort'); % A USER CLAIMS THAT SAMPLING RATE CAN BE h.scale = fread(fid,1,'double'); % FRACTIONAL IN NEUROSCAN WHICH IS h.veogcorrect = fread(fid,1,'char'); % OBVIOUSLY NOT POSSIBLE HERE (BUG 606) h.heogcorrect = fread(fid,1,'char'); h.aux1correct = fread(fid,1,'char'); h.aux2correct = fread(fid,1,'char'); h.veogtrig = fread(fid,1,'float'); h.heogtrig = fread(fid,1,'float'); h.aux1trig = fread(fid,1,'float'); h.aux2trig = fread(fid,1,'float'); h.heogchnl = fread(fid,1,'short'); h.veogchnl = fread(fid,1,'short'); h.aux1chnl = fread(fid,1,'short'); h.aux2chnl = fread(fid,1,'short'); h.veogdir = fread(fid,1,'char'); h.heogdir = fread(fid,1,'char'); h.aux1dir = fread(fid,1,'char'); h.aux2dir = fread(fid,1,'char'); h.veog_n = fread(fid,1,'short'); h.heog_n = fread(fid,1,'short'); h.aux1_n = fread(fid,1,'short'); h.aux2_n = fread(fid,1,'short'); h.veogmaxcnt = fread(fid,1,'short'); h.heogmaxcnt = fread(fid,1,'short'); h.aux1maxcnt = fread(fid,1,'short'); h.aux2maxcnt = fread(fid,1,'short'); h.veogmethod = fread(fid,1,'char'); h.heogmethod = fread(fid,1,'char'); h.aux1method = fread(fid,1,'char'); h.aux2method = fread(fid,1,'char'); h.ampsensitivity = fread(fid,1,'float'); h.lowpass = fread(fid,1,'char'); h.highpass = fread(fid,1,'char'); h.notch = fread(fid,1,'char'); h.autoclipadd = fread(fid,1,'char'); h.baseline = fread(fid,1,'char'); h.offstart = fread(fid,1,'float'); h.offstop = fread(fid,1,'float'); h.reject = fread(fid,1,'char'); h.rejstart = fread(fid,1,'float'); h.rejstop = fread(fid,1,'float'); h.rejmin = fread(fid,1,'float'); h.rejmax = fread(fid,1,'float'); h.trigtype = fread(fid,1,'char'); h.trigval = fread(fid,1,'float'); h.trigchnl = fread(fid,1,'char'); h.trigmask = fread(fid,1,'short'); h.trigisi = fread(fid,1,'float'); h.trigmin = fread(fid,1,'float'); h.trigmax = fread(fid,1,'float'); h.trigdir = fread(fid,1,'char'); h.autoscale = fread(fid,1,'char'); h.n2 = fread(fid,1,'short'); h.dir = fread(fid,1,'char'); h.dispmin = fread(fid,1,'float'); h.dispmax = fread(fid,1,'float'); h.xmin = fread(fid,1,'float'); h.xmax = fread(fid,1,'float'); h.automin = fread(fid,1,'float'); h.automax = fread(fid,1,'float'); h.zmin = fread(fid,1,'float'); h.zmax = fread(fid,1,'float'); h.lowcut = fread(fid,1,'float'); h.highcut = fread(fid,1,'float'); h.common = fread(fid,1,'char'); h.savemode = fread(fid,1,'char'); h.manmode = fread(fid,1,'char'); h.ref = fread(fid,10,'char'); h.rectify = fread(fid,1,'char'); h.displayxmin = fread(fid,1,'float'); h.displayxmax = fread(fid,1,'float'); h.phase = fread(fid,1,'char'); h.screen = fread(fid,16,'char'); h.calmode = fread(fid,1,'short'); h.calmethod = fread(fid,1,'short'); h.calupdate = fread(fid,1,'short'); h.calbaseline = fread(fid,1,'short'); h.calsweeps = fread(fid,1,'short'); h.calattenuator = fread(fid,1,'float'); h.calpulsevolt = fread(fid,1,'float'); h.calpulsestart = fread(fid,1,'float'); h.calpulsestop = fread(fid,1,'float'); h.calfreq = fread(fid,1,'float'); h.taskfile = fread(fid,34,'char'); h.seqfile = fread(fid,34,'char'); h.spectmethod = fread(fid,1,'char'); h.spectscaling = fread(fid,1,'char'); h.spectwindow = fread(fid,1,'char'); h.spectwinlength = fread(fid,1,'float'); h.spectorder = fread(fid,1,'char'); h.notchfilter = fread(fid,1,'char'); h.headgain = fread(fid,1,'short'); h.additionalfiles = fread(fid,1,'int'); h.unused = fread(fid,5,'char'); h.fspstopmethod = fread(fid,1,'short'); h.fspstopmode = fread(fid,1,'short'); h.fspfvalue = fread(fid,1,'float'); h.fsppoint = fread(fid,1,'short'); h.fspblocksize = fread(fid,1,'short'); h.fspp1 = fread(fid,1,'ushort'); h.fspp2 = fread(fid,1,'ushort'); h.fspalpha = fread(fid,1,'float'); h.fspnoise = fread(fid,1,'float'); h.fspv1 = fread(fid,1,'short'); h.montage = fread(fid,40,'char'); h.eventfile = fread(fid,40,'char'); h.fratio = fread(fid,1,'float'); h.minor_rev = fread(fid,1,'char'); h.eegupdate = fread(fid,1,'short'); h.compressed = fread(fid,1,'char'); h.xscale = fread(fid,1,'float'); h.yscale = fread(fid,1,'float'); h.xsize = fread(fid,1,'float'); h.ysize = fread(fid,1,'float'); h.acmode = fread(fid,1,'char'); h.commonchnl = fread(fid,1,'uchar'); h.xtics = fread(fid,1,'char'); h.xrange = fread(fid,1,'char'); h.ytics = fread(fid,1,'char'); h.yrange = fread(fid,1,'char'); h.xscalevalue = fread(fid,1,'float'); h.xscaleinterval = fread(fid,1,'float'); h.yscalevalue = fread(fid,1,'float'); h.yscaleinterval = fread(fid,1,'float'); h.scaletoolx1 = fread(fid,1,'float'); h.scaletooly1 = fread(fid,1,'float'); h.scaletoolx2 = fread(fid,1,'float'); h.scaletooly2 = fread(fid,1,'float'); h.port = fread(fid,1,'short'); h.numsamples = fread(fid,1,'ulong'); h.filterflag = fread(fid,1,'char'); h.lowcutoff = fread(fid,1,'float'); h.lowpoles = fread(fid,1,'short'); h.highcutoff = fread(fid,1,'float'); h.highpoles = fread(fid,1,'short'); h.filtertype = fread(fid,1,'char'); h.filterdomain = fread(fid,1,'char'); h.snrflag = fread(fid,1,'char'); h.coherenceflag = fread(fid,1,'char'); h.continuoustype = fread(fid,1,'char'); h.eventtablepos = fread(fid,1,'ulong'); h.continuousseconds = fread(fid,1,'float'); h.channeloffset = fread(fid,1,'long'); h.autocorrectflag = fread(fid,1,'char'); h.dcthreshold = fread(fid,1,'uchar'); for n = 1:h.nchannels e(n).lab = deblank(char(fread(fid,10,'char')')); e(n).reference = fread(fid,1,'char'); e(n).skip = fread(fid,1,'char'); e(n).reject = fread(fid,1,'char'); e(n).display = fread(fid,1,'char'); e(n).bad = fread(fid,1,'char'); e(n).n = fread(fid,1,'ushort'); e(n).avg_reference = fread(fid,1,'char'); e(n).clipadd = fread(fid,1,'char'); e(n).x_coord = fread(fid,1,'float'); e(n).y_coord = fread(fid,1,'float'); e(n).veog_wt = fread(fid,1,'float'); e(n).veog_std = fread(fid,1,'float'); e(n).snr = fread(fid,1,'float'); e(n).heog_wt = fread(fid,1,'float'); e(n).heog_std = fread(fid,1,'float'); e(n).baseline = fread(fid,1,'short'); e(n).filtered = fread(fid,1,'char'); e(n).fsp = fread(fid,1,'char'); e(n).aux1_wt = fread(fid,1,'float'); e(n).aux1_std = fread(fid,1,'float'); e(n).senstivity = fread(fid,1,'float'); e(n).gain = fread(fid,1,'char'); e(n).hipass = fread(fid,1,'char'); e(n).lopass = fread(fid,1,'char'); e(n).page = fread(fid,1,'uchar'); e(n).size = fread(fid,1,'uchar'); e(n).impedance = fread(fid,1,'uchar'); e(n).physicalchnl = fread(fid,1,'uchar'); e(n).rectify = fread(fid,1,'char'); e(n).calib = fread(fid,1,'float'); end % finding if 32-bits of 16-bits file % ---------------------------------- begdata = ftell(fid); if strcmpi(r.dataformat, 'auto') r.dataformat = 'int16'; if (h.nextfile > 0) fseek(fid,h.nextfile+52,'bof'); is32bit = fread(fid,1,'char'); if (is32bit == 1) r.dataformat = 'int32'; end; fseek(fid,begdata,'bof'); end; end; enddata = h.eventtablepos; % after data if strcmpi(r.dataformat, 'int16') nums = (enddata-begdata)/h.nchannels/2; else nums = (enddata-begdata)/h.nchannels/4; end; % number of sample to read % ------------------------ if ~isempty(r.sample1) r.t1 = r.sample1/h.rate; else r.sample1 = r.t1*h.rate; end; if strcmpi(r.dataformat, 'int16') startpos = r.t1*h.rate*2*h.nchannels; else startpos = r.t1*h.rate*4*h.nchannels; end; if isempty(r.ldnsamples) if ~isempty(r.lddur) r.ldnsamples = round(r.lddur*h.rate); else r.ldnsamples = nums; end; end; % FIELDTRIP BUGFIX #1412 % In some cases, the orig.header.numsamples = 0, and the output number of samples is wrong. % In the previous version of loadcnt.m the orig.header.nums field was used (instead of numsamples), which was changed in r5380 to fix bug #1348. % This bug (1348) was due to loadcnt.m being updated to the most recent version (from neuroscan), which removed the nums field in favor of using numsamples. % Below is a workaround for when numsamples is incorrect (bug 1412). The reason is unknown (it looks like a neuroscan data-file specific bug). % I re-added the nums field to loadcnt.m so that it can be used in ft_read_header.m. % -roevdmei h.nums = nums; % channel offset % -------------- if ~isempty(r.blockread) h.channeloffset = r.blockread; end; if h.channeloffset > 1 fprintf('WARNING: reading data in blocks of %d, if this fails, try using option "''blockread'', 1"\n', ... h.channeloffset); end; disp('Reading data .....') if type == 'cnt' % while (ftell(fid) +1 < h.eventtablepos) %d(:,i)=fread(fid,h.nchannels,'int16'); %end fseek(fid, startpos, 0); % **** This marks the beginning of the code modified for reading % large .cnt files % Switched to r.memmapfile for continuity. Check to see if the % variable exists. If it does, then the user has indicated the % file is too large to be processed in memory. If the variable % is blank, the file is processed in memory. if (~isempty(r.memmapfile)) % open a file for writing foutid = fopen(r.memmapfile, 'w') ; % This portion of the routine reads in a section of the EEG file % and then writes it out to the harddisk. samples_left = h.nchannels * r.ldnsamples ; % the size of the data block to be read is limited to 4M % samples. This equates to 16MB and 32MB of memory for % 16 and 32 bit files, respectively. data_block = 4000000 ; max_rows = data_block / h.nchannels ; %warning off ; max_written = h.nchannels * uint32(max_rows) ; %warning on ; % This while look tracks the remaining samples. The % data is processed in chunks rather than put into % memory whole. while (samples_left > 0) % Check to see if the remaining data is smaller than % the general processing block by looking at the % remaining number of rows. to_read = max_rows ; if (data_block > samples_left) to_read = samples_left / h.nchannels ; end ; % Read data in a relatively small chunk temp_dat = fread(fid, [h.nchannels to_read], r.dataformat) ; % The data is then scaled using the original routine. % In the original routine, the entire data set was scaled % after being read in. For this version, scaling occurs % after every chunk is read. if strcmpi(r.scale, 'on') disp('Scaling data .....') %%% scaling to microvolts for i=1:h.nchannels bas=e(i).baseline;sen=e(i).senstivity;cal=e(i).calib; mf=sen*(cal/204.8); temp_dat(i,:)=(temp_dat(i,:)-bas).*mf; end end % Write out data in float32 form to the file name % supplied by the user. written = fwrite (foutid, temp_dat, 'float32') ; if (written ~= max_written) samples_left = 0 ; else samples_left = samples_left - written ; end ; end ; fclose (foutid) ; % Set the dat variable. This gets used later by other % EEGLAB functions. dat = r.memmapfile ; % This variable tracks how the data should be read. bReadIntoMemory = false ; else % The memmapfile variable is empty, read into memory. bReadIntoMemory = true ; end % This ends the modifications made to read large files. % Everything contained within the following if statement is the % original code. if (bReadIntoMemory == true) if h.channeloffset <= 1 dat=fread(fid, [h.nchannels Inf], r.dataformat); if size(dat,2) < r.ldnsamples dat=single(dat); r.ldnsamples = size(dat,2); else dat=single(dat(:,1:r.ldnsamples)); end; else h.channeloffset = h.channeloffset/2; % reading data in blocks dat = zeros( h.nchannels, r.ldnsamples, 'single'); dat(:, 1:h.channeloffset) = fread(fid, [h.channeloffset h.nchannels], r.dataformat)'; counter = 1; while counter*h.channeloffset < r.ldnsamples dat(:, counter*h.channeloffset+1:counter*h.channeloffset+h.channeloffset) = ... fread(fid, [h.channeloffset h.nchannels], r.dataformat)'; counter = counter + 1; end; end ; % ftell(fid) if strcmpi(r.scale, 'on') disp('Scaling data .....') %%% scaling to microvolts for i=1:h.nchannels bas=e(i).baseline;sen=e(i).senstivity;cal=e(i).calib; mf=sen*(cal/204.8); dat(i,:)=(dat(i,:)-bas).*mf; end % end for i=1:h.nchannels end; % end if (strcmpi(r.scale, 'on') end ; ET_offset = (double(h.prevfile) * (2^32)) + double(h.eventtablepos); % prevfile contains high order bits of event table offset, eventtablepos contains the low order bits fseek(fid, ET_offset, 'bof'); disp('Reading Event Table...') eT.teeg = fread(fid,1,'uchar'); eT.size = fread(fid,1,'ulong'); eT.offset = fread(fid,1,'ulong'); if eT.teeg==2 nevents=eT.size/sizeEvent2; if nevents > 0 ev2(nevents).stimtype = []; for i=1:nevents ev2(i).stimtype = fread(fid,1,'ushort'); ev2(i).keyboard = fread(fid,1,'char'); temp = fread(fid,1,'uint8'); ev2(i).keypad_accept = bitand(15,temp); ev2(i).accept_ev1 = bitshift(temp,-4); ev2(i).offset = fread(fid,1,'long'); ev2(i).type = fread(fid,1,'short'); ev2(i).code = fread(fid,1,'short'); ev2(i).latency = fread(fid,1,'float'); ev2(i).epochevent = fread(fid,1,'char'); ev2(i).accept = fread(fid,1,'char'); ev2(i).accuracy = fread(fid,1,'char'); end else ev2 = []; end; elseif eT.teeg==3 % type 3 is similar to type 2 except the offset field encodes the global sample frame nevents=eT.size/sizeEvent3; if nevents > 0 ev2(nevents).stimtype = []; if r.dataformat == 'int32' bytes_per_samp = 4; % I only have 32 bit data, unable to check whether this is necessary, else % perhaps there is no type 3 file with 16 bit data bytes_per_samp = 2; end for i=1:nevents ev2(i).stimtype = fread(fid,1,'ushort'); ev2(i).keyboard = fread(fid,1,'char'); temp = fread(fid,1,'uint8'); ev2(i).keypad_accept = bitand(15,temp); ev2(i).accept_ev1 = bitshift(temp,-4); os = fread(fid,1,'ulong'); ev2(i).offset = os * bytes_per_samp * h.nchannels; ev2(i).type = fread(fid,1,'short'); ev2(i).code = fread(fid,1,'short'); ev2(i).latency = fread(fid,1,'float'); ev2(i).epochevent = fread(fid,1,'char'); ev2(i).accept = fread(fid,1,'char'); ev2(i).accuracy = fread(fid,1,'char'); end else ev2 = []; end; elseif eT.teeg==1 nevents=eT.size/sizeEvent1; if nevents > 0 ev2(nevents).stimtype = []; for i=1:nevents ev2(i).stimtype = fread(fid,1,'ushort'); ev2(i).keyboard = fread(fid,1,'char'); % modified by Andreas Widmann 2005/05/12 14:15:00 %ev2(i).keypad_accept = fread(fid,1,'char'); temp = fread(fid,1,'uint8'); ev2(i).keypad_accept = bitand(15,temp); ev2(i).accept_ev1 = bitshift(temp,-4); % end modification ev2(i).offset = fread(fid,1,'long'); end; else ev2 = []; end; else disp('Skipping event table (tag != 1,2,3 ; theoritically impossible)'); ev2 = []; end fseek(fid, -1, 'eof'); t = fread(fid,'char'); f.header = h; f.electloc = e; f.data = dat; f.Teeg = eT; f.event = ev2; f.tag=t; % Surgical addition of number of samples f.ldnsamples = r.ldnsamples ; %%%% channels labels for i=1:h.nchannels plab=sprintf('%c',f.electloc(i).lab); if i>1 lab=str2mat(lab,plab); else lab=plab; end end %%%% to change offest in bytes to points if ~isempty(ev2) if r.sample1 ~= 0 fprintf(2,'Warning: events imported with a time shift might be innacurate\n'); end; ev2p=ev2; ioff=900+(h.nchannels*75); %% initial offset : header + electordes desc if strcmpi(r.dataformat, 'int16') for i=1:nevents ev2p(i).offset=(ev2p(i).offset-ioff)/(2*h.nchannels) - r.sample1; %% 2 short int end end else % 32 bits for i=1:nevents ev2p(i).offset=(ev2p(i).offset-ioff)/(4*h.nchannels) - r.sample1; %% 4 short int end end end; f.event = ev2p; end; frewind(fid); fclose(fid); end
github
philippboehmsturm/antx-master
read_yokogawa_header.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_yokogawa_header.m
8,340
utf_8
c1392a52ad7bb86127e7a704c5abce9d
function hdr = read_yokogawa_header(filename) % READ_YOKOGAWA_HEADER reads the header information from continuous, % epoched or averaged MEG data that has been generated by the Yokogawa % MEG system and software and allows that data to be used in combination % with FieldTrip. % % Use as % [hdr] = read_yokogawa_header(filename) % % This is a wrapper function around the functions % GetMeg160SystemInfoM % GetMeg160ChannelCountM % GetMeg160ChannelInfoM % GetMeg160CalibInfoM % GetMeg160AmpGainM % GetMeg160DataAcqTypeM % GetMeg160ContinuousAcqCondM % GetMeg160EvokedAcqCondM % % See also READ_YOKOGAWA_DATA, READ_YOKOGAWA_EVENT % this function also calls % GetMeg160MriInfoM % GetMeg160MatchingInfoM % GetMeg160SourceInfoM % but I don't know whether to use the information provided by those % Copyright (C) 2005, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_yokogawa_header.m 7123 2012-12-06 21:21:38Z roboos $ % FIXED % txt -> m % fopen iee-le if ~ft_hastoolbox('yokogawa') error('cannot determine whether Yokogawa toolbox is present'); end handles = definehandles; fid = fopen(filename, 'rb', 'ieee-le'); % these are always present [id ver rev sys_name] = GetMeg160SystemInfoM(fid); channel_count = GetMeg160ChannelCountM(fid); channel_info = GetMeg160ChannelInfoM(fid); calib_info = GetMeg160CalibInfoM(fid); amp_gain = GetMeg160AmpGainM(fid); acq_type = GetMeg160DataAcqTypeM(fid); ad_bit = GetMeg160ADbitInfoM(fid); % these depend on the data type sample_rate = []; sample_count = []; pretrigger_length = []; averaged_count = []; actual_epoch_count = []; switch acq_type case handles.AcqTypeContinuousRaw [sample_rate, sample_count] = GetMeg160ContinuousAcqCondM(fid); if isempty(sample_rate) | isempty(sample_count) fclose(fid); return; end pretrigger_length = 0; averaged_count = 1; case handles.AcqTypeEvokedAve [sample_rate, sample_count, pretrigger_length, averaged_count] = GetMeg160EvokedAcqCondM( fid ); if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(averaged_count) fclose(fid); return; end case handles.AcqTypeEvokedRaw [sample_rate, sample_count, pretrigger_length, actual_epoch_count] = GetMeg160EvokedAcqCondM( fid ); if isempty(sample_rate) | isempty(sample_count) | isempty(pretrigger_length) | isempty(actual_epoch_count) fclose(fid); return; end otherwise error('unknown data type'); end % these are always present mri_info = GetMeg160MriInfoM(fid); matching_info = GetMeg160MatchingInfoM(fid); source_info = GetMeg160SourceInfoM(fid); fclose(fid); % put all local variables into a structure, this is a bit unusual matlab programming style tmp = whos; orig = []; for i=1:length(tmp) if isempty(strmatch(tmp(i).name, {'tmp', 'fid', 'ans', 'handles'})) orig = setfield(orig, tmp(i).name, eval(tmp(i).name)); end end % convert the original header information into something that FieldTrip understands hdr = []; hdr.orig = orig; % also store the original full header information hdr.Fs = orig.sample_rate; % sampling frequency hdr.nChans = orig.channel_count; % number of channels hdr.nSamples = []; % number of samples per trial hdr.nSamplesPre = []; % number of pre-trigger samples in each trial hdr.nTrials = []; % number of trials switch orig.acq_type case handles.AcqTypeEvokedAve hdr.nSamples = orig.sample_count; hdr.nSamplesPre = orig.pretrigger_length; hdr.nTrials = 1; % only the average, which can be considered as a single trial case handles.AcqTypeContinuousRaw hdr.nSamples = orig.sample_count; hdr.nSamplesPre = 0; % there is no fixed relation between triggers and data hdr.nTrials = 1; % the continuous data can be considered as a single very long trial case handles.AcqTypeEvokedRaw hdr.nSamples = orig.sample_count; hdr.nSamplesPre = orig.pretrigger_length; hdr.nTrials = orig.actual_epoch_count; otherwise error('unknown acquisition type'); end % construct a cell-array with labels of each channel for i=1:hdr.nChans % this should be consistent with the predefined list in ft_senslabel, % with yokogawa2grad and with ft_channelselection if hdr.orig.channel_info(i, 2) == handles.NullChannel prefix = ''; elseif hdr.orig.channel_info(i, 2) == handles.MagnetoMeter prefix = 'M'; elseif hdr.orig.channel_info(i, 2) == handles.AxialGradioMeter prefix = 'AG'; elseif hdr.orig.channel_info(i, 2) == handles.PlannerGradioMeter prefix = 'PG'; elseif hdr.orig.channel_info(i, 2) == handles.RefferenceMagnetoMeter prefix = 'RM'; elseif hdr.orig.channel_info(i, 2) == handles.RefferenceAxialGradioMeter prefix = 'RAG'; elseif hdr.orig.channel_info(i, 2) == handles.RefferencePlannerGradioMeter prefix = 'RPG'; elseif hdr.orig.channel_info(i, 2) == handles.TriggerChannel prefix = 'TRIG'; elseif hdr.orig.channel_info(i, 2) == handles.EegChannel prefix = 'EEG'; elseif hdr.orig.channel_info(i, 2) == handles.EcgChannel prefix = 'ECG'; elseif hdr.orig.channel_info(i, 2) == handles.EtcChannel prefix = 'ETC'; end hdr.label{i} = sprintf('%s%03d', prefix, i); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this defines some usefull constants %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function handles = definehandles; handles.output = []; handles.sqd_load_flag = false; handles.mri_load_flag = false; handles.NullChannel = 0; handles.MagnetoMeter = 1; handles.AxialGradioMeter = 2; handles.PlannerGradioMeter = 3; handles.RefferenceChannelMark = hex2dec('0100'); handles.RefferenceMagnetoMeter = bitor( handles.RefferenceChannelMark, handles.MagnetoMeter ); handles.RefferenceAxialGradioMeter = bitor( handles.RefferenceChannelMark, handles.AxialGradioMeter ); handles.RefferencePlannerGradioMeter = bitor( handles.RefferenceChannelMark, handles.PlannerGradioMeter ); handles.TriggerChannel = -1; handles.EegChannel = -2; handles.EcgChannel = -3; handles.EtcChannel = -4; handles.NonMegChannelNameLength = 32; handles.DefaultMagnetometerSize = (4.0/1000.0); % Square of 4.0mm in length handles.DefaultAxialGradioMeterSize = (15.5/1000.0); % Circle of 15.5mm in diameter handles.DefaultPlannerGradioMeterSize = (12.0/1000.0); % Square of 12.0mm in length handles.AcqTypeContinuousRaw = 1; handles.AcqTypeEvokedAve = 2; handles.AcqTypeEvokedRaw = 3; handles.sqd = []; handles.sqd.selected_start = []; handles.sqd.selected_end = []; handles.sqd.axialgradiometer_ch_no = []; handles.sqd.axialgradiometer_ch_info = []; handles.sqd.axialgradiometer_data = []; handles.sqd.plannergradiometer_ch_no = []; handles.sqd.plannergradiometer_ch_info = []; handles.sqd.plannergradiometer_data = []; handles.sqd.eegchannel_ch_no = []; handles.sqd.eegchannel_data = []; handles.sqd.nullchannel_ch_no = []; handles.sqd.nullchannel_data = []; handles.sqd.selected_time = []; handles.sqd.sample_rate = []; handles.sqd.sample_count = []; handles.sqd.pretrigger_length = []; handles.sqd.matching_info = []; handles.sqd.source_info = []; handles.sqd.mri_info = []; handles.mri = [];
github
philippboehmsturm/antx-master
encode_nifti1.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/encode_nifti1.m
4,870
utf_8
9cf92a03587c511a5cec2c8c76a3c2c3
function blob = encode_nifti1(H) %function blob = encode_nifti1(H) % % Encodes a NIFTI-1 header (=> raw 348 bytes (uint8)) from a Matlab structure % that matches the C struct defined in nifti1.h. % % WARNING: This function currently ignores endianness !!! % (C) 2010 S.Klanke blob = uint8(zeros(1,348)); if ~isstruct(H) error 'Input must be a structure'; end % see nift1.h for information on structure sizeof_hdr = int32(348); blob(1:4) = typecast(sizeof_hdr, 'uint8'); blob = setString(blob, 5, 14, H, 'data_type'); blob = setString(blob, 15, 32, H, 'db_name'); blob = setInt32( blob, 33, 36, H, 'extents'); blob = setInt16( blob, 37, 38, H, 'session_error'); blob = setInt8( blob, 39, 39, H, 'regular'); blob = setInt8( blob, 40, 40, H, 'dim_info'); dim = int16(H.dim(:)'); ndim = numel(dim); if ndim<1 || ndim>7 error 'Field "dim" must have 1..7 elements'; end dim = [int16(ndim) dim]; blob(41:(42+2*ndim)) = typecast(dim,'uint8'); blob = setSingle(blob, 57, 60, H, 'intent_p1'); blob = setSingle(blob, 61, 64, H, 'intent_p2'); blob = setSingle(blob, 65, 68, H, 'intent_p3'); blob = setInt16( blob, 69, 70, H, 'intent_code'); blob = setInt16( blob, 71, 72, H, 'datatype'); blob = setInt16( blob, 73, 74, H, 'bitpix'); blob = setInt16( blob, 75, 76, H, 'slice_start'); blob = setSingle(blob, 77, 80, H, 'qfac'); if isfield(H,'pixdim') pixdim = single(H.pixdim(:)'); ndim = numel(pixdim); if ndim<1 || ndim>7 error 'Field "pixdim" must have 1..7 elements'; end blob(81:(80+4*ndim)) = typecast(pixdim,'uint8'); end blob = setSingle(blob, 109, 112, H, 'vox_offset'); blob = setSingle(blob, 113, 116, H, 'scl_scope'); blob = setSingle(blob, 117, 120, H, 'scl_inter'); blob = setInt16( blob, 121, 122, H, 'slice_end'); blob = setInt8( blob, 123, 123, H, 'slice_code'); blob = setInt8( blob, 124, 124, H, 'xyzt_units'); blob = setSingle(blob, 125, 128, H, 'cal_max'); blob = setSingle(blob, 129, 132, H, 'cal_min'); blob = setSingle(blob, 133, 136, H, 'slice_duration'); blob = setSingle(blob, 137, 140, H, 'toffset'); blob = setInt32( blob, 141, 144, H, 'glmax'); blob = setInt32( blob, 145, 148, H, 'glmin'); blob = setString(blob, 149, 228, H, 'descrip'); blob = setString(blob, 229, 252, H, 'aux_file'); blob = setInt16( blob, 253, 254, H, 'qform_code'); blob = setInt16( blob, 255, 256, H, 'sform_code'); blob = setSingle(blob, 257, 260, H, 'quatern_b'); blob = setSingle(blob, 261, 264, H, 'quatern_c'); blob = setSingle(blob, 265, 268, H, 'quatern_d'); blob = setSingle(blob, 269, 272, H, 'quatern_x'); blob = setSingle(blob, 273, 276, H, 'quatern_y'); blob = setSingle(blob, 277, 280, H, 'quatern_z'); blob = setSingle(blob, 281, 296, H, 'srow_x'); blob = setSingle(blob, 297, 312, H, 'srow_y'); blob = setSingle(blob, 313, 328, H, 'srow_z'); blob = setString(blob, 329, 344, H, 'intent_name'); if ~isfield(H,'magic') blob(345:347) = uint8('ni1'); else blob = setString(blob, 345, 347, H, 'magic'); end function blob = setString(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = getfield(H, fieldname); ne = numel(F); mx = endidx - begidx +1; if ne > 0 if ~ischar(F) || ne > mx errmsg = sprintf('Field "data_type" must be a string of maximally %i characters.', mx); error(errmsg); end blob(begidx:(begidx+ne-1)) = uint8(F(:)'); end % set 32-bit integers (check #elements) function blob = setInt32(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = int32(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1) / 4; if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8'); % set 16-bit integers (check #elements) function blob = setInt16(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = int16(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1) / 2; if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+2*ne-1)) = typecast(F(:)', 'uint8'); % just 8-bit integers (check #elements) function blob = setInt8(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = int8(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1); if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+ne-1)) = typecast(F(:)', 'uint8'); % single precision floats function blob = setSingle(blob, begidx, endidx, H, fieldname) if ~isfield(H,fieldname) return end F = single(getfield(H, fieldname)); ne = numel(F); sp = (endidx - begidx +1) / 4; if ne~=sp errmsg = sprintf('Field "data_type" must be an array with exactly %i elements.', sp); error(errmsg); end blob(begidx:(begidx+4*ne-1)) = typecast(F(:)', 'uint8');
github
philippboehmsturm/antx-master
avw_hdr_read.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/avw_hdr_read.m
16,668
utf_8
7cb599cd5b75177fed96189188822304
function [ avw, machine ] = avw_hdr_read(fileprefix, machine, verbose) % avw_hdr_read - read Analyze format data header (*.hdr) % % [ avw, machine ] = avw_hdr_read(fileprefix, [machine], [verbose]) % % fileprefix - string filename (without .hdr); the file name % can be given as a full path or relative to the % current directory. % % machine - a string, see machineformat in fread for details. % The default here is 'ieee-le' but the routine % will automatically switch between little and big % endian to read any such Analyze header. It % reports the appropriate machine format and can % return the machine value. % % avw.hdr - a struct, all fields returned from the header. % For details, find a good description on the web % or see the Analyze File Format pdf in the % mri_toolbox doc folder or read this .m file. % % verbose - the default is to output processing information to the command % window. If verbose = 0, this will not happen. % % This function is called by avw_img_read % % See also avw_hdr_write, avw_hdr_make, avw_view_hdr, avw_view % % $Revision: 7123 $ $Date: 2009/01/14 09:24:45 $ % Licence: GNU GPL, no express or implied warranties % History: 05/2002, [email protected] % The Analyze format and c code below is copyright % (c) Copyright, 1986-1995 % Biomedical Imaging Resource, Mayo Foundation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~exist('verbose','var'), verbose = 1; end if verbose, version = '[$Revision: 7123 $]'; fprintf('\nAVW_HDR_READ [v%s]\n',version(12:16)); tic; end if ~exist('fileprefix','var'), msg = sprintf('...no input fileprefix - see help avw_hdr_read\n\n'); error(msg); end if ~exist('machine','var'), machine = 'ieee-le'; end if findstr('.hdr',fileprefix), % fprintf('...removing .hdr extension from ''%s''\n',fileprefix); fileprefix = strrep(fileprefix,'.hdr',''); end if findstr('.img',fileprefix), % fprintf('...removing .img extension from ''%s''\n',fileprefix); fileprefix = strrep(fileprefix,'.img',''); end file = sprintf('%s.hdr',fileprefix); if exist(file), if verbose, fprintf('...reading %s Analyze format',machine); end fid = fopen(file,'r',machine); avw.hdr = read_header(fid,verbose); avw.fileprefix = fileprefix; fclose(fid); if ~isequal(avw.hdr.hk.sizeof_hdr,348), if verbose, fprintf('...failed.\n'); end % first try reading the opposite endian to 'machine' switch machine, case 'ieee-le', machine = 'ieee-be'; case 'ieee-be', machine = 'ieee-le'; end if verbose, fprintf('...reading %s Analyze format',machine); end fid = fopen(file,'r',machine); avw.hdr = read_header(fid,verbose); avw.fileprefix = fileprefix; fclose(fid); end if ~isequal(avw.hdr.hk.sizeof_hdr,348), % Now throw an error if verbose, fprintf('...failed.\n'); end msg = sprintf('...size of header not equal to 348 bytes!\n\n'); error(msg); end else msg = sprintf('...cannot find file %s.hdr\n\n',file); error(msg); end if verbose, t=toc; fprintf('...done (%5.2f sec).\n',t); end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ dsr ] = read_header(fid,verbose) % Original header structures - ANALYZE 7.5 %struct dsr % { % struct header_key hk; /* 0 + 40 */ % struct image_dimension dime; /* 40 + 108 */ % struct data_history hist; /* 148 + 200 */ % }; /* total= 348 bytes*/ dsr.hk = header_key(fid); dsr.dime = image_dimension(fid,verbose); dsr.hist = data_history(fid); return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [hk] = header_key(fid) % The required elements in the header_key substructure are: % % int sizeof_header Must indicate the byte size of the header file. % int extents Should be 16384, the image file is created as % contiguous with a minimum extent size. % char regular Must be 'r' to indicate that all images and % volumes are the same size. % Original header structures - ANALYZE 7.5 % struct header_key /* header key */ % { /* off + size */ % int sizeof_hdr /* 0 + 4 */ % char data_type[10]; /* 4 + 10 */ % char db_name[18]; /* 14 + 18 */ % int extents; /* 32 + 4 */ % short int session_error; /* 36 + 2 */ % char regular; /* 38 + 1 */ % char hkey_un0; /* 39 + 1 */ % }; /* total=40 bytes */ fseek(fid,0,'bof'); hk.sizeof_hdr = fread(fid, 1,'*int32'); % should be 348! hk.data_type = fread(fid,10,'*char')'; hk.db_name = fread(fid,18,'*char')'; hk.extents = fread(fid, 1,'*int32'); hk.session_error = fread(fid, 1,'*int16'); hk.regular = fread(fid, 1,'*char')'; % might be uint8 hk.hkey_un0 = fread(fid, 1,'*uint8')'; % check if this value was a char zero if hk.hkey_un0 == 48, hk.hkey_un0 = 0; end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ dime ] = image_dimension(fid,verbose) %struct image_dimension % { /* off + size */ % short int dim[8]; /* 0 + 16 */ % /* % dim[0] Number of dimensions in database; usually 4. % dim[1] Image X dimension; number of *pixels* in an image row. % dim[2] Image Y dimension; number of *pixel rows* in slice. % dim[3] Volume Z dimension; number of *slices* in a volume. % dim[4] Time points; number of volumes in database % */ % char vox_units[4]; /* 16 + 4 */ % char cal_units[8]; /* 20 + 8 */ % short int unused1; /* 28 + 2 */ % short int datatype; /* 30 + 2 */ % short int bitpix; /* 32 + 2 */ % short int dim_un0; /* 34 + 2 */ % float pixdim[8]; /* 36 + 32 */ % /* % pixdim[] specifies the voxel dimensions: % pixdim[1] - voxel width, mm % pixdim[2] - voxel height, mm % pixdim[3] - slice thickness, mm % pixdim[4] - volume timing, in msec % ..etc % */ % float vox_offset; /* 68 + 4 */ % float roi_scale; /* 72 + 4 */ % float funused1; /* 76 + 4 */ % float funused2; /* 80 + 4 */ % float cal_max; /* 84 + 4 */ % float cal_min; /* 88 + 4 */ % int compressed; /* 92 + 4 */ % int verified; /* 96 + 4 */ % int glmax; /* 100 + 4 */ % int glmin; /* 104 + 4 */ % }; /* total=108 bytes */ dime.dim = fread(fid,8,'*int16')'; dime.vox_units = fread(fid,4,'*char')'; dime.cal_units = fread(fid,8,'*char')'; dime.unused1 = fread(fid,1,'*int16'); dime.datatype = fread(fid,1,'*int16'); dime.bitpix = fread(fid,1,'*int16'); dime.dim_un0 = fread(fid,1,'*int16'); dime.pixdim = fread(fid,8,'*float')'; dime.vox_offset = fread(fid,1,'*float'); dime.roi_scale = fread(fid,1,'*float'); dime.funused1 = fread(fid,1,'*float'); dime.funused2 = fread(fid,1,'*float'); dime.cal_max = fread(fid,1,'*float'); dime.cal_min = fread(fid,1,'*float'); dime.compressed = fread(fid,1,'*int32'); dime.verified = fread(fid,1,'*int32'); dime.glmax = fread(fid,1,'*int32'); dime.glmin = fread(fid,1,'*int32'); if dime.dim(1) < 4, % Number of dimensions in database; usually 4. if verbose, fprintf('...ensuring 4 dimensions in avw.hdr.dime.dim\n'); end dime.dim(1) = int16(4); end if dime.dim(5) < 1, % Time points; number of volumes in database if verbose, fprintf('...ensuring at least 1 volume in avw.hdr.dime.dim(5)\n'); end dime.dim(5) = int16(1); end return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ hist ] = data_history(fid) % Original header structures - ANALYZE 7.5 %struct data_history % { /* off + size */ % char descrip[80]; /* 0 + 80 */ % char aux_file[24]; /* 80 + 24 */ % char orient; /* 104 + 1 */ % char originator[10]; /* 105 + 10 */ % char generated[10]; /* 115 + 10 */ % char scannum[10]; /* 125 + 10 */ % char patient_id[10]; /* 135 + 10 */ % char exp_date[10]; /* 145 + 10 */ % char exp_time[10]; /* 155 + 10 */ % char hist_un0[3]; /* 165 + 3 */ % int views /* 168 + 4 */ % int vols_added; /* 172 + 4 */ % int start_field; /* 176 + 4 */ % int field_skip; /* 180 + 4 */ % int omax; /* 184 + 4 */ % int omin; /* 188 + 4 */ % int smax; /* 192 + 4 */ % int smin; /* 196 + 4 */ % }; /* total=200 bytes */ hist.descrip = fread(fid,80,'*char')'; hist.aux_file = fread(fid,24,'*char')'; hist.orient = fread(fid, 1,'*uint8'); % see note below on char hist.originator = fread(fid,10,'*char')'; hist.generated = fread(fid,10,'*char')'; hist.scannum = fread(fid,10,'*char')'; hist.patient_id = fread(fid,10,'*char')'; hist.exp_date = fread(fid,10,'*char')'; hist.exp_time = fread(fid,10,'*char')'; hist.hist_un0 = fread(fid, 3,'*char')'; hist.views = fread(fid, 1,'*int32'); hist.vols_added = fread(fid, 1,'*int32'); hist.start_field = fread(fid, 1,'*int32'); hist.field_skip = fread(fid, 1,'*int32'); hist.omax = fread(fid, 1,'*int32'); hist.omin = fread(fid, 1,'*int32'); hist.smax = fread(fid, 1,'*int32'); hist.smin = fread(fid, 1,'*int32'); % check if hist.orient was saved as ascii char value switch hist.orient, case 48, hist.orient = uint8(0); case 49, hist.orient = uint8(1); case 50, hist.orient = uint8(2); case 51, hist.orient = uint8(3); case 52, hist.orient = uint8(4); case 53, hist.orient = uint8(5); end return % Note on using char: % The 'char orient' field in the header is intended to % hold simply an 8-bit unsigned integer value, not the ASCII representation % of the character for that value. A single 'char' byte is often used to % represent an integer value in Analyze if the known value range doesn't % go beyond 0-255 - saves a byte over a short int, which may not mean % much in today's computing environments, but given that this format % has been around since the early 1980's, saving bytes here and there on % older systems was important! In this case, 'char' simply provides the % byte of storage - not an indicator of the format for what is stored in % this byte. Generally speaking, anytime a single 'char' is used, it is % probably meant to hold an 8-bit integer value, whereas if this has % been dimensioned as an array, then it is intended to hold an ASCII % character string, even if that was only a single character. % Denny <[email protected]> % Comments % The header format is flexible and can be extended for new % user-defined data types. The essential structures of the header % are the header_key and the image_dimension. % % The required elements in the header_key substructure are: % % int sizeof_header Must indicate the byte size of the header file. % int extents Should be 16384, the image file is created as % contiguous with a minimum extent size. % char regular Must be 'r' to indicate that all images and % volumes are the same size. % % The image_dimension substructure describes the organization and % size of the images. These elements enable the database to reference % images by volume and slice number. Explanation of each element follows: % % short int dim[ ]; /* Array of the image dimensions */ % % dim[0] Number of dimensions in database; usually 4. % dim[1] Image X dimension; number of pixels in an image row. % dim[2] Image Y dimension; number of pixel rows in slice. % dim[3] Volume Z dimension; number of slices in a volume. % dim[4] Time points; number of volumes in database. % dim[5] Undocumented. % dim[6] Undocumented. % dim[7] Undocumented. % % char vox_units[4] Specifies the spatial units of measure for a voxel. % char cal_units[8] Specifies the name of the calibration unit. % short int unused1 /* Unused */ % short int datatype /* Datatype for this image set */ % /*Acceptable values for datatype are*/ % #define DT_NONE 0 % #define DT_UNKNOWN 0 /*Unknown data type*/ % #define DT_BINARY 1 /*Binary ( 1 bit per voxel)*/ % #define DT_UNSIGNED_CHAR 2 /*Unsigned character ( 8 bits per voxel)*/ % #define DT_SIGNED_SHORT 4 /*Signed short (16 bits per voxel)*/ % #define DT_SIGNED_INT 8 /*Signed integer (32 bits per voxel)*/ % #define DT_FLOAT 16 /*Floating point (32 bits per voxel)*/ % #define DT_COMPLEX 32 /*Complex (64 bits per voxel; 2 floating point numbers)/* % #define DT_DOUBLE 64 /*Double precision (64 bits per voxel)*/ % #define DT_RGB 128 /*A Red-Green-Blue datatype*/ % #define DT_ALL 255 /*Undocumented*/ % % short int bitpix; /* Number of bits per pixel; 1, 8, 16, 32, or 64. */ % short int dim_un0; /* Unused */ % % float pixdim[]; Parallel array to dim[], giving real world measurements in mm and ms. % pixdim[0]; Pixel dimensions? % pixdim[1]; Voxel width in mm. % pixdim[2]; Voxel height in mm. % pixdim[3]; Slice thickness in mm. % pixdim[4]; timeslice in ms (ie, TR in fMRI). % pixdim[5]; Undocumented. % pixdim[6]; Undocumented. % pixdim[7]; Undocumented. % % float vox_offset; Byte offset in the .img file at which voxels start. This value can be % negative to specify that the absolute value is applied for every image % in the file. % % float roi_scale; Specifies the Region Of Interest scale? % float funused1; Undocumented. % float funused2; Undocumented. % % float cal_max; Specifies the upper bound of the range of calibration values. % float cal_min; Specifies the lower bound of the range of calibration values. % % int compressed; Undocumented. % int verified; Undocumented. % % int glmax; The maximum pixel value for the entire database. % int glmin; The minimum pixel value for the entire database. % %
github
philippboehmsturm/antx-master
read_stl.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_stl.m
4,072
utf_8
f8ab163555c079a78445be6bc53cac39
function [pnt, tri, nrm] = read_stl(filename); % READ_STL reads a triangulation from an ascii or binary *.stl file, which % is a file format native to the stereolithography CAD software created by % 3D Systems. % % Use as % [pnt, tri, nrm] = read_stl(filename) % % The format is described at http://en.wikipedia.org/wiki/STL_(file_format) % % See also WRITE_STL % Copyright (C) 2006-2011, Robert Oostenveld % % This file is part of FieldTrip, see http://www.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_stl.m 7123 2012-12-06 21:21:38Z roboos $ fid = fopen(filename, 'rt'); % read a small section to determine whether it is ascii or binary % a binary STL file has an 80 byte asci header, followed by non-printable characters section = fread(fid, 160, 'uint8'); fseek(fid, 0, 'bof'); if printableascii(section) % the first 160 characters are printable ascii, so assume it is an ascii format % solid testsphere % facet normal -0.13 -0.13 -0.98 % outer loop % vertex 1.50000 1.50000 0.00000 % vertex 1.50000 1.11177 0.05111 % vertex 1.11177 1.50000 0.05111 % endloop % endfacet % ... ntri = 0; while ~feof(fid) line = fgetl(fid); ntri = ntri + ~isempty(findstr('facet normal', line)); end fseek(fid, 0, 'bof'); tri = zeros(ntri,3); nrm = zeros(ntri,3); pnt = zeros(ntri*3,3); line = fgetl(fid); name = sscanf(line, 'solid %s'); for i=1:ntri line1 = fgetl(fid); line2 = fgetl(fid); % outer loop line3 = fgetl(fid); line4 = fgetl(fid); line5 = fgetl(fid); line6 = fgetl(fid); % endloop line7 = fgetl(fid); % endfacet i1 = (i-1)*3+1; i2 = (i-1)*3+2; i3 = (i-1)*3+3; tri(i,:) = [i1 i2 i3]; dum = sscanf(strtrim(line1), 'facet normal %f %f %f'); nrm(i,:) = dum(:)'; dum = sscanf(strtrim(line3), 'vertex %f %f %f'); pnt(i1,:) = dum(:)'; dum = sscanf(strtrim(line4), 'vertex %f %f %f'); pnt(i2,:) = dum(:)'; dum = sscanf(strtrim(line5), 'vertex %f %f %f'); pnt(i3,:) = dum(:)'; end else % reopen the file in binary mode, which does not make a difference on % UNIX but it does on windows fclose(fid); fid = fopen(filename, 'rb'); fseek(fid, 80, 'bof'); % skip the ascii header ntri = fread(fid, 1, 'uint32'); tri = zeros(ntri,3); nrm = zeros(ntri,3); pnt = zeros(ntri*3,3); attr = zeros(ntri,1); for i=1:ntri i1 = (i-1)*3+1; i2 = (i-1)*3+2; i3 = (i-1)*3+3; tri(i,:) = [i1 i2 i3]; nrm(i,:) = fread(fid, 3, 'float32'); pnt(i1,:) = fread(fid, 3, 'float32'); pnt(i2,:) = fread(fid, 3, 'float32'); pnt(i3,:) = fread(fid, 3, 'float32'); attr(i) = fread(fid, 1, 'uint16'); % Attribute byte count, don't know what it is end % for each triangle end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function retval = printableascii(num) % Codes 20hex (32dec) to 7Ehex (126dec), known as the printable characters, % represent letters, digits, punctuation marks, and a few miscellaneous % symbols. There are 95 printable characters in total. num = double(num); num(num==double(sprintf('\n'))) = double(sprintf(' ')); num(num==double(sprintf('\r'))) = double(sprintf(' ')); num(num==double(sprintf('\t'))) = double(sprintf(' ')); retval = all(num>=32 & num<=126);
github
philippboehmsturm/antx-master
read_itab_mhd.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_itab_mhd.m
12,499
utf_8
3f00166bb7197b9d65c619cfe0ac954d
function mhd = read_itab_mhd(filename) fid = fopen(filename, 'rb'); % Name of structure mhd.stname = fread(fid, [1 10], 'uint8=>char'); % Header identifier (VP_BIOMAG) mhd.stver = fread(fid, [1 8], 'uint8=>char'); % Header version mhd.stendian = fread(fid, [1 4], 'uint8=>char'); % LE (little endian) or BE (big endian) format % Subject's INFOs mhd.first_name = fread(fid, [1 32], 'uint8=>char'); % Subject's first name mhd.last_name = fread(fid, [1 32], 'uint8=>char'); % Subject's family name mhd.id = fread(fid, [1 32], 'uint8=>char'); % Subject's id mhd.notes = fread(fid, [1 256], 'uint8=>char'); % Notes on measurement % Other subj infos mhd.subj_info.sex = fread(fid, [1 1], 'uint8=>char'); % Sex (M or F) pad = fread(fid, [1 5], 'uint8'); mhd.subj_info.notes = fread(fid, [1 256], 'uint8=>char'); % Notes on subject mhd.subj_info.height = fread(fid, [1 1], 'float'); % Height in cm mhd.subj_info.weight = fread(fid, [1 1], 'float'); % Weight in kg mhd.subj_info.birthday = fread(fid, [1 1], 'int32'); % Birtday (1-31) mhd.subj_info.birthmonth = fread(fid, [1 1], 'int32'); % Birthmonth (1-12) mhd.subj_info.birthyear = fread(fid, [1 1], 'int32'); % Birthyear (1900-2002) % Data acquisition INFOs mhd.time = fread(fid, [1 12], 'uint8=>char'); % time (ascii) mhd.date = fread(fid, [1 16], 'uint8=>char'); % date (ascii) mhd.nchan = fread(fid, [1 1], 'int32'); % total number of channels mhd.nelech = fread(fid, [1 1], 'int32'); % number of electric channels mhd.nelerefch = fread(fid, [1 1], 'int32'); % number of electric reference channels mhd.nmagch = fread(fid, [1 1], 'int32'); % number of magnetic channels mhd.nmagrefch = fread(fid, [1 1], 'int32'); % number of magnetic reference channels mhd.nauxch = fread(fid, [1 1], 'int32'); % number of auxiliary channels mhd.nparamch = fread(fid, [1 1], 'int32'); % number of parameter channels mhd.ndigitch = fread(fid, [1 1], 'int32'); % number of digit channels mhd.nflagch = fread(fid, [1 1], 'int32'); % number of flag channels mhd.data_type = fread(fid, [1 1], 'int32'); % 0 - BE_SHORT (HP-PA, big endian) % 1 - BE_LONG (HP-PA, big endian) % 2 - BE_FLOAT (HP-PA, big endian) % 3 - LE_SHORT (Intel, little endian) % 4 - LE_LONG (Intel, little endian) % 5 - LE_FLOAT (Intel, little endian) % 6 - RTE_A_SHORT (HP-A900, big endian) % 7 - RTE_A_FLOAT (HP-A900, big endian) % 8 - ASCII mhd.smpfq = fread(fid, [1 1], 'single'); % sampling frequency in Hz mhd.hw_low_fr = fread(fid, [1 1], 'single'); % hw data acquisition low pass filter mhd.hw_hig_fr = fread(fid, [1 1], 'single'); % hw data acquisition high pass filter mhd.hw_comb = fread(fid, [1 1], 'int32'); % hw data acquisition 50 Hz filter (1-TRUE) mhd.sw_hig_tc = fread(fid, [1 1], 'single'); % sw data acquisition high pass time constant mhd.compensation= fread(fid, [1 1], 'int32'); % 0 - no compensation 1 - compensation mhd.ntpdata = fread(fid, [1 1], 'int32'); % total number of time points in data mhd.no_segments = fread(fid, [1 1], 'int32'); % Number of segments described in the segment structure % INFOs on different segments for i=1:5 mhd.sgmt(i).start = fread(fid, [1 1], 'int32'); % Starting time point from beginning of data mhd.sgmt(i).ntptot = fread(fid, [1 1], 'int32'); % Total number of time points mhd.sgmt(i).type = fread(fid, [1 1], 'int32'); mhd.sgmt(i).no_samples = fread(fid, [1 1], 'int32'); mhd.sgmt(i).st_sample = fread(fid, [1 1], 'int32'); end mhd.nsmpl = fread(fid, [1 1], 'int32'); % Overall number of samples % INFOs on different samples for i=1:4096 mhd.smpl(i).start = fread(fid, [1 1], 'int32'); % Starting time point from beginning of data mhd.smpl(i).ntptot = fread(fid, [1 1], 'int32'); % Total number of time points mhd.smpl(i).ntppre = fread(fid, [1 1], 'int32'); % Number of points in pretrigger mhd.smpl(i).type = fread(fid, [1 1], 'int32'); mhd.smpl(i).quality = fread(fid, [1 1], 'int32'); end mhd.nrefchan = fread(fid, [1 1], 'int32'); % number of reference channels mhd.ref_ch = fread(fid, [1 640], 'int32'); % reference channel list mhd.ntpref = fread(fid, [1 1], 'int32'); % total number of time points in reference % Header INFOs mhd.raw_header_type = fread(fid, [1 1], 'int32'); % 0 - Unknown header % 2 - rawfile (A900) % 3 - GE runfile header % 31 - ATB runfile header version 1.0 % 41 - IFN runfile header version 1.0 % 51 - BMDSys runfile header version 1.0 mhd.header_type = fread(fid, [1 1], 'int32'); % 0 - Unknown header % 2 - rawfile (A900) % 3 - GE runfile header % 4 - old header % 10 - 256ch normal header % 11 - 256ch master header % 20 - 640ch normal header % 21 - 640ch master header % 31 - ATB runfile header version 1.0 % 41 - IFN runfile header version 1.0 % 51 - BMDSys runfile header version 1.0 mhd.conf_file = fread(fid, [1 64], 'uint8=>char'); % Filename used for data acquisition configuration mhd.header_size = fread(fid, [1 1], 'int32'); % sizeof(header) at the time of file creation mhd.start_reference = fread(fid, [1 1], 'int32'); % start reference mhd.start_data = fread(fid, [1 1], 'int32'); % start data mhd.rawfile = fread(fid, [1 1], 'int32'); % 0 - not a rawfile 1 - rawfile mhd.multiplexed_data = fread(fid, [1 1], 'int32'); % 0 - FALSE 1 - TRUE mhd.isns = fread(fid, [1 1], 'int32'); % sensor code 1 - Single channel % 28 - Original Rome 28 ch. % 29 - .............. % .. - .............. % 45 - Updated Rome 28 ch. (spring 2009) % .. - .............. % .. - .............. % 55 - Original Chieti 55 ch. flat % 153 - Original Chieti 153 ch. helmet % 154 - Chieti 153 ch. helmet from Jan 2002 % Channel's INFOs for i=1:640 mhd.ch(i).type = fread(fid, [1 1], 'uint8'); pad = fread(fid, [1 3], 'uint8'); % type 0 - unknown % 1 - ele % 2 - mag % 4 - ele ref % 8 - mag ref % 16 - aux % 32 - param % 64 - digit % 128 - flag mhd.ch(i).number = fread(fid, [1 1], 'int32'); % number mhd.ch(i).label = fixstr(fread(fid, [1 16], 'uint8=>char')); % label mhd.ch(i).flag = fread(fid, [1 1], 'uint8'); pad = fread(fid, [1 3], 'uint8'); % on/off flag 0 - working channel % 1 - noisy channel % 2 - very noisy channel % 3 - broken channel mhd.ch(i).amvbit = fread(fid, [1 1], 'float'); % calibration from LSB to mV mhd.ch(i).calib = fread(fid, [1 1], 'float'); % calibration from mV to unit mhd.ch(i).unit = fread(fid, [1 6], 'uint8=>char'); % unit label (fT, uV, ...) pad = fread(fid, [1 2], 'uint8'); mhd.ch(i).ncoils = fread(fid, [1 1], 'int32'); % number of coils building up one channel mhd.ch(i).wgt = fread(fid, [1 10], 'float'); % weight of coils % position and orientation of coils for j=1:10 mhd.ch(i).position(j).r_s = fread(fid, [1 3], 'float'); mhd.ch(i).position(j).u_s = fread(fid, [1 3], 'float'); end end % Sensor position INFOs mhd.r_center = fread(fid, [1 3], 'float'); % sensor position in convenient format mhd.u_center = fread(fid, [1 3], 'float'); mhd.th_center = fread(fid, [1 1], 'float'); % sensor orientation as from markers fit mhd.fi_center= fread(fid, [1 1], 'float'); mhd.rotation_angle= fread(fid, [1 1], 'float'); mhd.cosdir = fread(fid, [3 3], 'float'); % for compatibility only mhd.irefsys = fread(fid, [1 1], 'int32'); % reference system 0 - sensor reference system % 1 - Polhemus % 2 - head3 % 3 - MEG % Marker positions for MRI integration mhd.num_markers = fread(fid, [1 1], 'int32'); % Total number of markers mhd.i_coil = fread(fid, [1 64], 'int32'); % Markers to be used to find sensor position mhd.marker = fread(fid, [3 64], 'int32'); % Position of all the markers mhd.best_chi = fread(fid, [1 1], 'float'); % Best chi_square value obtained in finding sensor position mhd.cup_vertex_center = fread(fid, [1 1], 'float'); % dist anc sensor cente vertex (as entered % from keyboard) mhd.cup_fi_center = fread(fid, [1 1], 'float'); % fi angle of sensor center mhd.cup_rotation_angle = fread(fid, [1 1], 'float'); % rotation angle of sensor center axis mhd.dist_a1_a2 = fread(fid, [1 1], 'float'); % head informations % (used to find subject's head dimensions) mhd.dist_inion_nasion = fread(fid, [1 1], 'float'); mhd.max_circ = fread(fid, [1 1], 'float'); mhd.nasion_vertex_inion = fread(fid, [1 1], 'float'); % Data analysis INFOs mhd.security = fread(fid, [1 1], 'int32'); % security flag mhd.ave_alignement = fread(fid, [1 1], 'int32'); % average data alignement 0 - FALSE % 1 - TRUE mhd.itri = fread(fid, [1 1], 'int32'); % trigger channel number mhd.ntpch = fread(fid, [1 1], 'int32'); % no. of time points per channel mhd.ntppre = fread(fid, [1 1], 'int32'); % no. of time points of pretrigger mhd.navrg = fread(fid, [1 1], 'int32'); % no. of averages mhd.nover = fread(fid, [1 1], 'int32'); % no. of discarded averages mhd.nave_filt = fread(fid, [1 1], 'int32'); % no. of applied filters % Filters used before average for i=1:15 mhd.ave_filt(i).type = fread(fid, [1 1], 'int32'); % type 0 - no filter % 1 - bandpass - param[0]: highpass freq % - param[1]: lowpass freq % 2 - notch - param[0]: notch freq 1 % param[1]: notch freq 2 % param[2]: notch freq 3 % param[3]: notch freq 4 % param[4]: span % 3 - artifact - param[0]: True/False % 4 - adaptive - param[0]: True/False % 5 - rectifier - param[0]: True/False % 6 - heart - param[0]: True/False % 7 - evoked - param[0]: True/False % 8 - derivate - param[0]: True/False % 9 - polarity - param[0]: True/False mhd.ave_filt(i).param = fread(fid, [1 5], 'float'); % up to 5 filter parameters end mhd.stdev = fread(fid, [1 1], 'int32'); % 0 - not present mhd.bas_start = fread(fid, [1 1], 'int32'); % starting data points for baseline mhd.bas_end = fread(fid, [1 1], 'int32'); % ending data points for baseline mhd.source_files = fread(fid, [1 32], 'int32'); % Progressive number of files (if more than one) % template INFOs mhd.ichtpl = fread(fid, [1 1], 'int32'); mhd.ntptpl = fread(fid, [1 1], 'int32'); mhd.ifitpl = fread(fid, [1 1], 'int32'); mhd.corlim = fread(fid, [1 1], 'float'); % Filters used before template for i=1:15 mhd.tpl_filt(i).type = fread(fid, [1 1], 'int32'); % type 0 - no filter % 1 - bandpass - param[0]: highpass freq % - param[1]: lowpass freq % 2 - notch - param[0]: notch freq 1 % param[1]: notch freq 2 % param[2]: notch freq 3 % param[3]: notch freq 4 % param[4]: span % 3 - artifact - param[0]: True/False % 4 - adaptive - param[0]: True/False % 5 - rectifier - param[0]: True/False % 6 - heart - param[0]: True/False % 7 - evoked - param[0]: True/False % 8 - derivate - param[0]: True/False % 9 - polarity - param[0]: True/False mhd.tpl_filt(i).param = fread(fid, [1 5], 'float'); % up to 5 filter parameters end % Just in case info mhd.dummy = fread(fid, [1 64], 'int32'); % there seems to be more dummy data at the end... fclose(fid); function str = fixstr(str) sel = find(str==0, 1, 'first'); if ~isempty(sel) str = str(1:sel-1); end
github
philippboehmsturm/antx-master
read_plexon_plx.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_plexon_plx.m
19,936
utf_8
a5f213ea449dd4e5bb51d240302e6364
function [varargout] = read_plexon_plx(filename, varargin) % READ_PLEXON_PLX reads header or data from a Plexon *.plx file, which % is a file containing action-potential (spike) timestamps and waveforms % (spike channels), event timestamps (event channels), and continuous % variable data (continuous A/D channels). % % Use as % [hdr] = read_plexon_plx(filename) % [dat] = read_plexon_plx(filename, ...) % [dat1, dat2, dat3, hdr] = read_plexon_plx(filename, ...) % % Optional input arguments should be specified in key-value pairs % 'header' = structure with header information % 'memmap' = 0 or 1 % 'feedback' = 0 or 1 % 'ChannelIndex' = number, or list of numbers (that will result in multiple outputs) % 'SlowChannelIndex' = number, or list of numbers (that will result in multiple outputs) % Copyright (C) 2007, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_plexon_plx.m 7123 2012-12-06 21:21:38Z roboos $ % parse the optional input arguments hdr = ft_getopt(varargin, 'header'); memmap = ft_getopt(varargin, 'memmap', false); feedback = ft_getopt(varargin, 'feedback', true); ChannelIndex = ft_getopt(varargin, 'ChannelIndex'); SlowChannelIndex = ft_getopt(varargin, 'SlowChannelIndex'); EventIndex = ft_getopt(varargin, 'EventIndex'); % not yet used needhdr = isempty(hdr); % start with empty return values varargout = {}; % the datafile is little endian, hence it may be neccessary to swap bytes in % the memory mapped data stream depending on the CPU type of this computer if littleendian swapFcn = @(x) x; else swapFcn = @(x) swapbytes(x); end % read header info from file, use Matlabs for automatic byte-ordering fid = fopen(filename, 'r', 'ieee-le'); fseek(fid, 0, 'eof'); siz = ftell(fid); fseek(fid, 0, 'bof'); if needhdr if feedback, fprintf('reading header from %s\n', filename); end % a PLX file consists of a file header, channel headers, and data blocks hdr = PL_FileHeader(fid); for i=1:hdr.NumDSPChannels hdr.ChannelHeader(i) = PL_ChannelHeader(fid); end for i=1:hdr.NumEventChannels hdr.EventHeader(i) = PL_EventHeader(fid); end for i=1:hdr.NumSlowChannels hdr.SlowChannelHeader(i) = PL_SlowChannelHeader(fid); end hdr.DataOffset = ftell(fid); if memmap % open the file as meory mapped object, note that byte swapping may be needed mm = memmapfile(filename, 'offset', hdr.DataOffset, 'format', 'int16'); end dum = struct(... 'Type', [],... 'UpperByteOf5ByteTimestamp', [],... 'TimeStamp', [],... 'Channel', [],... 'Unit', [],... 'NumberOfWaveforms', [],... 'NumberOfWordsInWaveform', [] ... ); % read the header of each data block and remember its data offset in bytes Nblocks = 0; offset = hdr.DataOffset; % only used when reading from memmapped file hdr.DataBlockOffset = []; hdr.DataBlockHeader = dum; while offset<siz if Nblocks>=length(hdr.DataBlockOffset); % allocate another 1000 elements, this prevents continuous reallocation hdr.DataBlockOffset(Nblocks+10000) = 0; hdr.DataBlockHeader(Nblocks+10000) = dum; if feedback, fprintf('reading DataBlockHeader %4.1f%%\n', 100*(offset-hdr.DataOffset)/(siz-hdr.DataOffset)); end end Nblocks = Nblocks+1; if memmap % get the header information from the memory mapped file hdr.DataBlockOffset(Nblocks) = offset; hdr.DataBlockHeader(Nblocks) = PL_DataBlockHeader(mm, offset-hdr.DataOffset, swapFcn); % skip the header (16 bytes) and the data (int16 words) offset = offset + 16 + 2 * double(hdr.DataBlockHeader(Nblocks).NumberOfWordsInWaveform * hdr.DataBlockHeader(Nblocks).NumberOfWaveforms); else % read the header information from the file the traditional way hdr.DataBlockOffset(Nblocks) = offset; hdr.DataBlockHeader(Nblocks) = PL_DataBlockHeader(fid, [], swapFcn); fseek(fid, 2 * double(hdr.DataBlockHeader(Nblocks).NumberOfWordsInWaveform * hdr.DataBlockHeader(Nblocks).NumberOfWaveforms), 'cof'); % data consists of short integers offset = ftell(fid); end % if memmap end % this prints the final 100% if feedback, fprintf('reading DataBlockHeader %4.1f%%\n', 100*(offset-hdr.DataOffset)/(siz-hdr.DataOffset)); end % remove the allocated space that was not needed hdr.DataBlockOffset = hdr.DataBlockOffset(1:Nblocks); hdr.DataBlockHeader = hdr.DataBlockHeader(1:Nblocks); end % if needhdr %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the spike channel data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(ChannelIndex) if feedback, fprintf('reading spike data from %s\n', filename); end if memmap % open the file as meory mapped object, note that byte swapping may be needed mm = memmapfile(filename, 'offset', hdr.DataOffset, 'format', 'int16'); end type = [hdr.DataBlockHeader.Type]; chan = [hdr.DataBlockHeader.Channel]; ts = [hdr.DataBlockHeader.TimeStamp]; for i=1:length(ChannelIndex) % determine the data blocks with continuous data belonging to this channel sel = (type==1 & chan==hdr.ChannelHeader(ChannelIndex(i)).Channel); sel = find(sel); if isempty(sel) warning('spike channel %d contains no data', ChannelIndex(i)); varargin{end+1} = []; continue; end % the number of samples can potentially be different in each block num = double([hdr.DataBlockHeader(sel).NumberOfWordsInWaveform]) .* double([hdr.DataBlockHeader(sel).NumberOfWaveforms]); % check whether the number of samples per block makes sense if any(num~=num(1)) error('spike channel blocks with diffent number of samples'); end % allocate memory to hold the data buf = zeros(num(1), length(sel), 'int16'); if memmap % get the header information from the memory mapped file datbeg = double(hdr.DataBlockOffset(sel) - hdr.DataOffset)/2 + 8 + 1; % expressed in 2-byte words, minus the file header, skip the 16 byte block header datend = datbeg + num - 1; for j=1:length(sel) buf(:,j) = mm.Data(datbeg(j):datend(j)); end % optionally swap the bytes to correct for the endianness buf = swapFcn(buf); else % read the data from the file in the traditional way offset = double(hdr.DataBlockOffset(sel)) + 16; % expressed in bytes, skip the 16 byte block header for j=1:length(sel) fseek(fid, offset(j), 'bof'); buf(:,j) = fread(fid, num(j), 'int16'); end end % if memmap % remember the data for this channel varargout{i} = buf; end %for ChannelIndex end % if ChannelIndex %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the continuous channel data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(SlowChannelIndex) if feedback, fprintf('reading continuous data from %s\n', filename); end dat = {}; if memmap % open the file as meory mapped object, note that byte swapping may be needed mm = memmapfile(filename, 'offset', hdr.DataOffset, 'format', 'int16'); end type = [hdr.DataBlockHeader.Type]; chan = [hdr.DataBlockHeader.Channel]; ts = [hdr.DataBlockHeader.TimeStamp]; for i=1:length(SlowChannelIndex) % determine the data blocks with continuous data belonging to this channel sel = (type==5 & chan==hdr.SlowChannelHeader(SlowChannelIndex(i)).Channel); sel = find(sel); if isempty(sel) error(sprintf('Continuous channel %d contains no data', SlowChannelIndex(i))); % warning('Continuous channel %d contains no data', SlowChannelIndex(i)); % varargin{end+1} = []; % continue; end % the number of samples can be different in each block num = double([hdr.DataBlockHeader(sel).NumberOfWordsInWaveform]) .* double([hdr.DataBlockHeader(sel).NumberOfWaveforms]); cumnum = cumsum([0 num]); % allocate memory to hold the data buf = zeros(1, cumnum(end), 'int16'); if memmap % get the header information from the memory mapped file datbeg = double(hdr.DataBlockOffset(sel) - hdr.DataOffset)/2 + 8 + 1; % expressed in 2-byte words, minus the file header, skip the 16 byte block header datend = datbeg + num - 1; for j=1:length(sel) bufbeg = cumnum(j)+1; bufend = cumnum(j+1); % copy the data from the memory mapped file into the continuous buffer buf(bufbeg:bufend) = mm.Data(datbeg(j):datend(j)); end % optionally swap the bytes to correct for the endianness buf = swapFcn(buf); else % read the data from the file in the traditional way offset = double(hdr.DataBlockOffset(sel)) + 16; % expressed in bytes, skip the 16 byte block header for j=1:length(sel) bufbeg = cumnum(j)+1; bufend = cumnum(j+1); % copy the data from the file into the continuous buffer fseek(fid, offset(j), 'bof'); buf(bufbeg:bufend) = fread(fid, num(j), 'int16'); end end % if memmap % remember the data for this channel varargout{i} = buf; end %for SlowChannelIndex end % if SlowChannelIndex %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % read the event channel data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isempty(EventIndex) type = [hdr.DataBlockHeader.Type]; chan = [hdr.DataBlockHeader.Channel]; ts = [hdr.DataBlockHeader.TimeStamp]; for i=1:length(EventIndex) % determine the data blocks with continuous data belonging to this channel sel = (type==0 & chan==hdr.EventHeader(EventIndex(i)).Channel); sel = find(sel); if isempty(sel) warning('event channel %d contains no data', EventIndex(i)); varargin{end+1} = []; continue; end % this still has to be implemented keyboard end % for EventIndex end % if EventIndex fclose(fid); % always return the header as last varargout{end+1} = hdr; return %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTIONS for reading the different header elements %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = PL_FileHeader(fid) hdr.MagicNumber = fread(fid, 1, 'uint32=>uint32'); % = 0x58454c50; hdr.Version = fread(fid, 1, 'int32' ); % Version of the data format; determines which data items are valid hdr.Comment = fread(fid, [1 128], 'uint8=>char' ); % User-supplied comment hdr.ADFrequency = fread(fid, 1, 'int32' ); % Timestamp frequency in hertz hdr.NumDSPChannels = fread(fid, 1, 'int32' ); % Number of DSP channel headers in the file hdr.NumEventChannels = fread(fid, 1, 'int32' ); % Number of Event channel headers in the file hdr.NumSlowChannels = fread(fid, 1, 'int32' ); % Number of A/D channel headers in the file hdr.NumPointsWave = fread(fid, 1, 'int32' ); % Number of data points in waveform hdr.NumPointsPreThr = fread(fid, 1, 'int32' ); % Number of data points before crossing the threshold hdr.Year = fread(fid, 1, 'int32' ); % Time/date when the data was acquired hdr.Month = fread(fid, 1, 'int32' ); hdr.Day = fread(fid, 1, 'int32' ); hdr.Hour = fread(fid, 1, 'int32' ); hdr.Minute = fread(fid, 1, 'int32' ); hdr.Second = fread(fid, 1, 'int32' ); hdr.FastRead = fread(fid, 1, 'int32' ); % reserved hdr.WaveformFreq = fread(fid, 1, 'int32' ); % waveform sampling rate; ADFrequency above is timestamp freq hdr.LastTimestamp = fread(fid, 1, 'double'); % duration of the experimental session, in ticks % The following 6 items are only valid if Version >= 103 hdr.Trodalness = fread(fid, 1, 'char' ); % 1 for single, 2 for stereotrode, 4 for tetrode hdr.DataTrodalness = fread(fid, 1, 'char' ); % trodalness of the data representation hdr.BitsPerSpikeSample = fread(fid, 1, 'char' ); % ADC resolution for spike waveforms in bits (usually 12) hdr.BitsPerSlowSample = fread(fid, 1, 'char' ); % ADC resolution for slow-channel data in bits (usually 12) hdr.SpikeMaxMagnitudeMV = fread(fid, 1, 'uint16'); % the zero-to-peak voltage in mV for spike waveform adc values (usually 3000) hdr.SlowMaxMagnitudeMV = fread(fid, 1, 'uint16'); % the zero-to-peak voltage in mV for slow-channel waveform adc values (usually 5000); Only valid if Version >= 105 (usually either 1000 or 500) % The following item is only valid if Version >= 105 hdr.SpikePreAmpGain = fread(fid, 1, 'uint16'); % so that this part of the header is 256 bytes hdr.Padding = fread(fid, 46, 'char' ); % so that this part of the header is 256 bytes % Counters for the number of timestamps and waveforms in each channel and unit. % Note that these only record the counts for the first 4 units in each channel. % channel numbers are 1-based - array entry at [0] is unused hdr.TSCounts = fread(fid, [5 130], 'int32' ); % number of timestamps[channel][unit] hdr.WFCounts = fread(fid, [5 130], 'int32' ); % number of waveforms[channel][unit] % Starting at index 300, the next array also records the number of samples for the % continuous channels. Note that since EVCounts has only 512 entries, continuous % channels above channel 211 do not have sample counts. hdr.EVCounts = fread(fid, 512, 'int32' ); % number of timestamps[event_number] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = PL_ChannelHeader(fid) hdr.Name = fread(fid, [1 32], 'uint8=>char' ); % Name given to the DSP channel hdr.SIGName = fread(fid, [1 32], 'uint8=>char' ); % Name given to the corresponding SIG channel hdr.Channel = fread(fid, 1, 'int32' ); % DSP channel number, 1-based hdr.WFRate = fread(fid, 1, 'int32' ); % When MAP is doing waveform rate limiting, this is limit w/f per sec divided by 10 hdr.SIG = fread(fid, 1, 'int32' ); % SIG channel associated with this DSP channel 1 - based hdr.Ref = fread(fid, 1, 'int32' ); % SIG channel used as a Reference signal, 1- based hdr.Gain = fread(fid, 1, 'int32' ); % actual gain divided by SpikePreAmpGain. For pre version 105, actual gain divided by 1000. hdr.Filter = fread(fid, 1, 'int32' ); % 0 or 1 hdr.Threshold = fread(fid, 1, 'int32' ); % Threshold for spike detection in a/d values hdr.Method = fread(fid, 1, 'int32' ); % Method used for sorting units, 1 - boxes, 2 - templates hdr.NUnits = fread(fid, 1, 'int32' ); % number of sorted units hdr.Template = fread(fid, [64 5], 'int16' ); % Templates used for template sorting, in a/d values hdr.Fit = fread(fid, 5, 'int32' ); % Template fit hdr.SortWidth = fread(fid, 1, 'int32' ); % how many points to use in template sorting (template only) hdr.Boxes = reshape(fread(fid, 4*2*5, 'int16' ), [4 2 5]); % the boxes used in boxes sorting hdr.SortBeg = fread(fid, 1, 'int32' ); % beginning of the sorting window to use in template sorting (width defined by SortWidth) hdr.Comment = fread(fid, [1 128], 'uint8=>char' ); hdr.Padding = fread(fid, 11, 'int32' ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = PL_EventHeader(fid) hdr.Name = fread(fid, [1 32], 'uint8=>char' ); % name given to this event hdr.Channel = fread(fid, 1, 'int32' ); % event number, 1-based hdr.Comment = fread(fid, [1 128], 'uint8=>char' ); hdr.Padding = fread(fid, 33, 'int32' ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = PL_SlowChannelHeader(fid) hdr.Name = fread(fid, [1 32], 'uint8=>char' ); % name given to this channel hdr.Channel = fread(fid, 1, 'int32' ); % channel number, 0-based hdr.ADFreq = fread(fid, 1, 'int32' ); % digitization frequency hdr.Gain = fread(fid, 1, 'int32' ); % gain at the adc card hdr.Enabled = fread(fid, 1, 'int32' ); % whether this channel is enabled for taking data, 0 or 1 hdr.PreAmpGain = fread(fid, 1, 'int32' ); % gain at the preamp % As of Version 104, this indicates the spike channel (PL_ChannelHeader.Channel) of % a spike channel corresponding to this continuous data channel. % <=0 means no associated spike channel. hdr.SpikeChannel = fread(fid, 1, 'int32' ); hdr.Comment = fread(fid, [1 128], 'uint8=>char' ); hdr.Padding = fread(fid, 28, 'int32' ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function hdr = PL_DataBlockHeader(fid, offset, swapFcn) % % this is the conventional code, it has been replaced by code that works % % with both regular and memmapped files % hdr.Type = fread(fid, 1, 'int16=>int16' ); % Data type; 1=spike, 4=Event, 5=continuous % hdr.UpperByteOf5ByteTimestamp = fread(fid, 1, 'uint16=>uint16' ); % Upper 8 bits of the 40 bit timestamp % hdr.TimeStamp = fread(fid, 1, 'uint32=>uint32' ); % Lower 32 bits of the 40 bit timestamp % hdr.Channel = fread(fid, 1, 'int16=>int16' ); % Channel number % hdr.Unit = fread(fid, 1, 'int16=>int16' ); % Sorted unit number; 0=unsorted % hdr.NumberOfWaveforms = fread(fid, 1, 'int16=>int16' ); % Number of waveforms in the data to folow, usually 0 or 1 % hdr.NumberOfWordsInWaveform = fread(fid, 1, 'int16=>int16' ); % Number of samples per waveform in the data to follow if isa(fid, 'memmapfile') mm = fid; datbeg = offset/2 + 1; % the offset is in bytes (minus the file header), the memory mapped file is indexed in int16 words datend = offset/2 + 8; buf = mm.Data(datbeg:datend); else buf = fread(fid, 8, 'int16=>int16'); end hdr.Type = swapFcn(buf(1)); hdr.UpperByteOf5ByteTimestamp = swapFcn(uint16(buf(2))); hdr.TimeStamp = swapFcn(typecast(buf([3 4]), 'uint32')); hdr.Channel = swapFcn(buf(5)); hdr.Unit = swapFcn(buf(6)); hdr.NumberOfWaveforms = swapFcn(buf(7)); hdr.NumberOfWordsInWaveform = swapFcn(buf(8));
github
philippboehmsturm/antx-master
read_neurosim_evolution.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_neurosim_evolution.m
4,562
utf_8
fef2b6110659fbc86ec755b093316cc2
function [hdr, dat] = read_neurosim_evolution(filename, varargin) % READ_NEUROSIM_EVOLUTION reads the "evolution" file that is written % by Jan van der Eerden's NeuroSim software. When a directory is used % as input, the default filename 'evolution' is read. % % Use as % [hdr, dat] = read_neurosim_evolution(filename, ...) % where additional options should come in key-value pairs and can include % Vonly = 0 or 1, only give the membrane potentials as output % headerOnly = 0 or 1, only read the header information (skip the data), automatically set to 1 if nargout==1 % % See also FT_READ_HEADER, FT_READ_DATA % Copyright (C) 2012 Robert Oostenveld % % This file is part of FieldTrip, see http://www.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_neurosim_evolution.m 7327 2013-01-16 08:26:23Z bargip $ if isdir(filename) filename = fullfile(filename, 'evolution'); end Vonly = ft_getopt(varargin, 'Vonly',0); headerOnly = ft_getopt(varargin, 'headerOnly',0); if nargout<2 % make sure that when only one output is requested the header is returned headerOnly=true; end label = {}; orig = {}; fid = fopen(filename, 'rb'); % read the header line = '#'; ishdr=1; while ishdr==1 % find temporal information if strfind(lower(line),'start time') dum= regexp(line, 'time\s+(\d+.\d+E[+-]\d+)', 'tokens'); hdr.FirstTimeStamp = str2double(dum{1}{1}); end if strfind(lower(line),'time bin') dum= regexp(line, 'bin\s+(\d+.\d+E[+-]\d+)', 'tokens'); dt=str2double(dum{1}{1}); hdr.Fs= 1e3/dt; hdr.TimeStampPerSample=dt; end if strfind(lower(line),'end time') dum= regexp(line, 'time\s+(\d+.\d+E[+-]\d+)', 'tokens'); hdr.LastTimeStamp = str2double(dum{1}{1}); hdr.nSamples=int64((hdr.LastTimeStamp-hdr.FirstTimeStamp)/dt+1); end % parse the content of the line, determine the label for each column colid = sscanf(line, '# column %d:', 1); if ~isempty(colid) label{colid} = [num2str(colid) rmspace(line(find(line==':'):end))]; end offset = ftell(fid); % remember the file pointer position line = fgetl(fid); % get the next line if ~isempty(line) && line(1)~='#' && ~isempty(str2num(line)) % the data starts here, rewind the last line fseek(fid, offset, 'bof'); line = []; ishdr=0; else orig{end+1} = line; end end timelab=find(~cellfun('isempty',regexp(lower(label), 'time', 'match'))); if ~headerOnly % read the complete data dat = fscanf(fid, '%f', [length(label), inf]); hdr.nSamples = length(dat(timelab, :)); %overwrites the value written in the header with the actual number of samples found hdr.LastTimeStamp = dat(1,end); end fclose(fid); % only extract V_membrane if wanted if Vonly matchLab=regexp(label,'V of (\S+) neuron','start'); idx=find(~cellfun(@isempty,matchLab)); if isempty(idx) % most likely a multi compartment simulation matchLab=regexp(label,'V\S+ of (\S+) neuron','start'); idx=find(~cellfun(@isempty,matchLab)); end if ~headerOnly dat=dat([timelab idx],:); end label=label([timelab idx]); for n=2:length(label) % renumbering of the labels label{n}=[num2str(n) label{n}(regexp(label{n},': V'):end)]; end end % convert the header into fieldtrip style hdr.label = label(:); hdr.nChans = length(label); hdr.nSamplesPre = 0; hdr.nTrials = 1; % also store the original ascii header details hdr.orig = orig(:); [hdr.chanunit hdr.chantype] = deal(cell(length(label),1)); hdr.chantype(:) = {'evolution (neurosim)'}; hdr.chanunit(:) = {'unknown'}; function y=rmspace(x) % remove double spaces from string % (c) Bart Gips 2012 y=strtrim(x); [sbeg send]=regexp(y,' \s+'); for n=1:length(sbeg) y(sbeg(n):send(n)-1)=[]; end
github
philippboehmsturm/antx-master
read_eeglabevent.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_eeglabevent.m
4,191
utf_8
67bd5db5f42d6abb30df32d9db8277eb
% read_eeglabevent() - import EEGLAB dataset events % % Usage: % >> event = read_eeglabevent(filename, ...); % % Inputs: % filename - [string] file name % % Optional inputs: % 'header' - FILEIO structure header % % Outputs: % event - FILEIO toolbox event structure % % Author: Arnaud Delorme, SCCN, INC, UCSD, 2008- %123456789012345678901234567890123456789012345678901234567890123456789012 % Copyright (C) 2008 Arnaud Delorme, SCCN, INC, UCSD, [email protected] % % This program is free software; you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation; either version 2 of the License, or % (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA function event = read_eeglabevent(filename, varargin) if nargin < 1 help read_eeglabheader; return; end; hdr = ft_getopt(varargin, 'header'); if isempty(hdr) hdr = read_eeglabheader(filename); end event = []; % these will be the output in FieldTrip format oldevent = hdr.orig.event; % these are in EEGLAB format missingFieldFlag=false; if ~isfield(oldevent,'code') && ~isfield(oldevent,'value') && ~isfield(oldevent,'setname') disp('Warning: No ''value'' field in the events structure.'); missingFieldFlag=true; end; if ~isfield(oldevent,'type') disp('Warning: No ''type'' field in the events structure.'); missingFieldFlag=true; end; if missingFieldFlag if ~isfield(oldevent,'setname') %accommodate Widmann's pop_grandaverage function disp('EEGlab data files should have both a ''value'' field'); disp('to denote the generic type of event, as in ''trigger'', and a ''type'' field'); disp('to denote the nature of this generic event, as in the condition of the experiment.'); disp('Note also that this is the reverse of the FieldTrip convention.'); end; end; for index = 1:length(oldevent) if isfield(oldevent,'code') type = oldevent(index).code; elseif isfield(oldevent,'value') type = oldevent(index).value; else type = 'trigger'; end; % events can have a numeric or a string value if isfield(oldevent,'type') value = oldevent(index).type; else value = 'default'; end; % this is the sample number of the concatenated data to which the event corresponds sample = oldevent(index).latency; % a non-zero offset only applies to trial-events, i.e. in case the data is % segmented and each data segment needs to be represented as event. In % that case the offset corresponds to the baseline duration (times -1). offset = 0; if isfield(oldevent, 'duration') duration = oldevent(index).duration; else duration = 0; end; % add the current event in fieldtrip format event(index).type = type; % this is usually a string, e.g. 'trigger' or 'trial' event(index).value = value; % in case of a trigger, this is the value event(index).sample = sample; % this is the sample in the datafile at which the event happens event(index).offset = offset; % some events should be represented with a shifted time-axix, e.g. a trial with a baseline period event(index).duration = duration; % some events have a duration, such as a trial end; if hdr.nTrials>1 % add the trials to the event structure for i=1:hdr.nTrials event(end+1).type = 'trial'; event(end ).sample = (i-1)*hdr.nSamples + 1; if isfield(oldevent,'setname') && (length(oldevent) == hdr.nTrials) event(end ).value = oldevent(i).setname; %accommodate Widmann's pop_grandaverage function else event(end ).value = []; end; event(end ).offset = -hdr.nSamplesPre; event(end ).duration = hdr.nSamples; end end
github
philippboehmsturm/antx-master
read_bti_ascii.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/read_bti_ascii.m
2,301
utf_8
1a848485b63c5722f7013276c80d4dab
function [file] = read_bti_ascii(filename); % READ_BTI_ASCII reads general data from a BTI configuration file % % The file should be formatted like % Group: % item1 : value1a value1b value1c % item2 : value2a value2b value2c % item3 : value3a value3b value3c % item4 : value4a value4b value4c % % Copyright (C) 2004, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: read_bti_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) | line==-1 | isempty(findstr(line, ':')) continue end % the line is not empty, which means that we have encountered a chunck of information if findstr(line, ':')~=length(line) [item, value] = strtok(line, ':'); value(1) = ' '; % remove the : value = strtrim(value); item = strtrim(item); item(findstr(item, '.')) = '_'; item(findstr(item, ' ')) = '_'; if ischar(item) eval(sprintf('file.%s = ''%s'';', item, value)); else eval(sprintf('file.%s = %s;', item, value)); end else subline = cleanline(fgetl(fid)); error, the rest has not been implemented (yet) end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function line = cleanline(line) if isempty(line) | line==-1 return end comment = findstr(line, '//'); if ~isempty(comment) line(min(comment):end) = ' '; end line = strtrim(line);
github
philippboehmsturm/antx-master
openbdf.m
.m
antx-master/xspm8/external/fieldtrip/fileio/private/openbdf.m
6,812
utf_8
cb49358a2a955b165a5c50127c25e3d8
% openbdf() - Opens an BDF File (European Data Format for Biosignals) in MATLAB (R) % % Usage: % >> EDF=openedf(FILENAME) % % Note: About EDF -> www.biosemi.com/faq/file_format.htm % % Author: Alois Schloegl, 5.Nov.1998 % % See also: readedf() % Copyright (C) 1997-1998 by Alois Schloegl % [email protected] % Ver 2.20 18.Aug.1998 % Ver 2.21 10.Oct.1998 % Ver 2.30 5.Nov.1998 % % For use under Octave define the following function % function s=upper(s); s=toupper(s); end; % V2.12 Warning for missing Header information % V2.20 EDF.AS.* changed % V2.30 EDF.T0 made Y2K compatible until Year 2090 % This program is free software; you can redistribute it and/or % modify it under the terms of the GNU General Public License % as published by the Free Software Foundation; either version 2 % of the License, or (at your option) any later version. % % This program is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with this program; if not, write to the Free Software % Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. % Name changed for bdf files Sept 6,2002 T.S. Lorig % Header updated for EEGLAB format (update web link too) - Arnaud Delorme 14 Oct 2002 function [DAT,H1]=openbdf(FILENAME) SLASH='/'; % defines Seperator for Subdirectories BSLASH=char(92); cname=computer; if cname(1:2)=='PC' SLASH=BSLASH; end; fid=fopen(FILENAME,'r','ieee-le'); if fid<0 fprintf(2,['Error LOADEDF: File ' FILENAME ' not found\n']); return; end; EDF.FILE.FID=fid; EDF.FILE.OPEN = 1; EDF.FileName = FILENAME; PPos=min([max(find(FILENAME=='.')) length(FILENAME)+1]); SPos=max([0 find((FILENAME=='/') | (FILENAME==BSLASH))]); EDF.FILE.Ext = FILENAME(PPos+1:length(FILENAME)); EDF.FILE.Name = FILENAME(SPos+1:PPos-1); if SPos==0 EDF.FILE.Path = pwd; else EDF.FILE.Path = FILENAME(1:SPos-1); end; EDF.FileName = [EDF.FILE.Path SLASH EDF.FILE.Name '.' EDF.FILE.Ext]; H1=char(fread(EDF.FILE.FID,256,'char')'); % EDF.VERSION=H1(1:8); % 8 Byte Versionsnummer %if 0 fprintf(2,'LOADEDF: WARNING Version EDF Format %i',ver); end; EDF.PID = deblank(H1(9:88)); % 80 Byte local patient identification EDF.RID = deblank(H1(89:168)); % 80 Byte local recording identification %EDF.H.StartDate = H1(169:176); % 8 Byte %EDF.H.StartTime = H1(177:184); % 8 Byte EDF.T0=[str2num(H1(168+[7 8])) str2num(H1(168+[4 5])) str2num(H1(168+[1 2])) str2num(H1(168+[9 10])) str2num(H1(168+[12 13])) str2num(H1(168+[15 16])) ]; % Y2K compatibility until year 2090 if EDF.VERSION(1)=='0' if EDF.T0(1) < 91 EDF.T0(1)=2000+EDF.T0(1); else EDF.T0(1)=1900+EDF.T0(1); end; else ; % in a future version, this is hopefully not needed end; EDF.HeadLen = str2num(H1(185:192)); % 8 Byte Length of Header % reserved = H1(193:236); % 44 Byte EDF.NRec = str2num(H1(237:244)); % 8 Byte # of data records EDF.Dur = str2num(H1(245:252)); % 8 Byte # duration of data record in sec EDF.NS = str2num(H1(253:256)); % 8 Byte # of signals EDF.Label = char(fread(EDF.FILE.FID,[16,EDF.NS],'char')'); EDF.Transducer = char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); EDF.PhysDim = char(fread(EDF.FILE.FID,[8,EDF.NS],'char')'); EDF.PhysMin= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.PhysMax= str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); EDF.DigMin = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); % EDF.DigMax = str2num(char(fread(EDF.FILE.FID,[8,EDF.NS],'char')')); % % check validity of DigMin and DigMax if (length(EDF.DigMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Minimum\n'); EDF.DigMin = -(2^15)*ones(EDF.NS,1); end if (length(EDF.DigMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Digital Maximum\n'); EDF.DigMax = (2^15-1)*ones(EDF.NS,1); end if (any(EDF.DigMin >= EDF.DigMax)) fprintf(2,'Warning OPENEDF: Digital Minimum larger than Maximum\n'); end % check validity of PhysMin and PhysMax if (length(EDF.PhysMin) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Minimum\n'); EDF.PhysMin = EDF.DigMin; end if (length(EDF.PhysMax) ~= EDF.NS) fprintf(2,'Warning OPENEDF: Failing Physical Maximum\n'); EDF.PhysMax = EDF.DigMax; end if (any(EDF.PhysMin >= EDF.PhysMax)) fprintf(2,'Warning OPENEDF: Physical Minimum larger than Maximum\n'); EDF.PhysMin = EDF.DigMin; EDF.PhysMax = EDF.DigMax; end EDF.PreFilt= char(fread(EDF.FILE.FID,[80,EDF.NS],'char')'); % tmp = fread(EDF.FILE.FID,[8,EDF.NS],'char')'; % samples per data record EDF.SPR = str2num(char(tmp)); % samples per data record fseek(EDF.FILE.FID,32*EDF.NS,0); EDF.Cal = (EDF.PhysMax-EDF.PhysMin)./ ... (EDF.DigMax-EDF.DigMin); EDF.Off = EDF.PhysMin - EDF.Cal .* EDF.DigMin; tmp = find(EDF.Cal < 0); EDF.Cal(tmp) = ones(size(tmp)); EDF.Off(tmp) = zeros(size(tmp)); EDF.Calib=[EDF.Off';(diag(EDF.Cal))]; %EDF.Calib=sparse(diag([1; EDF.Cal])); %EDF.Calib(1,2:EDF.NS+1)=EDF.Off'; EDF.SampleRate = EDF.SPR / EDF.Dur; EDF.FILE.POS = ftell(EDF.FILE.FID); if EDF.NRec == -1 % unknown record size, determine correct NRec fseek(EDF.FILE.FID, 0, 'eof'); endpos = ftell(EDF.FILE.FID); EDF.NRec = floor((endpos - EDF.FILE.POS) / (sum(EDF.SPR) * 2)); fseek(EDF.FILE.FID, EDF.FILE.POS, 'bof'); H1(237:244)=sprintf('%-8i',EDF.NRec); % write number of records end; EDF.Chan_Select=(EDF.SPR==max(EDF.SPR)); for k=1:EDF.NS if EDF.Chan_Select(k) EDF.ChanTyp(k)='N'; else EDF.ChanTyp(k)=' '; end; if findstr(upper(EDF.Label(k,:)),'ECG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EKG') EDF.ChanTyp(k)='C'; elseif findstr(upper(EDF.Label(k,:)),'EEG') EDF.ChanTyp(k)='E'; elseif findstr(upper(EDF.Label(k,:)),'EOG') EDF.ChanTyp(k)='O'; elseif findstr(upper(EDF.Label(k,:)),'EMG') EDF.ChanTyp(k)='M'; end; end; EDF.AS.spb = sum(EDF.SPR); % Samples per Block bi=[0;cumsum(EDF.SPR)]; idx=[];idx2=[]; for k=1:EDF.NS, idx2=[idx2, (k-1)*max(EDF.SPR)+(1:EDF.SPR(k))]; end; maxspr=max(EDF.SPR); idx3=zeros(EDF.NS*maxspr,1); for k=1:EDF.NS, idx3(maxspr*(k-1)+(1:maxspr))=bi(k)+ceil((1:maxspr)'/maxspr*EDF.SPR(k));end; %EDF.AS.bi=bi; EDF.AS.IDX2=idx2; %EDF.AS.IDX3=idx3; DAT.Head=EDF; DAT.MX.ReRef=1; %DAT.MX=feval('loadxcm',EDF); return;
github
philippboehmsturm/antx-master
ft_trialfun_general.m
.m
antx-master/xspm8/external/fieldtrip/trialfun/ft_trialfun_general.m
13,271
utf_8
0cfa2157a643d65e98d581477165b7b5
function [trl, event] = ft_trialfun_general(cfg) % FT_TRIALFUN_GENERAL determines trials/segments in the data that are % interesting for analysis, using the general event structure returned % by read_event. This function is independent of the dataformat % % The trialdef structure can contain the following specifications % cfg.trialdef.eventtype = 'string' % cfg.trialdef.eventvalue = number, string or list with numbers or strings % cfg.trialdef.prestim = latency in seconds (optional) % cfg.trialdef.poststim = latency in seconds (optional) % % If you want to read all data from a continous file in segments, you can specify % cfg.trialdef.triallength = duration in seconds (can be Inf) % cfg.trialdef.ntrials = number of trials % % If you specify % cfg.trialdef.eventtype = '?' % a list with the events in your datafile will be displayed on screen. % % See also FT_DEFINETRIAL, FT_PREPROCESSING % 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_trialfun_general.m 7123 2012-12-06 21:21:38Z roboos $ % some events do not require the specification a type, pre or poststim period % in that case it is more convenient not to have them, instead of making them empty if isfield(cfg.trialdef, 'eventvalue') && isempty(cfg.trialdef.eventvalue ), cfg.trialdef = rmfield(cfg.trialdef, 'eventvalue' ); end if isfield(cfg.trialdef, 'prestim') && isempty(cfg.trialdef.prestim ), cfg.trialdef = rmfield(cfg.trialdef, 'prestim' ); end if isfield(cfg.trialdef, 'poststim') && isempty(cfg.trialdef.poststim ), cfg.trialdef = rmfield(cfg.trialdef, 'poststim' ); end if isfield(cfg.trialdef, 'triallength') && isempty(cfg.trialdef.triallength ), cfg.trialdef = rmfield(cfg.trialdef, 'triallength'); end if isfield(cfg.trialdef, 'ntrials') && isempty(cfg.trialdef.ntrials ), cfg.trialdef = rmfield(cfg.trialdef, 'ntrials' ); end if isfield(cfg.trialdef, 'triallength') % reading all segments from a continuous file is incompatible with any other option try, cfg.trialdef = rmfield(cfg.trialdef, 'eventvalue'); end try, cfg.trialdef = rmfield(cfg.trialdef, 'prestim' ); end try, cfg.trialdef = rmfield(cfg.trialdef, 'poststim' ); end if ~isfield(cfg.trialdef, 'ntrials') if isinf(cfg.trialdef.triallength) cfg.trialdef.ntrials = 1; else cfg.trialdef.ntrials = inf; end end end % default rejection parameter if ~isfield(cfg, 'eventformat'), cfg.eventformat = []; end if ~isfield(cfg, 'headerformat'), cfg.headerformat = []; end if ~isfield(cfg, 'dataformat'), cfg.dataformat = []; end % read the header, contains the sampling frequency hdr = ft_read_header(cfg.headerfile, 'headerformat', cfg.headerformat); % read the events if isfield(cfg, 'event') fprintf('using the events from the configuration structure\n'); event = cfg.event; else try fprintf('reading the events from ''%s''\n', cfg.headerfile); event = ft_read_event(cfg.headerfile, 'headerformat', cfg.headerformat, 'eventformat', cfg.eventformat, 'dataformat', cfg.dataformat); catch % ensure that it has the correct fields, even if it is empty event = struct('type', {}, 'value', {}, 'sample', {}, 'offset', {}, 'duration', {}); end end % for the following, the trials do not depend on the events in the data if isfield(cfg.trialdef, 'triallength') if isinf(cfg.trialdef.triallength) % make one long trial with the complete continuous data in it trl = [1 hdr.nSamples*hdr.nTrials 0]; elseif isinf(cfg.trialdef.ntrials) % cut the continous data into as many segments as possible nsamples = round(cfg.trialdef.triallength*hdr.Fs); trlbeg = 1:nsamples:(hdr.nSamples*hdr.nTrials - nsamples + 1); trlend = trlbeg + nsamples - 1; offset = zeros(size(trlbeg)); trl = [trlbeg(:) trlend(:) offset(:)]; else % make the pre-specified number of trials nsamples = round(cfg.trialdef.triallength*hdr.Fs); trlbeg = (0:(cfg.trialdef.ntrials-1))*nsamples + 1; trlend = trlbeg + nsamples - 1; offset = zeros(size(trlbeg)); trl = [trlbeg(:) trlend(:) offset(:)]; end return end sel = []; trl = []; val = []; if strcmp(cfg.trialdef.eventtype, '?') % no trials should be added, show event information using subfunction and exit show_event(event); return end if strcmp(cfg.trialdef.eventtype, 'gui') || (isfield(cfg.trialdef, 'eventvalue') && length(cfg.trialdef.eventvalue)==1 && strcmp(cfg.trialdef.eventvalue, 'gui')) cfg.trialdef = select_event(event, cfg.trialdef); usegui = 1; else usegui = 0; end if ~isfield(cfg.trialdef, 'eventvalue') cfg.trialdef.eventvalue = []; elseif ischar(cfg.trialdef.eventvalue) % convert single string into cell-array, otherwise the intersection does not work as intended cfg.trialdef.eventvalue = {cfg.trialdef.eventvalue}; end % select all events of the specified type and with the specified value if ~isempty(cfg.trialdef.eventtype) sel = ismember({event.type}, cfg.trialdef.eventtype); else sel = true(size(event)); end if ~isempty(cfg.trialdef.eventvalue) % this cannot be done robustly in a single line of code if ~iscell(cfg.trialdef.eventvalue) valchar = ischar(cfg.trialdef.eventvalue); valnumeric = isnumeric(cfg.trialdef.eventvalue); else valchar = ischar(cfg.trialdef.eventvalue{1}); valnumeric = isnumeric(cfg.trialdef.eventvalue{1}); end for i=1:numel(event) if (ischar(event(i).value) && valchar) || (isnumeric(event(i).value) && valnumeric) sel(i) = sel(i) & ~isempty(intersect(event(i).value, cfg.trialdef.eventvalue)); end end end % convert from boolean vector into a list of indices sel = find(sel); if usegui % Checks whether offset and duration are defined for all the selected % events and/or prestim/poststim are defined in trialdef. if (any(cellfun('isempty', {event(sel).offset})) || ... any(cellfun('isempty', {event(sel).duration}))) && ... ~(isfield(cfg.trialdef, 'prestim') && isfield(cfg.trialdef, 'poststim')) % If at least some of offset/duration values and prestim/poststim % values are missing tries to ask the user for prestim/poststim answer = inputdlg({'Prestimulus latency (sec)','Poststimulus latency (sec)'}, 'Enter borders'); if isempty(answer) || any(cellfun('isempty', answer)) error('The information in the data and cfg is insufficient to define trials.'); else cfg.trialdef.prestim=str2double(answer{1}); cfg.trialdef.poststim=str2double(answer{2}); if isnan(cfg.trialdef.prestim) || isnan(cfg.trialdef.poststim) error('Illegal input for trial borders'); end end end % if specification is not complete end % if usegui for i=sel % catch empty fields in the event table and interpret them meaningfully if isempty(event(i).offset) % time axis has no offset relative to the event event(i).offset = 0; end if isempty(event(i).duration) % the event does not specify a duration event(i).duration = 0; end % determine where the trial starts with respect to the event if ~isfield(cfg.trialdef, 'prestim') trloff = event(i).offset; trlbeg = event(i).sample; else % override the offset of the event trloff = round(-cfg.trialdef.prestim*hdr.Fs); % also shift the begin sample with the specified amount trlbeg = event(i).sample + trloff; end % determine the number of samples that has to be read (excluding the begin sample) if ~isfield(cfg.trialdef, 'poststim') trldur = max(event(i).duration - 1, 0); else % this will not work if prestim was not defined, the code will then crash trldur = round((cfg.trialdef.poststim+cfg.trialdef.prestim)*hdr.Fs) - 1; end trlend = trlbeg + trldur; % add the beginsample, endsample and offset of this trial to the list % if all samples are in the dataset if trlbeg>0 && trlend<=hdr.nSamples.*hdr.nTrials, trl = [trl; [trlbeg trlend trloff]]; if isnumeric(event(i).value), val = [val; event(i).value]; elseif ischar(event(i).value) && (event(i).value(1)=='S'|| event(i).value(1)=='R') % on brainvision these are called 'S 1' for stimuli or 'R 1' for responses val = [val; str2double(event(i).value(2:end))]; else val = [val; nan]; end end end % append the vector with values if ~isempty(val) && ~all(isnan(val)) trl = [trl val]; end if usegui % This complicated line just computes the trigger times in seconds and % converts them to a cell array of strings to use in the GUI eventstrings = cellfun(@num2str, mat2cell((trl(:, 1)- trl(:, 3))./hdr.Fs , ones(1, size(trl, 1))), 'UniformOutput', 0); % Let us start with handling at least the completely unsegmented case % semi-automatically. The more complicated cases are better left % to the user. if hdr.nTrials==1 selected = find(trl(:,1)>0 & trl(:,2)<=hdr.nSamples); else selected = find(trl(:,1)>0); end indx = select_channel_list(eventstrings, selected , 'Select events'); trl=trl(indx, :); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that shows event table %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function show_event(event) if isempty(event) fprintf('no events were found in the datafile\n'); return end eventtype = unique({event.type}); Neventtype = length(eventtype); if Neventtype==0 fprintf('no events were found in the datafile\n'); else fprintf('the following events were found in the datafile\n'); for i=1:Neventtype sel = find(strcmp(eventtype{i}, {event.type})); try eventvalue = unique({event(sel).value}); % cell-array with string value eventvalue = sprintf('''%s'' ', eventvalue{:}); % translate into a single string catch eventvalue = unique(cell2mat({event(sel).value})); % array with numeric values or empty eventvalue = num2str(eventvalue); % translate into a single string end fprintf('event type: ''%s'' ', eventtype{i}); fprintf('with event values: %s', eventvalue); fprintf('\n'); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION that allows the user to select an event using gui %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function trialdef=select_event(event, trialdef) if isempty(event) fprintf('no events were found in the datafile\n'); return end if strcmp(trialdef.eventtype, 'gui') eventtype = unique({event.type}); else eventtype ={trialdef.eventtype}; end Neventtype = length(eventtype); if Neventtype==0 fprintf('no events were found in the datafile\n'); else % Two lists are built in parallel settings={}; % The list of actual values to be used later strsettings={}; % The list of strings to show in the GUI for i=1:Neventtype sel = find(strcmp(eventtype{i}, {event.type})); emptyval=find(cellfun('isempty', {event(sel).value})); if all(cellfun(@isnumeric, {event(sel).value})) [event(sel(emptyval)).value]=deal(Inf); eventvalue = unique([event(sel).value]); else if ~isempty(strmatch('Inf', {event(sel).value},'exact')) % It's a very unlikely scenario but ... warning('Event value''Inf'' cannot be handled by GUI selection. Mistakes are possible.') end [event(sel(emptyval)).value]=deal('Inf'); eventvalue = unique({event(sel).value}); if ~iscell(eventvalue) eventvalue={eventvalue}; end end for j=1:length(eventvalue) if (ischar(eventvalue(j)) && ~strcmp(eventvalue(j), 'Inf')) || ... (isnumeric(eventvalue(j)) && eventvalue(j)~=Inf) settings=[settings; [eventtype(i), eventvalue(j)]]; else settings=[settings; [eventtype(i), {[]}]]; end if isa(eventvalue, 'numeric') strsettings=[strsettings; {['Type: ' eventtype{i} ' ; Value: ' num2str(eventvalue(j))]}]; else strsettings=[strsettings; {['Type: ' eventtype{i} ' ; Value: ' eventvalue{j}]}]; end end end if isempty(strsettings) fprintf('no events of the selected type were found in the datafile\n'); return end [selection ok]= listdlg('ListString',strsettings, 'SelectionMode', 'single', 'Name', 'Select event', 'ListSize', [300 300]); if ok trialdef.eventtype=settings{selection,1}; trialdef.eventvalue=settings{selection,2}; end end
github
philippboehmsturm/antx-master
ft_trialfun_realtime.m
.m
antx-master/xspm8/external/fieldtrip/trialfun/ft_trialfun_realtime.m
4,591
utf_8
643acf8caae74037ece5c0f0d5ca7057
function trl = ft_trialfun_realtime(cfg) % FT_TRIALFUN_REALTIME can be used to segment a continuous stream of % data in real-time. Trials are defined as [begsample endsample offset % condition] % % The configuration structure can contain the following specifications % cfg.minsample = the last sample number that was already considered (passed from rt_process) % cfg.blocksize = in seconds. In case of events, offset is % wrt the trigger. % cfg.offset = the offset wrt the 0 point. In case of no events, offset is wrt % prevSample. E.g., [-0.9 1] will read 1 second blocks with % 0.9 second overlap % cfg.bufferdata = {'first' 'last'}. If 'last' then only the last block of % interest is read. Otherwise, all well-defined blocks are read (default = 'first') % Copyright (C) 2009, Marcel van Gerven % % This file is part of FieldTrip, see http://www.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_trialfun_realtime.m 7123 2012-12-06 21:21:38Z roboos $ if ~isfield(cfg,'minsample'), cfg.minsample = 0; end if ~isfield(cfg,'blocksize'), cfg.blocksize = 0.1; end if ~isfield(cfg,'offset'), cfg.offset = 0; end if ~isfield(cfg,'bufferdata'), cfg.bufferdata = 'first'; end if ~isfield(cfg,'triggers'), cfg.triggers = []; end % blocksize and offset in terms of samples cfg.blocksize = round(cfg.blocksize * cfg.hdr.Fs); cfg.offset = round(cfg.offset * cfg.hdr.Fs); % retrieve trials of interest if isempty(cfg.event) % asynchronous mode trl = trialfun_asynchronous(cfg); else % synchronous mode trl = trialfun_synchronous(cfg); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function trl = trialfun_asynchronous(cfg) trl = []; prevSample = cfg.minsample; if strcmp(cfg.bufferdata, 'last') % only get last block % begsample starts blocksize samples before the end begsample = cfg.hdr.nSamples*cfg.hdr.nTrials - cfg.blocksize; % begsample should be offset samples away from the previous read if begsample >= (prevSample + cfg.offset) endsample = cfg.hdr.nSamples*cfg.hdr.nTrials; if begsample < endsample && begsample > 0 trl = [begsample endsample 0 nan]; end end else % get all blocks while true % see whether new samples are available newsamples = (cfg.hdr.nSamples*cfg.hdr.nTrials-prevSample); % if newsamples exceeds the offset plus length specified in blocksize if newsamples >= (cfg.offset+cfg.blocksize) % we do not consider samples < 1 begsample = max(1,prevSample+cfg.offset); endsample = max(1,prevSample+cfg.offset+cfg.blocksize); if begsample < endsample && endsample <= cfg.hdr.nSamples*cfg.hdr.nTrials trl = [trl; [begsample endsample 0 nan]]; end prevSample = endsample; else break; end end end end % function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function trl = trialfun_synchronous(cfg) trl = []; % process all events for j=1:length(cfg.event) if isempty(cfg.triggers) curtrig = cfg.event(j).value; else [m1,curtrig] = ismember(cfg.event(j).value,cfg.triggers); end if isempty(curtrig), curtrig = nan; end if isempty(cfg.triggers) || (~isempty(m1) && m1) % catched a trigger of interest % we do not consider samples < 1 begsample = max(1,cfg.event(j).sample + cfg.offset); endsample = max(1,begsample + cfg.blocksize); trl = [trl; [begsample endsample cfg.offset curtrig]]; end end end % function
github
philippboehmsturm/antx-master
select_channel_list.m
.m
antx-master/xspm8/external/fieldtrip/trialfun/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
ft_headmodel_fns.m
.m
antx-master/xspm8/external/fieldtrip/forward/ft_headmodel_fns.m
5,731
utf_8
2a5fde79978f74623faf81f8d9fa4af7
function vol = ft_headmodel_fns(seg, varargin) % FT_HEADMODEL_FNS creates the volume conduction structure to be used % in the FNS forward solver. % % Use as % vol = ft_headmodel_fns(seg, ...) % % Optional input arguments should be specified in key-value pairs and % can include % tissuecond = matrix C [9XN tissue types]; where N is the number of % tissues and a 3x3 tensor conductivity matrix is stored % in each column. % tissue = see fns_contable_write % tissueval = match tissues of segmentation input % transform = 4x4 transformation matrix (default eye(4)) % units = string (default 'cm') % sens = sensor information (for which ft_datatype(sens,'sens')==1) % deepelec = used in the case of deep voxel solution % tolerance = scalar (default 1e-8) % % Standard default values for conductivity matrix C are derived from % Saleheen HI, Ng KT. New finite difference formulations for general % inhomogeneous anisotropic bioelectric problems. IEEE Trans Biomed Eng. % 1997 % % Additional documentation available at: % http://hunghienvn.nmsu.edu/wiki/index.php/FNS % % See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD % Copyright (C) 2011, Cristiano Micheli and Hung Dang % % This file is part of FieldTrip, see http://www.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_headmodel_fns.m 7224 2012-12-18 11:09:44Z johzum $ ft_hastoolbox('fns', 1); % get the optional arguments tissue = ft_getopt(varargin, 'tissue', []); tissueval = ft_getopt(varargin, 'tissueval', []); tissuecond = ft_getopt(varargin, 'tissuecond', []); transform = ft_getopt(varargin, 'transform', eye(4)); units = ft_getopt(varargin, 'units', 'cm'); sens = ft_getopt(varargin, 'sens', []); deepelec = ft_getopt(varargin, 'deepelec', []); % used in the case of deep voxel solution tolerance = ft_getopt(varargin, 'tolerance', 1e-8); if isempty(sens) error('A set of sensors is required') end if ispc error('FNS only works on Linux and OSX') end % check the consistency between tissue values and the segmentation vecval = ismember(tissueval,unique(seg(:))); if any(vecval)==0 warning('Some of the tissue values are not in the segmentation') end % create the files to be written try tmpfolder = pwd; cd(tempdir) [tmp,tname] = fileparts(tempname); segfile = [tname]; [tmp,tname] = fileparts(tempname); confile = [tname '.csv']; [tmp,tname] = fileparts(tempname); elecfile = [tname '.h5']; [tmp,tname] = fileparts(tempname); exefile = [tname '.sh']; [tmp,tname] = fileparts(tempname); datafile = [tname '.h5']; % create a fake mri structure and write the segmentation on disk disp('writing the segmentation file...') if ~ft_hastoolbox('fileio') error('You must have the fileio module to go on') end mri = []; mri.dim = size(seg); mri.transform = eye(4); mri.seg = uint8(seg); cfg = []; cfg.datatype = 'uint8'; cfg.coordsys = 'ctf'; cfg.parameter = 'seg'; cfg.filename = segfile; cfg.filetype = 'analyze'; ft_volumewrite(cfg, mri); % write the cond matrix on disk, load the default cond matrix in case not specified disp('writing the conductivity file...') condmatrix = fns_contable_write('tissue',tissue,'tissueval',tissueval,'tissuecond',tissuecond); csvwrite(confile,condmatrix); % write the positions of the electrodes on disk disp('writing the electrodes file...') pos = warp_apply(inv(transform),sens.chanpos); % in voxel coordinates! % convert pos into int32 datatype. hdf5write(elecfile, '/electrodes/gridlocs', int32(pos)); % Exe file efid = fopen(exefile, 'w'); if ~ispc fprintf(efid,'#!/usr/bin/env bash\n'); fprintf(efid,['elecsfwd1 -img ' segfile ' -electrodes ./' elecfile ' -data ./', ... datafile ' -contable ./' confile ' -TOL ' num2str(tolerance) ' \n']);%2>&1 > /dev/null end fclose(efid); % run the shell instructions dos(sprintf('chmod +x %s', exefile)); dos(['./' exefile]); % FIXME: find a cleverer way to store the huge transfer matrix (vista?) [transfer,status] = fns_read_transfer(datafile); cleaner(segfile,confile,elecfile,exefile,datafile) catch ME disp('The transfer matrix was not written') cleaner(segfile,confile,elecfile,exefile,datafile) cd(tmpfolder) rethrow(ME) end % start with an empty volume conductor vol = []; vol.tissue = tissue; vol.tissueval = tissueval; vol.transform = transform; vol.segdim = size(seg); vol.units = units; vol.type = 'fns'; vol.transfer = transfer; if ~isempty(deepelec) vol.deepelec = deepelec; end function cleaner(segfile,confile,elecfile,exefile,datafile) delete([segfile '.hdr']); delete([segfile '.img']); delete(confile); delete(elecfile); delete(exefile); delete(datafile);
github
philippboehmsturm/antx-master
ft_convert_units.m
.m
antx-master/xspm8/external/fieldtrip/forward/ft_convert_units.m
7,014
utf_8
bd2c535cfe17e9623a258e0cabe01226
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 7336 2013-01-16 15:51:57Z 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/forward/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
ft_headmodel_slab.m
.m
antx-master/xspm8/external/fieldtrip/forward/ft_headmodel_slab.m
3,466
utf_8
757f6a05af6be4410be4b60f68219358
function vol = ft_headmodel_slab(geom1, geom2, Pc, varargin) % FT_HEADMODEL_SLAB creates an EEG volume conduction model that % is described with an infinite conductive slab. You can think % of this as two parallel planes containing a mass of conductive % material (e.g. water) and externally to them a non-conductive material % (e.g. air). % % Use as % vol = ft_headmodel_slab(geom1, geom2, Pc, varargin) % where % geom1.pnt = Nx3 vector specifying N points through which the 'upper' plane is fitted % geom2.pnt = Nx3 vector specifying N points through which the 'lower' plane is fitted % Pc = 1x3 vector specifying the spatial position of a point lying in the conductive slab % (this determines the plane's normal's direction) % % Optional arguments should be specified in key-value pairs and can include % 'sourcemodel' = 'monopole' % 'conductivity' = number , conductivity value of the conductive halfspace (default = 1) % % See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD % Copyright (C) 2012, Donders Centre for Cognitive Neuroimaging, Nijmegen, NL % % This file is part of FieldTrip, see http://www.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_headmodel_slab.m 7123 2012-12-06 21:21:38Z roboos $ model = ft_getopt(varargin, 'sourcemodel', 'monopole'); cond = ft_getopt(varargin, 'conductivity'); if isempty(cond) warning('Conductivity was not specified, using 1'); cond = 1; end % the description of this volume conduction model consists of the % description of the plane, and a point in the void halfspace if isstruct(geom1) && isfield(geom1,'pnt') pnt1 = geom1.pnt; pnt2 = geom2.pnt; elseif size(geom1,2)==3 pnt1 = geom1; pnt2 = geom2; else error('incorrect specification of the geometry'); end % fit a plane to the points [N1,P1] = fit_plane(pnt1); [N2,P2] = fit_plane(pnt2); % checks if Pc is in the conductive part. If not, flip incond = acos(dot(N1,(Pc-P1)./norm(Pc-P1))) > pi/2; if ~incond N1 = -N1; end incond = acos(dot(N2,(Pc-P2)./norm(Pc-P2))) > pi/2; if ~incond N2 = -N2; end vol = []; vol.cond = cond; vol.pnt1 = P1(:)'; % a point that lies on the plane that separates the conductive tissue from the air vol.ori1 = N1(:)'; % a unit vector pointing towards the air vol.ori1 = vol.ori1/norm(vol.ori1); vol.pnt2 = P2(:)'; vol.ori2 = N2(:)'; vol.ori2 = vol.ori2/norm(vol.ori2); if strcmpi(model,'monopole') vol.type = 'slab_monopole'; else error('unknow method') end function [N,P] = fit_plane(X) % Fits a plane through a number of points in 3D cartesian coordinates P = mean(X,1); % the plane is spanned by this point and by a normal vector X = bsxfun(@minus,X,P); [u, s, v] = svd(X, 0); N = v(:,3); % orientation of the plane, can be in either direction
github
philippboehmsturm/antx-master
ft_prepare_vol_sens.m
.m
antx-master/xspm8/external/fieldtrip/forward/ft_prepare_vol_sens.m
23,785
utf_8
48ad68a40571bf206b4973418d72acab
function [vol, sens] = ft_prepare_vol_sens(vol, sens, varargin) % FT_PREPARE_VOL_SENS does some bookkeeping to ensure that the volume % conductor model and the sensor array are ready for subsequent forward % leadfield computations. It takes care of some pre-computations that can % be done efficiently prior to the leadfield calculations. % % Use as % [vol, sens] = ft_prepare_vol_sens(vol, sens, ...) % with input arguments % sens structure with gradiometer or electrode definition % vol structure with volume conductor definition % % The vol structure represents a volume conductor model, its contents % depend on the type of model. The sens structure represents a sensor % array, i.e. EEG electrodes or MEG gradiometers. % % Additional options should be specified in key-value pairs and can be % 'channel' cell-array with strings (default = 'all') % 'order' number, for single shell "Nolte" model (default = 10) % % The detailled behaviour of this function depends on whether the input % consists of EEG or MEG and furthermoree depends on the type of volume % conductor model: % - in case of EEG single and concentric sphere models, the electrodes are % projected onto the skin surface. % - in case of EEG boundary element models, the electrodes are projected on % the surface and a blilinear interpoaltion matrix from vertices to % electrodes is computed. % - in case of MEG and a localspheres model, a local sphere is determined % for each coil in the gradiometer definition. % - in case of MEG with a singleshell Nolte model, the volume conduction % model is initialized % In any case channel selection and reordering will be done. The channel % order returned by this function corresponds to the order in the 'channel' % option, or if not specified, to the order in the input sensor array. % % See also FT_COMPUTE_LEADFIELD, FT_READ_VOL, FT_READ_SENS, FT_TRANSFORM_VOL, % FT_TRANSFORM_SENS % Copyright (C) 2004-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_prepare_vol_sens.m 7181 2012-12-13 16:22:50Z roboos $ % get the optional input arguments % fileformat = ft_getopt(varargin, 'fileformat'); channel = ft_getopt(varargin, 'channel', sens.label); % cell-array with channel labels, default is all order = ft_getopt(varargin, 'order', 10); % order of expansion for Nolte method; 10 should be enough for real applications; in simulations it makes sense to go higher % ensure that the sensor description is up-to-date (Aug 2011) sens = ft_datatype_sens(sens); % ensure that the volume conduction description is up-to-date (Jul 2012) vol = ft_datatype_headmodel(vol); % determine whether the input contains EEG or MEG sensors iseeg = ft_senstype(sens, 'eeg'); ismeg = ft_senstype(sens, 'meg'); % determine the skin compartment if ~isfield(vol, 'skin_surface') if isfield(vol, 'bnd') vol.skin_surface = find_outermost_boundary(vol.bnd); elseif isfield(vol, 'r') && length(vol.r)<=4 [dum, vol.skin_surface] = max(vol.r); end end % determine the inner_skull_surface compartment if ~isfield(vol, 'inner_skull_surface') if isfield(vol, 'bnd') vol.inner_skull_surface = find_innermost_boundary(vol.bnd); elseif isfield(vol, 'r') && length(vol.r)<=4 [dum, vol.inner_skull_surface] = min(vol.r); end end % otherwise the voltype assignment to an empty struct below won't work if isempty(vol) vol = []; end % this makes them easier to recognise sens.type = ft_senstype(sens); vol.type = ft_voltype(vol); if isfield(vol, 'unit') && isfield(sens, 'unit') && ~strcmp(vol.unit, sens.unit) error('inconsistency in the units of the volume conductor and the sensor array'); end switch ft_voltype(vol) case 'simbio' ft_hastoolbox('simbio', 1); case 'openmeeg' ft_hastoolbox('openmeeg', 1); end if ismeg && iseeg % this is something that could be implemented relatively easily error('simultaneous EEG and MEG not yet supported'); elseif ~ismeg && ~iseeg error('the input does not look like EEG, nor like MEG'); elseif ismeg % keep a copy of the original sensor array, this is needed for the MEG localspheres model sens_orig = sens; % always ensure that there is a linear transfer matrix for combining the coils into gradiometers if ~isfield(sens, 'tra'); Nchans = length(sens.label); Ncoils = size(sens.coilpos,1); if Nchans~=Ncoils error('inconsistent number of channels and coils'); end sens.tra = eye(Nchans, Ncoils); end % select the desired channels from the gradiometer array % order them according to the users specification [selchan, selsens] = match_str(channel, sens.label); % first only modify the linear combination of coils into channels try, sens.chantype = sens.chantype(selsens,:); end try, sens.chanunit = sens.chanunit(selsens,:); end sens.chanpos = sens.chanpos(selsens,:); sens.chanori = sens.chanori(selsens,:); sens.label = sens.label(selsens); sens.tra = sens.tra(selsens,:); % subsequently remove the coils that do not contribute to any channel output selcoil = any(sens.tra~=0,1); sens.coilpos = sens.coilpos(selcoil,:); sens.coilori = sens.coilori(selcoil,:); sens.tra = sens.tra(:,selcoil); switch ft_voltype(vol) case {'infinite' 'infinite_monopole'} % nothing to do case 'singlesphere' % nothing to do case 'concentricspheres' % nothing to do case 'neuromag' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if the forward model is computed using the external Neuromag toolbox, % we have to add a selection of the channels so that the channels % in the forward model correspond with those in the data. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [selchan, selsens] = match_str(channel, sens.label); vol.chansel = selsens; case 'localspheres' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % If the volume conduction model consists of multiple spheres then we % have to match the channels in the gradiometer array and the volume % conduction model. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % use the original sensor array instead of the one with a subset of % channels, because we need the complete mapping of coils to channels sens = sens_orig; % remove the coils that do not contribute to any channel output % since these do not have a corresponding sphere selcoil = find(sum(sens.tra,1)~=0); sens.coilpos = sens.coilpos(selcoil,:); sens.coilori = sens.coilori(selcoil,:); sens.tra = sens.tra(:,selcoil); % the initial localspheres volume conductor has a local sphere per % channel, whereas it should have a local sphere for each coil if size(vol.r,1)==size(sens.coilpos,1) && ~isfield(vol, 'label') % it appears that each coil already has a sphere, which suggests % that the volume conductor already has been prepared to match the % sensor array return elseif size(vol.r,1)==size(sens.coilpos,1) && isfield(vol, 'label') if ~isequal(vol.label(:), sens.label(:)) % if only the order is different, it would be possible to reorder them error('the coils in the volume conduction model do not correspond to the sensor array'); else % the coil-specific spheres in the volume conductor should not have a label % because the label is already specified for the coils in the % sensor array vol = rmfield(vol, 'label'); end return end % the CTF way of representing the headmodel is one-sphere-per-channel % whereas the FieldTrip way of doing the forward computation is one-sphere-per-coil Nchans = size(sens.tra,1); Ncoils = size(sens.tra,2); Nspheres = size(vol.label); if isfield(vol, 'orig') % these are present in a CTF *.hdm file singlesphere.o(1,1) = vol.orig.MEG_Sphere.ORIGIN_X; singlesphere.o(1,2) = vol.orig.MEG_Sphere.ORIGIN_Y; singlesphere.o(1,3) = vol.orig.MEG_Sphere.ORIGIN_Z; singlesphere.r = vol.orig.MEG_Sphere.RADIUS; % ensure consistent units singlesphere = ft_convert_units(singlesphere, vol.unit); % determine the channels that do not have a corresponding sphere % and use the globally fitted single sphere for those missing = setdiff(sens.label, vol.label); if ~isempty(missing) warning('using the global fitted single sphere for %d channels that do not have a local sphere', length(missing)); end for i=1:length(missing) vol.label(end+1) = missing(i); vol.r(end+1,:) = singlesphere.r; vol.o(end+1,:) = singlesphere.o; end end localspheres = []; % for each coil in the MEG helmet, determine the corresponding channel and from that the corresponding local sphere for i=1:Ncoils coilindex = find(sens.tra(:,i)~=0); % to which channel does this coil belong if length(coilindex)>1 % this indicates that there are multiple channels to which this coil contributes, % which happens if the sensor array represents a synthetic higher-order gradient. [dum, coilindex] = max(abs(sens.tra(:,i))); end coillabel = sens.label{coilindex}; % what is the label of this channel chanindex = strmatch(coillabel, vol.label, 'exact'); % what is the index of this channel in the list of local spheres localspheres.r(i,:) = vol.r(chanindex); localspheres.o(i,:) = vol.o(chanindex,:); end vol = localspheres; % finally do the selection of channels and coils % order them according to the users specification [selchan, selsens] = match_str(channel, sens.label); % first only modify the linear combination of coils into channels try, sens.chantype = sens.chantype(selsens,:); end try, sens.chanunit = sens.chanunit(selsens,:); end sens.chanpos = sens.chanpos(selsens,:); sens.chanori = sens.chanori(selsens,:); sens.label = sens.label(selsens); sens.tra = sens.tra(selsens,:); % subsequently remove the coils that do not contribute to any sensor output selcoil = find(sum(sens.tra,1)~=0); sens.coilpos = sens.coilpos(selcoil,:); sens.coilori = sens.coilori(selcoil,:); sens.tra = sens.tra(:,selcoil); % make the same selection of coils in the localspheres model vol.r = vol.r(selcoil); vol.o = vol.o(selcoil,:); case 'singleshell' %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if the forward model is computed using the code from Guido Nolte, we % have to initialize the volume model using the gradiometer coil % locations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % compute the surface normals for each vertex point if ~isfield(vol.bnd, 'nrm') fprintf('computing surface normals\n'); vol.bnd.nrm = normals(vol.bnd.pnt, vol.bnd.tri); end % estimate center and radius [center,radius] = fitsphere(vol.bnd.pnt); % initialize the forward calculation (only if gradiometer coils are available) if size(sens.coilpos,1)>0 vol.forwpar = meg_ini([vol.bnd.pnt vol.bnd.nrm], center', order, [sens.coilpos sens.coilori]); end case 'openmeeg' error('MEG not yet supported with openmeeg'); case 'simbio' error('MEG not yet supported with simbio'); otherwise error('unsupported volume conductor model for MEG'); end elseif iseeg % select the desired channels from the electrode array % order them according to the users specification [selchan, selsens] = match_str(channel, sens.label); Nchans = length(sens.label); if isfield(sens, 'tra') % first only modify the linear combination of electrodes into channels sens.chanpos = sens.chanpos(selsens,:); sens.label = sens.label(selsens); sens.tra = sens.tra(selsens,:); % subsequently remove the electrodes that do not contribute to any channel output selelec = any(sens.tra~=0,1); sens.elecpos = sens.elecpos(selelec,:); sens.tra = sens.tra(:,selelec); else % the electrodes and channels are identical sens.chanpos = sens.chanpos(selsens,:); sens.elecpos = sens.elecpos(selsens,:); sens.label = sens.label(selsens); end switch ft_voltype(vol) case {'infinite' 'infinite_monopole'} % nothing to do case {'halfspace', 'halfspace_monopole'} % electrodes' all-to-all distances numel = size(sens.elecpos,1); ref_el = sens.elecpos(1,:); md = dist( (sens.elecpos-repmat(ref_el,[numel 1]))' ); % take the min distance as reference md = min(md(1,2:end)); pnt = sens.elecpos; % scan the electrodes and reposition the ones which are in the % wrong halfspace (projected on the plane)... if not too far away! for i=1:size(pnt,1) P = pnt(i,:); is_in_empty = acos(dot(vol.ori,(P-vol.pnt)./norm(P-vol.pnt))) < pi/2; if is_in_empty dPplane = abs(dot(vol.ori, vol.pnt-P, 2)); if dPplane>md error('Some electrodes are too distant from the plane: consider repositioning them') else % project point on plane Ppr = pointproj(P,[vol.pnt vol.ori]); pnt(i,:) = Ppr; end end end sens.elecpos = pnt; case {'slab_monopole'} % electrodes' all-to-all distances numel = size(sens.elecpos,1); ref_el = sens.elecpos(1,:); md = dist( (sens.elecpos-repmat(ref_el,[numel 1]))' ); % choose min distance between electrodes md = min(md(1,2:end)); pnt = sens.elecpos; % looks for contacts outside the strip which are not too far away % and projects them on the nearest plane for i=1:size(pnt,1) P = pnt(i,:); instrip1 = acos(dot(vol.ori1,(P-vol.pnt1)./norm(P-vol.pnt1))) > pi/2; instrip2 = acos(dot(vol.ori2,(P-vol.pnt2)./norm(P-vol.pnt2))) > pi/2; is_in_empty = ~(instrip1&instrip2); if is_in_empty dPplane1 = abs(dot(vol.ori1, vol.pnt1-P, 2)); dPplane2 = abs(dot(vol.ori2, vol.pnt2-P, 2)); if dPplane1>md && dPplane2>md error('Some electrodes are too distant from the planes: consider repositioning them') elseif dPplane2>dPplane1 % project point on nearest plane Ppr = pointproj(P,[vol.pnt1 vol.ori1]); pnt(i,:) = Ppr; else % project point on nearest plane Ppr = pointproj(P,[vol.pnt2 vol.ori2]); pnt(i,:) = Ppr; end end end sens.elecpos = pnt; case {'singlesphere', 'concentricspheres'} % ensure that the electrodes ly on the skin surface radius = max(vol.r); pnt = sens.elecpos; if isfield(vol, 'o') % shift the the centre of the sphere to the origin pnt(:,1) = pnt(:,1) - vol.o(1); pnt(:,2) = pnt(:,2) - vol.o(2); pnt(:,3) = pnt(:,3) - vol.o(3); end distance = sqrt(sum(pnt.^2,2)); % to the center of the sphere if any((abs(distance-radius)/radius)>0.005) warning('electrodes do not lie on skin surface -> using radial projection') end pnt = pnt * radius ./ [distance distance distance]; if isfield(vol, 'o') % shift the center back to the original location pnt(:,1) = pnt(:,1) + vol.o(1); pnt(:,2) = pnt(:,2) + vol.o(2); pnt(:,3) = pnt(:,3) + vol.o(3); end sens.elecpos = pnt; case {'bem', 'dipoli', 'asa', 'bemcp', 'openmeeg'} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % do postprocessing of volume and electrodes in case of BEM model %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % project the electrodes on the skin and determine the bilinear interpolation matrix if ~isfield(vol, 'tra') % determine boundary corresponding with skin and inner_skull_surface if ~isfield(vol, 'skin_surface') vol.skin_surface = find_outermost_boundary(vol.bnd); fprintf('determining skin compartment (%d)\n', vol.skin_surface); end if ~isfield(vol, 'source') vol.source = find_innermost_boundary(vol.bnd); fprintf('determining source compartment (%d)\n', vol.source); end if size(vol.mat,1)~=size(vol.mat,2) && size(vol.mat,1)==length(sens.elecpos) fprintf('electrode transfer and system matrix were already combined\n'); else fprintf('projecting electrodes on skin surface\n'); % compute linear interpolation from triangle vertices towards electrodes [el, prj] = project_elec(sens.elecpos, vol.bnd(vol.skin_surface).pnt, vol.bnd(vol.skin_surface).tri); tra = transfer_elec(vol.bnd(vol.skin_surface).pnt, vol.bnd(vol.skin_surface).tri, el); % replace the original electrode positions by the projected positions sens.elecpos = prj; if size(vol.mat,1)==size(vol.bnd(vol.skin_surface).pnt,1) % construct the transfer from only the skin vertices towards electrodes interp = tra; else % construct the transfer from all vertices (also inner_skull_surface/outer_skull_surface) towards electrodes interp = []; for i=1:length(vol.bnd) if i==vol.skin_surface interp = [interp, tra]; else interp = [interp, zeros(size(el,1), size(vol.bnd(i).pnt,1))]; end end end % incorporate the linear interpolation matrix and the system matrix into one matrix % this speeds up the subsequent repeated leadfield computations fprintf('combining electrode transfer and system matrix\n'); if strcmp(ft_voltype(vol), 'openmeeg') nb_points_external_surface = size(vol.bnd(vol.skin_surface).pnt,1); vol.mat = vol.mat((end-nb_points_external_surface+1):end,:); vol.mat = interp(:,1:nb_points_external_surface) * vol.mat; else % convert to sparse matrix to speed up the subsequent multiplication interp = sparse(interp); vol.mat = interp * vol.mat; % ensure that the model potential will be average referenced avg = mean(vol.mat, 1); vol.mat = vol.mat - repmat(avg, size(vol.mat,1), 1); end end end case 'fns' if isfield(vol,'bnd') [el, prj] = project_elec(sens.elecpos, vol.bnd.pnt, vol.bnd.tri); sens.tra = transfer_elec(vol.bnd.pnt, vol.bnd.tri, el); % replace the original electrode positions by the projected positions sens.elecpos = prj; end case 'simbio' if isfield(vol,'bnd') [el, prj] = project_elec(sens.elecpos, vol.bnd.pnt, vol.bnd.tri); sens.tra = transfer_elec(vol.bnd.pnt, vol.bnd.tri, el); % replace the original electrode positions by the projected positions sens.elecpos = prj; end vol.transfer = sb_transfer(vol,sens); case 'interpolate' if ~isfield(sens, 'tra') && isequal(sens.chanpos, sens.elecpos) sens.tra = eye(size(sens.chanpos,1)); end if ~isfield(vol.sens, 'tra') && isequal(vol.sens.chanpos, vol.sens.elecpos) vol.sens.tra = eye(size(vol.sens.chanpos,1)); end % the channel positions can be nan, for example for a bipolar montage match = isequal(sens.label, vol.sens.label) & ... isequalwithequalnans(sens.tra, vol.sens.tra) & ... isequal(sens.elecpos, vol.sens.elecpos) & ... isequalwithequalnans(sens.chanpos, vol.sens.chanpos); if match % the input sensor array matches precisely with the forward model % no further interpolation is needed else % interpolate the channels in the forward model to the desired channels filename = tempname; vol = ft_headmodel_interpolate(filename, sens, vol); % update the sensor array with the one from the volume conductor sens = vol.sens; end % if recomputing interpolation % for the leadfield computations the @nifti object is used to map the image data into memory ft_hastoolbox('spm8', 1); for i=1:length(vol.sens.label) % map each of the leadfield files into memory vol.chan{i} = nifti(vol.filename{i}); end otherwise error('unsupported volume conductor model for EEG'); end % FIXME this needs careful thought to ensure that the average referencing which is now done here and there, and that the linear interpolation in case of BEM are all dealt with consistently % % always ensure that there is a linear transfer matrix for % % rereferencing the EEG potential % if ~isfield(sens, 'tra'); % sens.tra = eye(length(sens.label)); % end end % if iseeg or ismeg if isfield(sens, 'tra') if issparse(sens.tra) && size(sens.tra, 1)==1 % this multiplication would result in a sparse leadfield, which is not what we want % the effect can be demonstrated as sparse(1)*rand(1,10), see also http://bugzilla.fcdonders.nl/show_bug.cgi?id=1169#c7 sens.tra = full(sens.tra); elseif ~issparse(sens.tra) && size(sens.tra, 1)>1 % the multiplication of the "sensor" leadfield (electrode or coil) with the tra matrix to get the "channel" leadfield % is faster for most cases if the pre-multiplying weighting matrix is made sparse sens.tra = sparse(sens.tra); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function Ppr = pointproj(P,plane) % projects a point on a plane % plane(1:3) is a point on the plane % plane(4:6) is the ori of the plane Ppr = []; ori = plane(4:6); line = [P ori]; % get indices of line and plane which are parallel par = abs(dot(plane(4:6), line(:,4:6), 2))<1e-14; % difference between origins of plane and line dp = plane(1:3) - line(:, 1:3); % Divide only for non parallel vectors (DL) t = dot(ori(~par,:), dp(~par,:), 2)./dot(ori(~par,:), line(~par,4:6), 2); % compute coord of intersection point Ppr(~par, :) = line(~par,1:3) + repmat(t,1,3).*line(~par,4:6);
github
philippboehmsturm/antx-master
ft_headmodel_halfspace.m
.m
antx-master/xspm8/external/fieldtrip/forward/ft_headmodel_halfspace.m
3,240
utf_8
d78abbad6c8d161643451f71b14c2877
function vol = ft_headmodel_halfspace(geom, Pc, varargin) % FT_HEADMODEL_HALFSPACE creates an EEG volume conduction model that % is described with an infinite conductive halfspace. You can think % of this as a plane with on one side a infinite mass of conductive % material (e.g. water) and on the other side non-conductive material % (e.g. air). % % Use as % vol = ft_headmodel_halfspace(geom, Pc, ...) % where % geom.pnt = Nx3 vector specifying N points through which a plane is fitted % Pc = 1x3 vector specifying the spatial position of a point lying in the conductive halfspace % (this determines the plane normal's direction) % % Additional optional arguments should be specified as key-value pairs and can include % 'sourcemodel' = string, 'monopole' or 'dipole' (default = 'dipole') % 'conductivity' = number, conductivity value of the conductive halfspace (default = 1) % % See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD % Copyright (C) 2012, Donders Centre for Cognitive Neuroimaging, Nijmegen, NL % % This file is part of FieldTrip, see http://www.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_headmodel_halfspace.m 7123 2012-12-06 21:21:38Z roboos $ model = ft_getopt(varargin, 'sourcemodel', 'dipole'); cond = ft_getopt(varargin, 'conductivity'); if isempty(cond) warning('Conductivity was not specified, using 1'); cond = 1; end % the description of this volume conduction model consists of the % description of the plane, and a point in the void halfspace if isstruct(geom) && isfield(geom,'pnt') pnt = geom.pnt; elseif size(geom,2)==3 pnt = geom; else error('incorrect specification of the geometry'); end % fit a plane to the points [N,P] = fit_plane(pnt); % checks if Pc is in the conductive part. If not, flip incond = acos(dot(N,(Pc-P)./norm(Pc-P))) > pi/2; if ~incond N = -N; end vol = []; vol.cond = cond; vol.pnt = P(:)'; % a point that lies on the plane that separates the conductive tissue from the air vol.ori = N(:)'; % a unit vector pointing towards the air vol.ori = vol.ori/norm(vol.ori); if strcmpi(model,'dipole') vol.type = 'halfspace'; elseif strcmpi(model,'monopole') vol.type = 'halfspace_monopole'; else error('unknow method') end function [N,P] = fit_plane(X) % Fits a plane through a number of points in 3D cartesian coordinates P = mean(X,1); % the plane is spanned by this point and by a normal vector X = bsxfun(@minus,X,P); [u, s, v] = svd(X, 0); N = v(:,3); % orientation of the plane, can be in either direction
github
philippboehmsturm/antx-master
ft_headmodel_dipoli.m
.m
antx-master/xspm8/external/fieldtrip/forward/ft_headmodel_dipoli.m
6,816
utf_8
3465b5ee40c407eb1d5678ae6507e8f3
function vol = ft_headmodel_dipoli(geom, varargin) % FT_HEADMODEL_DIPOLI creates a volume conduction model of the head % using the boundary element method (BEM) for EEG. This function takes % as input the triangulated surfaces that describe the boundaries and % returns as output a volume conduction model which can be used to % compute leadfields. % % This implements % Oostendorp TF, van Oosterom A. "Source parameter estimation in % inhomogeneous volume conductors of arbitrary shape." IEEE Trans % Biomed Eng. 1989 Mar;36(3):382-91. % % The implementation of this function uses an external command-line % executable with the name "dipoli" which is provided by Thom Oostendorp. % % Use as % vol = ft_headmodel_dipoli(geom, ...) % % The geom is given as a boundary or a struct-array of boundaries (surfaces) % % Optional input arguments should be specified in key-value pairs and can % include % isolatedsource = string, 'yes' or 'no' % hdmfile = string, filename with BEM headmodel % conductivity = vector, conductivity of each compartment % % See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD % $Id: ft_headmodel_dipoli.m 7310 2013-01-14 15:44:07Z roboos $ ft_hastoolbox('dipoli', 1); % get the optional arguments isolatedsource = ft_getopt(varargin, 'isolatedsource'); conductivity = ft_getopt(varargin, 'conductivity'); if isfield(geom,'bnd') geom = geom.bnd; end % start with an empty volume conductor vol = []; vol.bnd = geom; % determine the number of compartments numboundaries = numel(vol.bnd); % % The following checks can in principle be performed, but are too % % time-consuming. Instead the code here relies on the calling function to % % feed in the correct geometry. % % % % if ~all(surface_closed(vol.bnd)) % % error('...'); % % end % % if any(surface_intersection(vol.bnd)) % % error('...'); % % end % % if any(surface_selfintersection(vol.bnd)) % % error('...'); % % end % % % The following checks should always be done. % vol.bnd = surface_orientation(vol.bnd, 'outwards'); % might have to be inwards % % order = surface_nesting(vol.bnd, 'outsidefirst'); % might have to be insidefirst % vol.bnd = vol.bnd(order); % FIXME also the cond % if isempty(isolatedsource) if numboundaries>1 % the isolated source compartment is by default the most inner one isolatedsource = true; else isolatedsource = false; end else % convert into a boolean isolatedsource = istrue(isolatedsource); end % determine the desired nesting of the compartments order = surface_nesting(vol.bnd, 'outsidefirst'); % rearrange boundaries and conductivities if numel(vol.bnd)>1 fprintf('reordering the boundaries to: '); fprintf('%d ', order); fprintf('\n'); % update the order of the compartments vol.bnd = vol.bnd(order); end if isempty(conductivity) warning('No conductivity is declared, Assuming standard values\n') if numboundaries == 1 conductivity = 1; elseif numboundaries == 3 % skin/skull/brain conductivity = [1 1/80 1] * 0.33; elseif numboundaries == 4 %FIXME: check for better default values here % skin / outer skull / inner skull / brain conductivity = [1 1/80 1 1] * 0.33; else error('Conductivity values are required!') end vol.cond = conductivity; else if numel(conductivity)~=numboundaries error('a conductivity value should be specified for each compartment'); end vol.cond = conductivity(order); end vol.skin_surface = 1; vol.source = numboundaries; % this is now the last one if isolatedsource fprintf('using compartment %d for the isolated source approach\n', vol.source); else fprintf('not using the isolated source approach\n'); end % find the location of the dipoli binary str = which('dipoli.maci'); [p, f, x] = fileparts(str); dipoli = fullfile(p, f); % without the .m extension switch mexext case {'mexmaci' 'mexmaci64'} % apple computer dipoli = [dipoli '.maci']; case {'mexglnx86' 'mexa64'} % linux computer dipoli = [dipoli '.glnx86']; otherwise error('there is no dipoli executable for your platform'); end fprintf('using the executable "%s"\n', dipoli); % write the triangulations to file bndfile = {}; bnddip = vol.bnd; for i=1:numboundaries bndfile{i} = [tempname '.tri']; % checks if normals are inwards oriented otherwise flips them ok = checknormals(bnddip(i)); if ~ok fprintf('flipping normals'' direction\n') bnddip(i).tri = fliplr(bnddip(i).tri); end write_tri(bndfile{i}, bnddip(i).pnt, bnddip(i).tri); end % these will hold the shell script and the inverted system matrix exefile = [tempname '.sh']; amafile = [tempname '.ama']; fid = fopen(exefile, 'w'); fprintf(fid, '#!/bin/sh\n'); fprintf(fid, '\n'); fprintf(fid, '%s -i %s << EOF\n', dipoli, amafile); for i=1:numboundaries if isolatedsource && vol.source==i % the isolated potential approach should be applied using this compartment fprintf(fid, '!%s\n', bndfile{i}); else fprintf(fid, '%s\n', bndfile{i}); end fprintf(fid, '%g\n', vol.cond(i)); end fprintf(fid, '\n'); fprintf(fid, '\n'); fprintf(fid, 'EOF\n'); fclose(fid); % ensure that the temporary shell script can be executed dos(sprintf('chmod +x %s', exefile)); try % execute dipoli and read the resulting file dos(exefile); ama = loadama(amafile); vol = ama2vol(ama); % This is to maintain the vol.bnd convention (outward oriented), whereas % in terms of further calculation it shuold not really matter. % The calculation fo the head model is done with inward normals % (sometimes flipped from the original input). This assures that the % outward oriented mesh is saved outward oriiented in the vol structure for i=1:numel(vol.bnd) isinw = checknormals(vol.bnd(i)); fprintf('flipping the normals outwards, after head matrix calculation\n') if isinw vol.bnd(i).tri = fliplr(vol.bnd(i).tri); end end catch warning('an error ocurred while running dipoli'); disp(lasterr); end % delete the temporary files for i=1:numboundaries delete(bndfile{i}) end delete(amafile); delete(exefile); % remember that it is a dipoli model vol.type = 'dipoli'; function ok = checknormals(bnd) % checks if the normals are inward oriented ok = 0; pnt = bnd.pnt; tri = bnd.tri; % translate to the center org = median(pnt,1); pnt(:,1) = pnt(:,1) - org(1); pnt(:,2) = pnt(:,2) - org(2); pnt(:,3) = pnt(:,3) - org(3); w = sum(solid_angle(pnt, tri)); if w<0 && (abs(w)-4*pi)<1000*eps % FIXME: this method is rigorous only for star shaped surfaces warning('your normals are outwards oriented\n') ok = 0; elseif w>0 && (abs(w)-4*pi)<1000*eps % warning('your normals are inwards oriented\n') ok = 1; else fprintf('attention: your surface probably is irregular!') ok = 1; end
github
philippboehmsturm/antx-master
ft_headmodel_openmeeg.m
.m
antx-master/xspm8/external/fieldtrip/forward/ft_headmodel_openmeeg.m
7,299
utf_8
471a50b0b7a3a9726773a1f15bcfa4f3
function vol = ft_headmodel_openmeeg(geom, varargin) % FT_HEADMODEL_OPENMEEG creates a volume conduction model of the % head using the boundary element method (BEM). This function takes % as input the triangulated surfaces that describe the boundaries and % returns as output a volume conduction model which can be used to % compute leadfields. % % This function implements % Gramfort et al. OpenMEEG: opensource software for quasistatic % bioelectromagnetics. Biomedical engineering online (2010) vol. 9 (1) pp. 45 % http://www.biomedical-engineering-online.com/content/9/1/45 % doi:10.1186/1475-925X-9-45 % and % Kybic et al. Generalized head models for MEG/EEG: boundary element method % beyond nested volumes. Phys. Med. Biol. (2006) vol. 51 pp. 1333-1346 % doi:10.1088/0031-9155/51/5/021 % % The implementation in this function is derived from the the OpenMEEG project % and uses external command-line executables. See http://gforge.inria.fr/projects/openmeeg % and http://gforge.inria.fr/frs/?group_id=435. % % Use as % vol = ft_headmodel_openmeeg(geom, ...) % % Optional input arguments should be specified in key-value pairs and can % include % isolatedsource = string, 'yes' or 'no' % hdmfile = string, filename with BEM headmodel % conductivity = vector, conductivity of each compartment % % See also FT_PREPARE_VOL_SENS, FT_COMPUTE_LEADFIELD %$Id: ft_headmodel_openmeeg.m 7310 2013-01-14 15:44:07Z roboos $ ft_hastoolbox('openmeeg', 1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the first part is largely shared with the dipoli and bemcp implementation %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get the optional arguments isolatedsource = ft_getopt(varargin, 'isolatedsource'); conductivity = ft_getopt(varargin, 'conductivity'); % copy the boundaries from the geometry into the volume conduction model if isfield(geom,'bnd') geom = geom.bnd; end % start with an empty volume conductor vol = []; vol.bnd = geom; % determine the number of compartments numboundaries = length(vol.bnd); if isempty(isolatedsource) if numboundaries>1 % the isolated source compartment is by default the most inner one isolatedsource = true; else isolatedsource = false; end else % convert into a boolean isolatedsource = istrue(isolatedsource); end % determine the desired nesting of the compartments order = surface_nesting(vol.bnd, 'outsidefirst'); % rearrange boundaries and conductivities if numel(vol.bnd)>1 fprintf('reordering the boundaries to: '); fprintf('%d ', order); fprintf('\n'); % update the order of the compartments vol.bnd = vol.bnd(order); end if isempty(conductivity) warning('No conductivity is declared, Assuming standard values\n') if numboundaries == 1 conductivity = 1; elseif numboundaries == 3 % skin/skull/brain conductivity = [1 1/80 1] * 0.33; else error('Conductivity values are required for 2 shells. More than 3 shells not allowed') end vol.cond = conductivity; else if numel(conductivity)~=numboundaries error('a conductivity value should be specified for each compartment'); end vol.cond = conductivity(order); end vol.skin_surface = 1; vol.source = numboundaries; if isolatedsource fprintf('using compartment %d for the isolated source approach\n', vol.source); else fprintf('not using the isolated source approach\n'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this uses an implementation that was contributed by INRIA Odyssee Team %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % show the license once % openmeeg_license % check that the binaries are ok om_checkombin; % store the current path and change folder to the temporary one tmpfolder = cd; bndom = vol.bnd; try cd(tempdir) % write the triangulations to file bndfile = {}; for ii=1:length(bndom) % check if vertices' normals are inward oriented ok = checknormals(bndom(ii)); if ~ok % Flip faces for openmeeg convention (inwards normals) fprintf('flipping normals'' direction\n') bndom(ii).tri = fliplr(bndom(ii).tri); end end for ii=1:length(vol.bnd) [junk,tname] = fileparts(tempname); bndfile{ii} = [tname '.tri']; om_save_tri(bndfile{ii}, bndom(ii).pnt, bndom(ii).tri); end % these will hold the shell script and the inverted system matrix [tmp,tname] = fileparts(tempname); if ~ispc exefile = [tname '.sh']; else exefile = [tname '.bat']; end [tmp,tname] = fileparts(tempname); condfile = [tname '.cond']; [tmp,tname] = fileparts(tempname); geomfile = [tname '.geom']; [tmp,tname] = fileparts(tempname); hmfile = [tname '.bin']; [tmp,tname] = fileparts(tempname); hminvfile = [tname '.bin']; % write conductivity and geometry files om_write_geom(geomfile,bndfile); om_write_cond(condfile,vol.cond); % Exe file efid = fopen(exefile, 'w'); omp_num_threads = feature('numCores'); if ~ispc fprintf(efid,'#!/usr/bin/env bash\n'); fprintf(efid,['export OMP_NUM_THREADS=',num2str(omp_num_threads),'\n']); fprintf(efid,['om_assemble -HM ./' geomfile ' ./' condfile ' ./' hmfile ' 2>&1 > /dev/null\n']); fprintf(efid,['om_minverser ./' hmfile ' ./' hminvfile ' 2>&1 > /dev/null\n']); else fprintf(efid,['om_assemble -HM ./' geomfile ' ./' condfile ' ./' hmfile '\n']); fprintf(efid,['om_minverser ./' hmfile ' ./' hminvfile '\n']); end fclose(efid); if ~ispc dos(sprintf('chmod +x %s', exefile)); end catch cd(tmpfolder) rethrow(lasterror) end try % execute OpenMEEG and read the resulting file if ispc dos([exefile]); else version = om_getgccversion; if version>3 dos(['./' exefile]); else error('non suitable GCC compiler version (must be superior to gcc3)'); end end vol.mat = om_load_sym(hminvfile,'binary'); cleaner(vol,bndfile,condfile,geomfile,hmfile,hminvfile,exefile) cd(tmpfolder) catch warning('an error ocurred while running OpenMEEG'); disp(lasterr); cleaner(vol,bndfile,condfile,geomfile,hmfile,hminvfile,exefile) cd(tmpfolder) end % remember the type of volume conduction model vol.type = 'openmeeg'; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % SUBFUNCTION %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cleaner(vol,bndfile,condfile,geomfile,hmfile,hminvfile,exefile) % delete the temporary files for i=1:length(vol.bnd) delete(bndfile{i}) end delete(condfile); delete(geomfile); delete(hmfile); delete(hminvfile); delete(exefile); function ok = checknormals(bnd) % FIXME: this method is rigorous only for star shaped surfaces ok = 0; pnt = bnd.pnt; tri = bnd.tri; % translate to the center org = mean(pnt,1); pnt(:,1) = pnt(:,1) - org(1); pnt(:,2) = pnt(:,2) - org(2); pnt(:,3) = pnt(:,3) - org(3); w = sum(solid_angle(pnt, tri)); if w<0 && (abs(w)-4*pi)<1000*eps ok = 0; warning('your normals are outwards oriented\n') elseif w>0 && (abs(w)-4*pi)<1000*eps ok = 1; % warning('your normals are inwards oriented') else error('your surface probably is irregular\n') ok = 0; end
github
philippboehmsturm/antx-master
ft_datatype_sens.m
.m
antx-master/xspm8/external/fieldtrip/forward/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
normals.m
.m
antx-master/xspm8/external/fieldtrip/forward/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
meg_ini.m
.m
antx-master/xspm8/external/fieldtrip/forward/private/meg_ini.m
5,605
utf_8
ebfaeafe751fd7aea7baf1049e6865b4
function forwpar=meg_ini(vc,center,order,sens,refs,gradlocs,weights) % initializes MEG-forward calculation % usage: forwpar=meg_ini(vc,center,order,sens,refs,gradlocs,weights); % % input: % vc: Nx6 matrix; N is the number of surface points % the first three numbers in each row are the location % and the second three are the orientation of the surface % normal % center: 3x1 vector denoting the center of volume the conductor % order: desired order of spherical spherical harmonics; % for 'real' realistic volume conductors order=10 is o.k % sens: Mx6 matrix containing sensor location and orientation, % format as for vc % refs: optional argument. If provided, refs contains the location and oriantion % (format as sens) of additional sensors which are subtracted from the original % ones. This makes a gradiometer. One can also do this with the % magnetometer version of this program und do the subtraction outside this program, % but the gradiometer version is faster. % gradlocs, weights: optional two arguments (they must come together!). % gradlocs are the location of additional channels (e.g. to calculate % a higher order gradiometer) and weights. The i.th row in weights contains % the weights to correct if the i.th cannel. These extra fields are added! % (has historical reasons). % % output: % forpwar: structure containing all parameters needed for forward % calculation % note: it is assumed that locations are in cm. % Copyright (C) 2003, Guido Nolte % % This file is part of FieldTrip, see http://www.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: meg_ini.m 7123 2012-12-06 21:21:38Z roboos $ if nargin==4 if order>0; coeff_sens=getcoeffs(sens,vc,center,order); forwpar=struct('device_sens',sens,'coeff_sens',coeff_sens,'center',center,'order',order); else forwpar=struct('device_sens',sens,'center',center,'order',order); end elseif nargin==5 if order>0; coeff_sens=getcoeffs(sens,vc,center,order); coeff_refs=getcoeffs(refs,vc,center,order); forwpar=struct('device_sens',sens,'device_ref',refs,'coeff_sens',coeff_sens,'coeff_ref',coeff_refs,'center',center,'order',order); else forwpar=struct('device_sens',sens,'device_ref',refs,'center',center,'order',order); end elseif nargin==7; if order>0; coeff_sens=getcoeffs(sens,vc,center,order); coeff_refs=getcoeffs(refs,vc,center,order); coeff_weights=getcoeffs(gradlocs,vc,center,order); forwpar=struct('device_sens',sens,'device_ref',refs,'coeff_sens',coeff_sens,... 'coeff_ref',coeff_refs,'center',center,'order',order,... 'device_weights',gradlocs,'coeff_weights',coeff_weights,'weights',weights); else forwpar=struct('device_sens',sens,'device_ref',refs,'center',center,'order',order,... 'device_weights',gradlocs,'weights',weights); end else error('you must provide 4,5 or 7 arguments'); end return function coeffs=getcoeffs(device,vc,center,order) [ndip,ndum]=size(vc); [nchan,ndum]=size(device); x1=vc(:,1:3)-repmat(center',ndip,1); n1=vc(:,4:6); x2=device(:,1:3)-repmat(center',nchan,1); n2=device(:,4:6); scale=10; nbasis=(order+1)^2-1; [bas,gradbas]=legs(x1,n1,order,scale); bt=leadsphere_all(x1',x2',n2'); n1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan); b=dotproduct(n1rep,bt); ctc=gradbas'*gradbas; warning('OFF', 'MATLAB:nearlySingularMatrix'); coeffs=inv(ctc)*gradbas'*b; warning('ON', 'MATLAB:nearlySingularMatrix'); return function field=getfield(source,device,coeffs,center,order) [ndip,ndum]=size(source); [nchan,ndum]=size(device); x1=source(:,1:3)-repmat(center',ndip,1); n1=source(:,4:6); x2=device(:,1:3)-repmat(center',nchan,1); n2=device(:,4:6); %spherical bt=leadsphere_all(x1',x2',n2'); n1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan); b=dotproduct(n1rep,bt); field=b'; %correction if order>0 scale=10; [bas,gradbas]=legs(x1,n1,order,scale); nbasis=(order+1)^2-1; coeffs=coeffs(1:nbasis,:); fcorr=gradbas*coeffs; field=field-fcorr'; end return function out=crossproduct(x,y) % usage: out=testprog(x,y) % testprog calculates the cross-product of vector x and y [n,m,k]=size(x); out=zeros(3,m,k); out(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:); out(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:); out(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:); return; function out=dotproduct(x,y) % usage: out=dotproduct(x,y) % testprog calculates the dotproduct of vector x and y [n,m,k]=size(x); outb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:); out=reshape(outb,m,k); return; function result=norms(x) [n,m,k]=size(x); resultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2); result=reshape(resultb,m,k); return;
github
philippboehmsturm/antx-master
eeg_halfspace_monopole.m
.m
antx-master/xspm8/external/fieldtrip/forward/private/eeg_halfspace_monopole.m
3,531
utf_8
a30cd5fd8a55c538ea729282dd92336a
function [lf] = eeg_halfspace_monopole(rd, elc, vol) % EEG_HALFSPACE_MONOPOLE calculate the halfspace medium leadfield % on positions pnt for a monopole at position rd and conductivity cond % The halfspace solution requires a plane dividing a conductive zone of % conductivity cond, from a non coductive zone (cond = 0) % % [lf] = eeg_halfspace_monopole(rd, elc, cond) % % Implemented from Malmivuo J, Plonsey R, Bioelectromagnetism (1993) % http://www.bem.fi/book/index.htm % Copyright (C) 2011, Cristiano Micheli % % This file is part of FieldTrip, see http://www.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: eeg_halfspace_monopole.m 7123 2012-12-06 21:21:38Z roboos $ siz = size(rd); if any(siz==1) % positions are specified as a single vector Npoles = prod(siz)/3; rd = rd(:)'; % ensure that it is a row vector elseif siz(2)==3 % positions are specified as a Nx3 matrix -> reformat to a single vector Npoles = siz(1); rd = rd'; rd = rd(:)'; % ensure that it is a row vector else error('incorrect specification of dipole locations'); end Nelc = size(elc,1); lf = zeros(Nelc,Npoles); for i=1:Npoles % this is the position of dipole "i" pole1 = rd((1:3) + 3*(i-1)); % distances electrodes - corrent poles r1 = elc - ones(Nelc,1) * pole1; % Method of mirror charges: % Defines the position of mirror charge being symmetric to the plane pole2 = get_mirror_pos(pole1,vol); % distances electrodes - mirror charge r2 = elc - ones(Nelc,1) * pole2; % denominator R1 = (4*pi*vol.cond) * (sum(r1' .^2 ) )'; % denominator, mirror term R2 = -(4*pi*vol.cond) * (sum(r2' .^2 ) )'; % condition of poles falling in the non conductive halfspace invacuum = acos(dot(vol.ori,(pole1-vol.pnt)./norm(pole1-vol.pnt))) < pi/2; if invacuum warning('a pole lies on the vacuum side of the plane'); lf(:,i) = NaN(Nelc,1); elseif any(R1)==0 warning('a pole coincides with one of the electrodes'); lf(:,i) = NaN(Nelc,1); else lf(:,i) = (1 ./ R1) + (1 ./ R2); end end function P2 = get_mirror_pos(P1,vol) % calculates the position of a point symmetric to pnt with respect to a plane P2 = []; % define the plane pnt = vol.pnt; ori = vol.ori; % already normalized if abs(dot(P1-pnt,ori))<eps warning(sprintf ('point %f %f %f lies in the symmetry plane',P1(1),P1(2),P1(3))) P2 = P1; else % define the plane in parametric form % define a non colinear vector vc with respect to the plane normal vc = [1 0 0]; if abs(cross(ori, vc, 2))<eps vc = [0 1 0]; end % define plane's direction vectors v1 = cross(ori, vc, 2); v1 = v1/norm(v1); v2 = cross(pnt, ori, 2); v2 = v2/norm(v2); plane = [pnt v1 v2]; % distance plane-point P1 d = abs(dot(ori, plane(:,1:3)-P1(:,1:3), 2)); % symmetric point P2 = P1 + 2*d*ori; end
github
philippboehmsturm/antx-master
eeg_halfspace_medium_leadfield.m
.m
antx-master/xspm8/external/fieldtrip/forward/private/eeg_halfspace_medium_leadfield.m
3,539
utf_8
1e8b5e9c0f452dc034f74f1a4035efd7
function [lf] = eeg_halfspace_medium_leadfield(rd, elc, vol) % HALFSPACE_MEDIUM_LEADFIELD calculate the halfspace medium leadfield % on positions pnt for a dipole at position rd and conductivity cond % The halfspace solution requires a plane dividing a conductive zone of % conductivity cond, from a non coductive zone (cond = 0) % % [lf] = halfspace_medium_leadfield(rd, elc, cond) % Copyright (C) 2011, Cristiano Micheli and Robert Oostenveld % % This file is part of FieldTrip, see http://www.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: eeg_halfspace_medium_leadfield.m 7123 2012-12-06 21:21:38Z roboos $ siz = size(rd); if any(siz==1) % positions are specified as a single vector Ndipoles = prod(siz)/3; rd = rd(:)'; % ensure that it is a row vector elseif siz(2)==3 % positions are specified as a Nx3 matrix -> reformat to a single vector Ndipoles = siz(1); rd = rd'; rd = rd(:)'; % ensure that it is a row vector else error('incorrect specification of dipole locations'); end Nelc = size(elc,1); lf = zeros(Nelc,3*Ndipoles); for i=1:Ndipoles % this is the position of dipole "i" dip1 = rd((1:3) + 3*(i-1)); % distances electrodes - dipole r1 = elc - ones(Nelc,1) * dip1; % Method of mirror dipoles: % Defines the position of mirror dipoles being symmetric to the plane dip2 = get_mirror_pos(dip1,vol); % distances electrodes - mirror dipole r2 = elc - ones(Nelc,1) * dip2; % denominator R1 = (4*pi*vol.cond) * (sum(r1' .^2 ) .^ 1.5)'; % denominator, mirror term R2 = -(4*pi*vol.cond) * (sum(r2' .^2 ) .^ 1.5)'; % condition of dipoles falling in the non conductive halfspace invacuum = acos(dot(vol.ori,(dip1-vol.pnt)./norm(dip1-vol.pnt))) < pi/2; if invacuum warning('dipole lies on the vacuum side of the plane'); lf(:,(1:3) + 3*(i-1)) = NaN(Nelc,3); elseif any(R1)==0 warning('dipole coincides with one of the electrodes'); lf(:,(1:3) + 3*(i-1)) = NaN(Nelc,3); else lf(:,(1:3) + 3*(i-1)) = (r1 ./ [R1 R1 R1]) + (r2 ./ [R2 R2 R2]); end end function P2 = get_mirror_pos(P1,vol) % calculates the position of a point symmetric to pnt with respect to a plane P2 = []; % define the plane pnt = vol.pnt; ori = vol.ori; % already normalized if abs(dot(P1-pnt,ori))<eps warning(sprintf ('point %f %f %f lies in the symmetry plane',P1(1),P1(2),P1(3))) P2 = P1; else % define the plane in parametric form % define a non colinear vector vc with respect to the plane normal vc = [1 0 0]; if abs(cross(ori, vc, 2))<eps vc = [0 1 0]; end % define plane's direction vectors v1 = cross(ori, vc, 2); v1 = v1/norm(v1); v2 = cross(pnt, ori, 2); v2 = v2/norm(v2); plane = [pnt v1 v2]; % distance plane-point P1 d = abs(dot(ori, plane(:,1:3)-P1(:,1:3), 2)); % symmetric point P2 = P1 + 2*d*ori; end
github
philippboehmsturm/antx-master
warning_once.m
.m
antx-master/xspm8/external/fieldtrip/forward/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
leadsphere_all.m
.m
antx-master/xspm8/external/fieldtrip/forward/private/leadsphere_all.m
2,351
utf_8
8a0c7658993d13ebbeafaa335b06386a
function out=leadsphere_chans(xloc,sensorloc,sensorori) % usage: out=leadsphere_chans(xloc,sensorloc,sensorori) % Copyright (C) 2003, Guido Nolte % % This file is part of FieldTrip, see http://www.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: leadsphere_all.m 7123 2012-12-06 21:21:38Z roboos $ [n,nsens]=size(sensorloc); %n=3 m=? [n,ndip]=size(xloc); xlocrep=reshape(repmat(xloc,1,nsens),3,ndip,nsens); sensorlocrep=reshape(repmat(sensorloc,ndip,1),3,ndip,nsens); sensororirep=reshape(repmat(sensorori,ndip,1),3,ndip,nsens); r2=norms(sensorlocrep); veca=sensorlocrep-xlocrep; a=norms(veca); adotr2=dotproduct(veca,sensorlocrep); gradf1=scal2vec(1./r2.*(a.^2)+adotr2./a+2*a+2*r2); gradf2=scal2vec(a+2*r2+adotr2./a); gradf=gradf1.*sensorlocrep-gradf2.*xlocrep; F=a.*(r2.*a+adotr2); A1=scal2vec(1./F); A2=A1.^2; A3=crossproduct(xlocrep,sensororirep); A4=scal2vec(dotproduct(gradf,sensororirep)); A5=crossproduct(xlocrep,sensorlocrep); out=1e-7*(A3.*A1-(A4.*A2).*A5); %%GRB change return; function out=crossproduct(x,y) [n,m,k]=size(x); out=zeros(3,m,k); out(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:); out(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:); out(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:); return; function out=dotproduct(x,y) [n,m,k]=size(x); outb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:); out=reshape(outb,m,k); return; function result=norms(x) [n,m,k]=size(x); resultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2); result=reshape(resultb,m,k); return; function result=scal2vec(x) [m,k]=size(x); % result=zeros(3,m,k); % for i=1:3 % result(i,:,:)=x; % end result=reshape(repmat(x(:)', [3 1]), [3 m k]); return
github
philippboehmsturm/antx-master
ft_hastoolbox.m
.m
antx-master/xspm8/external/fieldtrip/forward/private/ft_hastoolbox.m
21,701
utf_8
7141791b922e3b46334b4d5888532adf
function [status] = ft_hastoolbox(toolbox, autoadd, silent) % FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally % it will try to determine the path to the toolbox and install it % automatically. % % Use as % [status] = ft_hastoolbox(toolbox, autoadd, silent) % % autoadd = 0 means that it will not be added % autoadd = 1 means that give an error if it cannot be added % autoadd = 2 means that give a warning if it cannot be added % autoadd = 3 means that it remains silent if it cannot be added % % silent = 0 means that it will give some feedback about adding the toolbox % silent = 1 means that it will not give feedback % Copyright (C) 2005-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_hastoolbox.m 7172 2012-12-13 11:50:49Z roboos $ % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before % persistent previous previouspath % % if ~isequal(previouspath, path) % previous = []; % end % % if isempty(previous) % previous = struct; % elseif isfield(previous, fixname(toolbox)) % status = previous.(fixname(toolbox)); % return % end % this points the user to the website where he/she can download the toolbox url = { 'AFNI' 'see http://afni.nimh.nih.gov' 'DSS' 'see http://www.cis.hut.fi/projects/dss' 'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab' 'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox' 'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm' 'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd' 'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com' 'BIOSIG' 'see http://biosig.sourceforge.net' 'EEG' 'see http://eeg.sourceforge.net' 'EEGSF' 'see http://eeg.sourceforge.net' % alternative name 'MRI' 'see http://eeg.sourceforge.net' % alternative name 'NEUROSHARE' 'see http://www.neuroshare.org' 'BESA' 'see http://www.megis.de, or contact Karsten Hoechstetter' 'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde' 'YOKOGAWA' 'this is deprecated, please use YOKOGAWA_MEG_READER instead' 'YOKOGAWA_MEG_READER' 'see http://www.yokogawa.com/me/me-login-en.htm' 'BEOWULF' 'see http://robertoostenveld.nl, or contact Robert Oostenveld' 'MENTAT' 'see http://robertoostenveld.nl, or contact Robert Oostenveld' 'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth' '4D-VERSION' 'contact Christian Wienbruch' 'SIGNAL' 'see http://www.mathworks.com/products/signal' 'OPTIM' 'see http://www.mathworks.com/products/optim' 'IMAGE' 'see http://www.mathworks.com/products/image' % Mathworks refers to this as IMAGES 'SPLINES' 'see http://www.mathworks.com/products/splines' 'DISTCOMP' 'see http://www.mathworks.nl/products/parallel-computing/' 'COMPILER' 'see http://www.mathworks.com/products/compiler' 'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica' 'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm' 'FILEIO' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PREPROC' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'FORWARD' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'INVERSE' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'SPECEST' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'REALTIME' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'SPIKE' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'CONNECTIVITY' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PEER' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne' 'BCI2000' 'see http://bci2000.org' 'NLXNETCOM' 'see http://www.neuralynx.com' 'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external' 'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php' 'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydesaeter' 'BEMCP' 'contact Christophe Phillips' 'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435' 'PRTOOLS' 'see http://www.prtools.org' 'ITAB' 'contact Stefania Della Penna' 'BSMART' 'see http://www.brain-smart.org' 'PEER' 'see http://fieldtrip.fcdonders.nl/development/peer' 'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki' 'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page' 'VGRID' 'see http://www.rheinahrcampus.de/~medsim/vgrid/manual.html' 'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS' 'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti' 'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0' 'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab' 'BCT' 'see http://www.brain-connectivity-toolbox.net/' 'CCA' 'see http://www.imt.liu.se/~magnus/cca or contact Magnus Borga' 'EGI_MFF' 'see http://www.egi.com/ or contact either Phan Luu or Colin Davey at EGI' 'TOOLBOX_GRAPH' 'see http://www.mathworks.com/matlabcentral/fileexchange/5355-toolbox-graph or contact Gabriel Peyre' 'NETCDF' 'see http://www.mathworks.com/matlabcentral/fileexchange/15177' 'MYSQL' 'see http://www.mathworks.com/matlabcentral/fileexchange/8663-mysql-database-connector' 'ISO2MESH' 'see http://iso2mesh.sourceforge.net/cgi-bin/index.cgi?Home or contact Qianqian Fang' 'DATAHASH' 'see http://www.mathworks.com/matlabcentral/fileexchange/31272' 'IBTB' 'see http://www.ibtb.org' 'ICASSO' 'see http://www.cis.hut.fi/projects/ica/icasso' 'XUNIT' 'see http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework' 'PLEXON' 'available from http://www.plexon.com/assets/downloads/sdk/ReadingPLXandDDTfilesinMatlab-mexw.zip' }; if nargin<2 % default is not to add the path automatically autoadd = 0; end if nargin<3 % default is not to be silent silent = 0; end % determine whether the toolbox is installed toolbox = upper(toolbox); % set fieldtrip trunk path, used for determining ft-subdirs are on path fttrunkpath = unixpath(fileparts(which('ft_defaults'))); switch toolbox case 'AFNI' status = (exist('BrikLoad') && exist('BrikInfo')); case 'DSS' status = exist('denss', 'file') && exist('dss_create_state', 'file'); case 'EEGLAB' status = exist('runica', 'file'); case 'NWAY' status = exist('parafac', 'file'); case 'SPM' status = exist('spm.m'); % any version of SPM is fine case 'SPM99' status = exist('spm.m') && strcmp(spm('ver'),'SPM99'); case 'SPM2' status = exist('spm.m') && strcmp(spm('ver'),'SPM2'); case 'SPM5' status = exist('spm.m') && strcmp(spm('ver'),'SPM5'); case 'SPM8' status = exist('spm.m') && strncmp(spm('ver'),'SPM8', 4); case 'SPM12' status = exist('spm.m') && strncmp(spm('ver'),'SPM12', 5); case 'MEG-PD' status = (exist('rawdata') && exist('channames')); case 'MEG-CALC' status = (exist('megmodel') && exist('megfield') && exist('megtrans')); case 'BIOSIG' status = (exist('sopen') && exist('sread')); case 'EEG' status = (exist('ctf_read_res4') && exist('ctf_read_meg4')); case 'EEGSF' % alternative name status = (exist('ctf_read_res4') && exist('ctf_read_meg4')); case 'MRI' % other functions in the mri section status = (exist('avw_hdr_read') && exist('avw_img_read')); case 'NEUROSHARE' status = (exist('ns_OpenFile') && exist('ns_SetLibrary') && exist('ns_GetAnalogData')); case 'BESA' status = (exist('readBESAtfc') && exist('readBESAswf')); case 'EEPROBE' status = (exist('read_eep_avr') && exist('read_eep_cnt')); case 'YOKOGAWA' status = hasyokogawa('16bitBeta6'); case 'YOKOGAWA12BITBETA3' status = hasyokogawa('12bitBeta3'); case 'YOKOGAWA16BITBETA3' status = hasyokogawa('16bitBeta3'); case 'YOKOGAWA16BITBETA6' status = hasyokogawa('16bitBeta6'); case 'YOKOGAWA_MEG_READER' status = hasyokogawa('1.4'); case 'BEOWULF' status = (exist('evalwulf') && exist('evalwulf') && exist('evalwulf')); case 'MENTAT' status = (exist('pcompile') && exist('pfor') && exist('peval')); case 'SON2' status = (exist('SONFileHeader') && exist('SONChanList') && exist('SONGetChannel')); case '4D-VERSION' status = (exist('read4d') && exist('read4dhdr')); case {'STATS', 'STATISTICS'} status = license('checkout', 'statistics_toolbox'); % also check the availability of a toolbox license case {'OPTIM', 'OPTIMIZATION'} status = license('checkout', 'optimization_toolbox'); % also check the availability of a toolbox license case {'SPLINES', 'CURVE_FITTING'} status = license('checkout', 'curve_fitting_toolbox'); % also check the availability of a toolbox license case 'SIGNAL' status = license('checkout', 'signal_toolbox'); % also check the availability of a toolbox license case 'IMAGE' status = license('checkout', 'image_toolbox'); % also check the availability of a toolbox license case {'DCT', 'DISTCOMP'} status = license('checkout', 'distrib_computing_toolbox'); % also check the availability of a toolbox license case 'COMPILER' status = license('checkout', 'compiler'); % also check the availability of a toolbox license case 'FASTICA' status = exist('fpica', 'file'); case 'BRAINSTORM' status = exist('bem_xfer'); case 'DENOISE' status = (exist('tsr', 'file') && exist('sns', 'file')); case 'CTF' status = (exist('getCTFBalanceCoefs') && exist('getCTFdata')); case 'BCI2000' status = exist('load_bcidat'); case 'NLXNETCOM' status = (exist('MatlabNetComClient', 'file') && exist('NlxConnectToServer', 'file') && exist('NlxGetNewCSCData', 'file')); case 'DIPOLI' status = exist('dipoli.maci', 'file'); case 'MNE' status = (exist('fiff_read_meas_info', 'file') && exist('fiff_setup_read_raw', 'file')); case 'TCP_UDP_IP' status = (exist('pnet', 'file') && exist('pnet_getvar', 'file') && exist('pnet_putvar', 'file')); case 'BEMCP' status = (exist('bem_Cij_cog', 'file') && exist('bem_Cij_lin', 'file') && exist('bem_Cij_cst', 'file')); case 'OPENMEEG' status = exist('om_save_tri.m', 'file'); case 'PRTOOLS' status = (exist('prversion', 'file') && exist('dataset', 'file') && exist('svc', 'file')); case 'ITAB' status = (exist('lcReadHeader', 'file') && exist('lcReadData', 'file')); case 'BSMART' status = exist('bsmart'); case 'FREESURFER' status = exist('MRIread', 'file') && exist('vox2ras_0to1', 'file'); case 'FNS' status = exist('elecsfwd', 'file'); case 'SIMBIO' status = exist('calc_stiff_matrix_val', 'file') && exist('sb_transfer', 'file'); case 'VGRID' status = exist('vgrid.m', 'file'); case 'GIFTI' status = exist('gifti', 'file'); case 'XML4MAT' status = exist('xml2struct.m', 'file') && exist('xml2whos.m', 'file'); case 'SQDPROJECT' status = exist('sqdread.m', 'file') && exist('sqdwrite.m', 'file'); case 'BCT' status = exist('macaque71.mat', 'file') && exist('motif4funct_wei.m', 'file'); case 'CCA' status = exist('ccabss.m', 'file'); case 'EGI_MFF' status = exist('mff_getObject.m', 'file') && exist('mff_getSummaryInfo.m', 'file'); case 'TOOLBOX_GRAPH' status = exist('toolbox_graph'); case 'NETCDF' status = exist('netcdf'); case 'MYSQL' status = exist(['mysql.' mexext], 'file'); % this only consists of a single mex file case 'ISO2MESH' status = exist('vol2surf.m', 'file') && exist('qmeshcut.m', 'file'); case 'QSUB' status = exist('qsubfeval.m', 'file') && exist('qsubcellfun.m', 'file'); case 'ENGINE' status = exist('enginefeval.m', 'file') && exist('enginecellfun.m', 'file'); case 'DATAHASH' status = exist('DataHash.m', 'file'); case 'IBTB' status = exist('make_ibtb.m', 'file') && exist('binr.m', 'file'); case 'ICASSO' status = exist('icassoEst.m', 'file'); case 'XUNIT' status = exist('initTestSuite.m', 'file') && exist('runtests.m', 'file'); case 'PLEXON' status = exist('plx_adchan_gains.m', 'file') && exist('mexPlex'); % the following are fieldtrip modules/toolboxes case 'FILEIO' status = (exist('ft_read_header', 'file') && exist('ft_read_data', 'file') && exist('ft_read_event', 'file') && exist('ft_read_sens', 'file')); case 'FORWARD' status = (exist('ft_compute_leadfield', 'file') && exist('ft_prepare_vol_sens', 'file')); case 'PLOTTING' status = (exist('ft_plot_topo', 'file') && exist('ft_plot_mesh', 'file') && exist('ft_plot_matrix', 'file')); case 'PEER' status = exist('peerslave', 'file') && exist('peermaster', 'file'); case 'CONNECTIVITY' status = exist('ft_connectivity_corr', 'file') && exist('ft_connectivity_granger', 'file'); case 'SPIKE' status = exist('ft_spiketriggeredaverage.m', 'file') && exist('ft_spiketriggeredspectrum.m', 'file'); % these were missing, added them using the below style, see bug 1804 - roevdmei case 'INVERSE' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/inverse'], 'once')); % INVERSE is not added above, consider doing it there -roevdmei case 'REALTIME' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/realtime'], 'once')); % REALTIME is not added above, consider doing it there -roevdmei case 'SPECEST' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/specest'], 'once')); % SPECEST is not added above, consider doing it there -roevdmei case 'PREPROC' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/preproc'], 'once')); % PREPROC is not added above, consider doing it there -roevdmei % the following are not proper toolboxes, but only subdirectories in the fieldtrip toolbox % these are added in ft_defaults and are specified with unix-style forward slashes case 'COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/compat'], 'once')); case 'STATFUN' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/statfun'], 'once')); case 'TRIALFUN' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/trialfun'], 'once')); case 'UTILITIES/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/utilities/compat'], 'once')); case 'FILEIO/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/fileio/compat'], 'once')); case 'PREPROC/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/preproc/compat'], 'once')); case 'FORWARD/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/forward/compat'], 'once')); case 'PLOTTING/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/plotting/compat'], 'once')); case 'TEMPLATE/LAYOUT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/layout'], 'once')); case 'TEMPLATE/ANATOMY' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/anatomy'], 'once')); case 'TEMPLATE/HEADMODEL' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/headmodel'], 'once')); case 'TEMPLATE/ELECTRODE' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/electrode'], 'once')); case 'TEMPLATE/NEIGHBOURS' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/neighbours'], 'once')); case 'TEMPLATE/SOURCEMODEL' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/sourcemodel'], 'once')); otherwise if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end status = 0; end % it should be a boolean value status = (status~=0); % try to determine the path of the requested toolbox if autoadd>0 && ~status % for core fieldtrip modules prefix = fileparts(which('ft_defaults')); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for external fieldtrip modules prefix = fullfile(fileparts(which('ft_defaults')), 'external'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for contributed fieldtrip extensions prefix = fullfile(fileparts(which('ft_defaults')), 'contrib'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for linux computers in the Donders Centre for Cognitive Neuroimaging prefix = '/home/common/matlab'; if ~status && isunix status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for windows computers in the Donders Centre for Cognitive Neuroimaging prefix = 'h:\common\matlab'; if ~status && ispc status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % use the matlab subdirectory in your homedirectory, this works on linux and mac prefix = fullfile(getenv('HOME'), 'matlab'); if ~status && isdir(prefix) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end if ~status % the toolbox is not on the path and cannot be added sel = find(strcmp(url(:,1), toolbox)); if ~isempty(sel) msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2}); else msg = sprintf('the %s toolbox is not installed', toolbox); end if autoadd==1 error(msg); elseif autoadd==2 warning(msg); else % fail silently end end end % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before if status previous.(fixname(toolbox)) = status; end % remember the previous path, allows us to determine on the next call % whether the path has been modified outise of this function previouspath = path; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = myaddpath(toolbox, silent) if isdeployed warning('cannot change path settings for %s in a compiled application', toolbox); elseif exist(toolbox, 'dir') if ~silent, ws = warning('backtrace', 'off'); warning('adding %s toolbox to your Matlab path', toolbox); warning(ws); % return to the previous warning level end addpath(toolbox); status = 1; else status = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function path = unixpath(path) path(path=='\') = '/'; % replace backward slashes with forward slashes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = hasfunction(funname, toolbox) try % call the function without any input arguments, which probably is inapropriate feval(funname); % it might be that the function without any input already works fine status = true; catch % either the function returned an error, or the function is not available % availability is influenced by the function being present and by having a % license for the function, i.e. in a concurrent licensing setting it might % be that all toolbox licenses are in use m = lasterror; if strcmp(m.identifier, 'MATLAB:license:checkouterror') if nargin>1 warning('the %s toolbox is available, but you don''t have a license for it', toolbox); else warning('the function ''%s'' is available, but you don''t have a license for it', funname); end status = false; elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction') status = false; else % the function seems to be available and it gave an unknown error, % which is to be expected with inappropriate input arguments status = true; end end
github
philippboehmsturm/antx-master
eeg_slab_monopole.m
.m
antx-master/xspm8/external/fieldtrip/forward/private/eeg_slab_monopole.m
4,438
utf_8
a73da4acab82be2e433ef6b96c5da222
function [lf] = eeg_slab_monopole(rd, elc, vol) % EEG_SLAB_MONOPOLE calculate the strip medium leadfield % on positions pnt for a monopole at position rd and conductivity cond % The halfspace solution requires a plane dividing a conductive zone of % conductivity cond, from a non coductive zone (cond = 0) % % [lf] = eeg_slab_monopole(rd, elc, cond) % % Implemented from Malmivuo J, Plonsey R, Bioelectromagnetism (1993) % http://www.bem.fi/book/index.htm % Copyright (C) 2011, Cristiano Micheli % % This file is part of FieldTrip, see http://www.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: eeg_slab_monopole.m 7123 2012-12-06 21:21:38Z roboos $ siz = size(rd); if any(siz==1) % positions are specified as a single vector Npoles = prod(siz)/3; rd = rd(:)'; % ensure that it is a row vector elseif siz(2)==3 % positions are specified as a Nx3 matrix -> reformat to a single vector Npoles = siz(1); rd = rd'; rd = rd(:)'; % ensure that it is a row vector else error('incorrect specification of pole locations'); end Nelc = size(elc,1); lf = zeros(Nelc,Npoles); for i=1:Npoles % this is the position of dipole "i" pole1 = rd((1:3) + 3*(i-1)); % distances electrodes - corrent poles r1 = elc - ones(Nelc,1) * pole1; % Method of mirror charges: % Defines the position of mirror charge being symmetric to the plane [pole2,pole3,pole4] = get_mirror_pos(pole1,vol); % distances electrodes - mirror charge r2 = elc - ones(Nelc,1) * pole2; r3 = elc - ones(Nelc,1) * pole3; r4 = elc - ones(Nelc,1) * pole4; % denominator R1 = (4*pi*vol.cond) * sqrt(sum(r1' .^2 ) )'; % denominator, mirror term R2 = -(4*pi*vol.cond) * sqrt(sum(r2' .^2 ) )'; % denominator, mirror term of P1, plane 2 R3 = -(4*pi*vol.cond) * sqrt(sum(r3' .^2 ) )'; % denominator, mirror term of P2, plane 2 R4 = (4*pi*vol.cond) * sqrt(sum(r4' .^2 ) )'; % condition of poles falling in the non conductive halfspace instrip1 = acos(dot(vol.ori1,(pole1-vol.pnt1)./norm(pole1-vol.pnt1))) > pi/2; instrip2 = acos(dot(vol.ori2,(pole1-vol.pnt2)./norm(pole1-vol.pnt2))) > pi/2; invacuum = ~(instrip1&instrip2); if invacuum warning('a pole lies on the vacuum side of the plane'); lf(:,i) = NaN(Nelc,1); elseif any(R1)==0 warning('a pole coincides with one of the electrodes'); lf(:,i) = NaN(Nelc,1); else lf(:,i) = (1 ./ R1) + (1 ./ R2) + (1 ./ R3);% + (1 ./ R4); end end function [P2,P3,P4] = get_mirror_pos(P1,vol) % calculates the position of a point symmetric to the pole, with respect to plane1 % and two points symmetric to the last ones, with respect to plane2 P2 = []; P3 = []; P4 = []; % define the planes pnt1 = vol.pnt1; ori1 = vol.ori1; pnt2 = vol.pnt2; ori2 = vol.ori2; if abs(dot(P1-pnt1,ori1))<eps || abs(dot(P1-pnt2,ori2))<eps warning(sprintf ('point %f %f %f lies on the plane',P1(1),P1(2),P1(3))) P2 = P1; else % define the planes plane1 = def_plane(pnt1,ori1); plane2 = def_plane(pnt2,ori2); % distance plane1-point P1 d = abs(dot(ori1, plane1(:,1:3)-P1(:,1:3), 2)); % symmetric point P2 = P1 + 2*d*ori1; % distance plane2-point P1 d = abs(dot(ori2, plane2(:,1:3)-P1(:,1:3), 2)); % symmetric point P3 = P1 + 2*d*ori2; % distance plane2-point P2 d = abs(dot(ori2, plane2(:,1:3)-P2(:,1:3), 2)); % symmetric point P4 = P2 + 2*d*ori2; end function plane = def_plane(pnt,ori) % define the plane in parametric form % define a non colinear vector vc with respect to the plane normal vc = [1 0 0]; if abs(cross(ori, vc, 2))<eps vc = [0 1 0]; end % define plane's direction vectors v1 = cross(ori, vc, 2); v1 = v1/norm(v1); v2 = cross(pnt, ori, 2); v2 = v2/norm(v2); plane = [pnt v1 v2];
github
philippboehmsturm/antx-master
eeg_leadfield1.m
.m
antx-master/xspm8/external/fieldtrip/forward/private/eeg_leadfield1.m
3,851
utf_8
5b4189b3e0cfc474f626b46f8d47b752
function lf = eeg_leadfield1(R, elc, vol) % EEG_LEADFIELD1 electric leadfield for a dipole in a single sphere % % [lf] = eeg_leadfield1(R, elc, vol) % % with input arguments % R position dipole (vector of length 3) % elc position electrodes % and vol being a structure with the elements % vol.r radius of sphere % vol.c conductivity of sphere % Copyright (C) 2002, Robert Oostenveld % % this implementation is adapted from % Luetkenhoener, Habilschrift '92 % the original reference is % R. Kavanagh, T. M. Darccey, D. Lehmann, and D. H. Fender. Evaluation of methods for three-dimensional localization of electric sources in the human brain. IEEE Trans Biomed Eng, 25:421-429, 1978. % % 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: eeg_leadfield1.m 7123 2012-12-06 21:21:38Z roboos $ Nchans = size(elc, 1); lf = zeros(Nchans,3); % always take the outermost sphere, this makes comparison with the 4-sphere computation easier [vol.r, indx] = max(vol.r); vol.c = vol.c(indx); % check whether the electrode ly on the sphere, allowing 0.5% tolerance dist = sqrt(sum(elc.^2,2)); if any(abs(dist-vol.r)>vol.r*0.005) warning('electrodes do not ly on sphere surface -> using projection') end elc = vol.r * elc ./ [dist dist dist]; % check whether the dipole is inside the brain [disabled for EEGLAB] % if sqrt(sum(R.^2))>=vol.r % error('dipole is outside the brain compartment'); % end c0 = norm(R); c1 = vol.r; c2 = 4*pi*c0^2*vol.c; if c0==0 % the dipole is in the origin, this can and should be handeled as an exception [phi, el] = cart2sph(elc(:,1), elc(:,2), elc(:,3)); theta = pi/2 - el; lf(:,1) = sin(theta).*cos(phi); lf(:,2) = sin(theta).*sin(phi); lf(:,3) = cos(theta); % the potential in a homogenous sphere is three times the infinite medium potential lf = 3/(c1^2*4*pi*vol.c)*lf; else for i=1:Nchans % use another name for the electrode, in accordance with lutkenhoner1992 r = elc(i,:); c3 = r-R; c4 = norm(c3); c5 = c1^2 * c0^2 - dot(r,R)^2; % lutkenhoner A.11 c6 = c0^2*r - dot(r,R)*R; % lutkenhoner, just after A.17 % the original code reads (cf. lutkenhoner1992 equation A.17) % lf(i,:) = ((dot(R, r/norm(r) - (r-R)/norm(r-R))/(norm(cross(r,R))^2) + 2/(norm(r-R)^3)) * cross(R, cross(r, R)) + ((norm(r)^2-norm(R)^2)/(norm(r-R)^3) - 1/norm(r)) * R) / (4*pi*vol.c(1)*norm(R)^2); % but more efficient execution of the code is achieved by some precomputations if c5<1000*eps % the dipole lies on a single line with the electrode lf(i,:) = (2/c4^3 * c6 + ((c1^2-c0^2)/c4^3 - 1/c1) * R) / c2; else % nothing wrong, do the complete computation lf(i,:) = ((dot(R, r/c1 - c3/c4)/c5 + 2/c4^3) * c6 + ((c1^2-c0^2)/c4^3 - 1/c1) * R) / c2; end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fast cross product function [c] = cross(a,b) c = [a(2)*b(3)-a(3)*b(2) a(3)*b(1)-a(1)*b(3) a(1)*b(2)-a(2)*b(1)]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % fast dot product function [c] = dot(a,b) c = sum(a.*b);
github
philippboehmsturm/antx-master
meg_forward.m
.m
antx-master/xspm8/external/fieldtrip/forward/private/meg_forward.m
4,038
utf_8
ac153d74863728e2e7c2eb70a19bf210
function field=meg_forward(dip_par,forwpar) % calculates the magnetic field of n dipoles % in a realistic volume conductor % usage: field=meg_forward(dip_par,forwpar) % % input: % dip_par nx6 matrix where each row contains location (first 3 numbers) % and moment (second 3 numbers) of a dipole % forwpar structure containing all information relevant for this % calculation; forwpar is calculated with meg_ini % You have here an option to include linear transformations in % the forward model by specifying forpwar.lintrafo=A % where A is an NxM matrix. Then field -> A field % You can use that, e.g., if you can write the forward model % with M magnetometer-channels plus a matrix multiplication % transforming this to a (eventually higher order) gradiometer. % % output: % field mxn matrix where the i.th column is the field in m channels % of the i.th dipole % % note: No assumptions about units made (i.e. no scaling factors) % % Copyright (C) 2003, Guido Nolte % % 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: meg_forward.m 7123 2012-12-06 21:21:38Z roboos $ device_sens=forwpar.device_sens; field_sens_sphere=getfield_sphere(dip_par,forwpar.device_sens,forwpar.center); field=field_sens_sphere;clear field_sens_sphere; if isfield(forwpar,'device_ref') field=field-getfield_sphere(dip_par,forwpar.device_ref,forwpar.center); end if isfield(forwpar,'device_weights') field=field+forwpar.weights*getfield_sphere(dip_par,forwpar.device_weights,forwpar.center); end if forwpar.order>0 coeff=forwpar.coeff_sens; if isfield(forwpar,'device_ref') coeff=coeff-forwpar.coeff_ref; end if isfield(forwpar,'device_weights') coeff=coeff+forwpar.coeff_weights*forwpar.weights'; end field=field+getfield_corr(dip_par,coeff,forwpar.center,forwpar.order); end if isfield(forwpar,'lintrafo'); field=forwpar.lintrafo*field; end return function field=getfield_sphere(source,device,center); [ndip,ndum]=size(source); [nchan,ndum]=size(device); x1=source(:,1:3)-repmat(center',ndip,1); n1=source(:,4:6); x2=device(:,1:3)-repmat(center',nchan,1); n2=device(:,4:6); %spherical bt=leadsphere_all(x1',x2',n2'); n1rep=reshape(repmat(n1',1,nchan),3,ndip,nchan); b=dotproduct(n1rep,bt); field=b'; return function field=getfield_corr(source,coeffs,center,order); [ndip,ndum]=size(source); x1=source(:,1:3)-repmat(center',ndip,1); n1=source(:,4:6); %correction if order>0 scale=10; [bas,gradbas]=legs(x1,n1,order,scale); nbasis=(order+1)^2-1; coeffs=coeffs(1:nbasis,:); field=-(gradbas*coeffs)'; end return function out=crossproduct(x,y) % usage: out=testprog(x,y) % testprog calculates the cross-product of vector x and y [n,m,k]=size(x); out=zeros(3,m,k); out(1,:,:)=x(2,:,:).*y(3,:,:)-x(3,:,:).*y(2,:,:); out(2,:,:)=x(3,:,:).*y(1,:,:)-x(1,:,:).*y(3,:,:); out(3,:,:)=x(1,:,:).*y(2,:,:)-x(2,:,:).*y(1,:,:); return; function out=dotproduct(x,y) % usage: out=dotproduct(x,y) % testprog calculates the dotproduct of vector x and y [n,m,k]=size(x); outb=x(1,:,:).*y(1,:,:)+x(2,:,:).*y(2,:,:)+x(3,:,:).*y(3,:,:); out=reshape(outb,m,k); return; function result=norms(x); [n,m,k]=size(x); resultb=sqrt(x(1,:,:).^2+x(2,:,:).^2+x(3,:,:).^2); result=reshape(resultb,m,k); return;
github
philippboehmsturm/antx-master
postpad.m
.m
antx-master/xspm8/external/fieldtrip/preproc/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/preproc/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/preproc/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/preproc/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
butter.m
.m
antx-master/xspm8/external/fieldtrip/preproc/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
ft_statfun_roc.m
.m
antx-master/xspm8/external/fieldtrip/statfun/ft_statfun_roc.m
5,372
utf_8
ec4b890f9fa0c3a897be1b3cc74e9910
function [s, cfg] = statfun_roc(cfg, dat, design) % STATFUN_roc computes the area under the curve (AUC) of the % Receiver Operator Characteristic (ROC). This is a measure of the % separability of the data divided over two conditions. The AUC can % be used to test statistical significance of being able to predict % on a single observation basis to which condition the observation % belongs. % % Use this function by calling one of the high-level statistics % functions as % [stat] = ft_timelockstatistics(cfg, timelock1, timelock2, ...) % [stat] = ft_freqstatistics(cfg, freq1, freq2, ...) % [stat] = ft_sourcestatistics(cfg, source1, source2, ...) % with the following configuration option: % cfg.statistic = 'roc' % % Configuration options that are relevant for this function are % cfg.ivar = number, index into the design matrix with the independent variable % cfg.logtransform = 'yes' or 'no' (default = 'no') % % Note that this statfun performs a one sided test in which condition "1" % is assumed to be larger than condition "2". % A low-level example for this function is % a = randn(1,1000) + 1; % b = randn(1,1000); % design = [1*ones(1,1000) 2*ones(1,1000)]; % auc = statfun_roc([], [a b], design); % Copyright (C) 2008, Robert Oostenveld % % This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip % for the documentation and details. % % FieldTrip is free software: you can redistribute it and/or modify % it under the terms of the GNU General Public License as published by % the Free Software Foundation, either version 3 of the License, or % (at your option) any later version. % % FieldTrip is distributed in the hope that it will be useful, % but WITHOUT ANY WARRANTY; without even the implied warranty of % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the % GNU General Public License for more details. % % You should have received a copy of the GNU General Public License % along with FieldTrip. If not, see <http://www.gnu.org/licenses/>. % % $Id: ft_statfun_roc.m 7123 2012-12-06 21:21:38Z roboos $ if ~isfield(cfg, 'ivar'), cfg.ivar = 1; end if ~isfield(cfg, 'logtransform'), cfg.logtransform = 'no'; end if strcmp(cfg.logtransform, 'yes'), dat = log10(dat); end if isfield(cfg, 'numbins') % this function was completely reimplemented on 21 July 2008 by Robert Oostenveld % the old function had a positive bias in the AUC (i.e. the expected value was not 0.5) error('the option cfg.numbins is not supported any more'); end % start with a quick test to see whether there appear to be NaNs if any(isnan(dat(1,:))) % exclude trials that contain NaNs for all observed data points sel = all(isnan(dat),1); dat = dat(:,~sel); design = design(:,~sel); end % logical indexing is faster than using find(...) selA = (design(cfg.ivar,:)==1); selB = (design(cfg.ivar,:)==2); % select the data in the two classes datA = dat(:, selA); datB = dat(:, selB); nobs = size(dat,1); na = size(datA,2); nb = size(datB,2); auc = zeros(nobs, 1); for k = 1:nobs % compute the area under the curve for each channel/time/frequency a = datA(k,:); b = datB(k,:); % to speed up the AUC, the critical value is determined by the actual % values in class B, which also ensures a regular sampling of the False Alarms b = sort(b); ca = zeros(nb+1,1); ib = zeros(nb+1,1); % cb = zeros(nb+1,1); % ia = zeros(nb+1,1); for i=1:nb % for the first approach below, the critval could also be choosen based on e.g. linspace(min,max,n) critval = b(i); % for each of the two distributions, determine the number of correct and incorrect assignments given the critical value % ca(i) = sum(a>=critval); % ib(i) = sum(b>=critval); % cb(i) = sum(b<critval); % ia(i) = sum(a<critval); % this is a much faster approach, which works due to using the sorted values in b as the critical values ca(i) = sum(a>=critval); % correct assignments to class A ib(i) = nb-i+1; % incorrect assignments to class B end % add the end point ca(end) = 0; ib(end) = 0; % cb(end) = nb; % ia(end) = na; hits = ca/na; fa = ib/nb; % the numerical integration is faster if the points are sorted hits = fliplr(hits); fa = fliplr(fa); if false % this part is optional and should only be used when exploring the data figure plot(fa, hits, '.-') xlabel('false positive'); ylabel('true positive'); title('ROC-curve'); end % compute the area under the curve using numerical integration auc(k) = numint(fa, hits); end s.stat = auc; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % NUMINT computes a numerical integral of a set of sampled points using % linear interpolation. Alugh the algorithm works for irregularly sampled points % along the x-axis, it will perform best for regularly sampled points % % Use as % z = numint(x, y) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function z = numint(x, y) if ~all(diff(x)>=0) % ensure that the points are sorted along the x-axis [x, i] = sort(x); y = y(i); end n = length(x); z = 0; for i=1:(n-1) x0 = x(i); y0 = y(i); dx = x(i+1)-x(i); dy = y(i+1)-y(i); z = z + (y0 * dx) + (dy*dx/2); end
github
philippboehmsturm/antx-master
nansum.m
.m
antx-master/xspm8/external/fieldtrip/statfun/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/statfun/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/statfun/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/statfun/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/statfun/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/statfun/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
nansum.m
.m
antx-master/xspm8/external/fieldtrip/src/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/src/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
nanmean.m
.m
antx-master/xspm8/external/fieldtrip/src/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/src/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_connectivity_corr.m
.m
antx-master/xspm8/external/fieldtrip/connectivity/ft_connectivity_corr.m
8,643
utf_8
ff666c57a9e6619f5cef4afbccd42832
function [c, v, outcnt] = ft_connectivity_corr(input, varargin) % FT_CONNECTIVITY_CORR computes correlation or coherence (or a related % quantity) from a data-matrix containing a covariance or cross-spectral % density. It implements the methods described in: % Coherence: Rosenberg et al, The Fourier approach to the identification of % functional coupling between neuronal spike trains. Prog Biophys Molec % Biol 1989; 53; 1-31 % Partial coherence: Rosenberg et al, Identification of patterns of % neuronal connectivity - partial spectra, partial coherence, and neuronal % interactions. J. Neurosci. Methods, 1998; 83; 57-72 % Phase locking value: Lachaux et al, Measuring phase sychrony in brain % signals. Human Brain Mapping, 1999; 8; 194-208 % Imaginary part of coherency: Nolte et al, Identifying true brain % interaction from EEG data using the imaginary part of coherence. Clinical % Neurophysiology, 2004; 115; 2292-2307 % % Use as % [c, v, n] = ft_connectivity_corr(input, varargin) % % The input data input should be organized as: % % Repetitions x Channel x Channel (x Frequency) (x Time) % % or % % Repetitions x Channelcombination (x Frequency) (x Time) % % The first dimension should be singleton if the input already contains an % average. Furthermore, the input data can be complex-valued cross spectral % densities, or real-valued covariance estimates. If the former is the % case, the output will be coherence (or a derived metric), if the latter % is the case, the output will be the correlation coefficient. % % Additional input arguments come as key-value pairs: % % hasjack 0 or 1 specifying whether the Repetitions represent % leave-one-out samples % complex 'abs', 'angle', 'real', 'imag', 'complex', 'logabs' for % post-processing of coherency % feedback 'none', 'text', 'textbar' type of feedback showing progress of % computation % dimord specifying how the input matrix should be interpreted % powindx required if the input data contain linearly indexed % channel pairs. should be an Nx2 matrix indexing on each % row for the respective channel pair the indices of the % corresponding auto-spectra % pownorm flag that specifies whether normalisation with the % product of the power should be performed (thus should % be true when correlation/coherence is requested, and % false when covariance or cross-spectral density is % requested). % % Partialisation can be performed when the input data is (chan x chan). The % following options need to be specified: % % pchanindx index-vector to the channels that need to be % partialised % allchanindx index-vector to all channels that are used % (including the "to-be-partialised" ones). % % The output c contains the correlation/coherence, v is a variance estimate % which only can be computed if the data contains leave-one-out samples, % and n is the number of repetitions in the input data. % % See also FT_CONNECTIVITYANALYSIS % Copyright (C) 2009-2010 Donders Institute, 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_connectivity_corr.m 7123 2012-12-06 21:21:38Z roboos $ % FiXME: If output is angle, then jack-knifing should be done % differently since it is a circular variable hasjack = ft_getopt(varargin, 'hasjack', 0); cmplx = ft_getopt(varargin, 'complex', 'abs'); feedback = ft_getopt(varargin, 'feedback', 'none'); dimord = ft_getopt(varargin, 'dimord'); powindx = ft_getopt(varargin, 'powindx'); pownorm = ft_getopt(varargin, 'pownorm', 0); pchanindx = ft_getopt(varargin, 'pchanindx'); allchanindx = ft_getopt(varargin, 'allchanindx'); if isempty(dimord) error('input parameters should contain a dimord'); end siz = [size(input) 1]; % do partialisation if necessary if ~isempty(pchanindx), % partial spectra are computed as in Rosenberg JR et al (1998) J.Neuroscience Methods, equation 38 chan = allchanindx; nchan = numel(chan); pchan = pchanindx; npchan = numel(pchan); newsiz = siz; newsiz(2:3) = numel(chan); % size of partialised csd A = zeros(newsiz); % FIXME this only works for data without time dimension if numel(siz)==5 && siz(5)>1, error('this only works for data without time'); end for j = 1:siz(1) %rpt loop AA = reshape(input(j, chan, chan, : ), [nchan nchan siz(4:end)]); AB = reshape(input(j, chan, pchan,: ), [nchan npchan siz(4:end)]); BA = reshape(input(j, pchan, chan, : ), [npchan nchan siz(4:end)]); BB = reshape(input(j, pchan, pchan, :), [npchan npchan siz(4:end)]); for k = 1:siz(4) %freq loop %A(j,:,:,k) = AA(:,:,k) - AB(:,:,k)*pinv(BB(:,:,k))*BA(:,:,k); A(j,:,:,k) = AA(:,:,k) - AB(:,:,k)/(BB(:,:,k))*BA(:,:,k); end end input = A; siz = size(input); else % do nothing end % compute the metric if (length(strfind(dimord, 'chan'))~=2 || length(strfind(dimord, 'pos'))>0) && ~isempty(powindx), % crossterms are not described with chan_chan_therest, but are linearly indexed outsum = zeros(siz(2:end)); outssq = zeros(siz(2:end)); outcnt = zeros(siz(2:end)); ft_progress('init', feedback, 'computing metric...'); for j = 1:siz(1) ft_progress(j/siz(1), 'computing metric for replicate %d from %d\n', j, siz(1)); if pownorm p1 = reshape(input(j,powindx(:,1),:,:,:), siz(2:end)); p2 = reshape(input(j,powindx(:,2),:,:,:), siz(2:end)); denom = sqrt(p1.*p2); clear p1 p2 else denom = 1; end tmp = complexeval(reshape(input(j,:,:,:,:), siz(2:end))./denom, cmplx); outsum = outsum + tmp; outssq = outssq + tmp.^2; outcnt = outcnt + double(~isnan(tmp)); end ft_progress('close'); elseif length(strfind(dimord, 'chan'))==2 || length(strfind(dimord, 'pos'))==2, % crossterms are described by chan_chan_therest outsum = zeros(siz(2:end)); outssq = zeros(siz(2:end)); outcnt = zeros(siz(2:end)); ft_progress('init', feedback, 'computing metric...'); for j = 1:siz(1) ft_progress(j/siz(1), 'computing metric for replicate %d from %d\n', j, siz(1)); if pownorm p1 = zeros([siz(2) 1 siz(4:end)]); p2 = zeros([1 siz(3) siz(4:end)]); for k = 1:siz(2) p1(k,1,:,:,:,:) = input(j,k,k,:,:,:,:); p2(1,k,:,:,:,:) = input(j,k,k,:,:,:,:); end p1 = p1(:,ones(1,siz(3)),:,:,:,:); p2 = p2(ones(1,siz(2)),:,:,:,:,:); denom = sqrt(p1.*p2); clear p1 p2; else denom = 1; end tmp = complexeval(reshape(input(j,:,:,:,:,:,:), siz(2:end))./denom, cmplx); % added this for nan support marvin %tmp(isnan(tmp)) = 0; % added for nan support outsum = outsum + tmp; outssq = outssq + tmp.^2; outcnt = outcnt + double(~isnan(tmp)); end ft_progress('close'); end n = siz(1); if all(outcnt(:)==n) outcnt = n; end %n1 = shiftdim(sum(~isnan(input),1),1); %c = outsum./n1; % added this for nan support marvin c = outsum./outcnt; % correct the variance estimate for the under-estimation introduced by the jackknifing if n>1, if hasjack %bias = (n1-1).^2; % added this for nan support marvin bias = (outcnt-1).^2; else bias = 1; end %v = bias.*(outssq - (outsum.^2)./n1)./(n1 - 1); % added this for nan support marvin v = bias.*(outssq - (outsum.^2)./outcnt)./(outcnt-1); else v = []; end function [c] = complexeval(c, str) switch str case 'complex' %do nothing case 'abs' c = abs(c); case 'angle' c = angle(c); % negative angle means first row leads second row case 'imag' c = imag(c); case 'real' c = real(c); case '-logabs' c = -log(1 - abs(c).^2); otherwise error('complex = ''%s'' not supported', str); end
github
philippboehmsturm/antx-master
ft_connectivity_psi.m
.m
antx-master/xspm8/external/fieldtrip/connectivity/ft_connectivity_psi.m
5,704
utf_8
f3a2ec7e8d4d69aca6e1b1f88eb342cf
function [p, v, n] = ft_connectivity_psi(input, varargin) % FT_CONNECTIVITY_PSI computes the phase slope index from a data-matrix % containing the cross-spectral density. It implements the method described % in: Nolte et al., Robustly estimating the flow direction of information % in complex physical systems. Physical Review Letters, 2008; 100; 234101. % % Use as % [c, v, n] = ft_connectivity_psi(input, varargin) % % The input data input should be organized as: % % Repetitions x Channel x Channel (x Frequency) (x Time) % % or % % Repetitions x Channelcombination (x Frequency) (x Time) % % The first dimension should be singleton if the input already contains an % average % % Additional input arguments come as key-value pairs: % % hasjack 0 or 1 specifying whether the Repetitions represent % leave-one-out samples (allowing for a variance % estimate) % feedback 'none', 'text', 'textbar' type of feedback showing progress of % computation % dimord specifying how the input matrix should be interpreted % powindx normalize nbin the number of frequency bins across % which to integrate % % The output p contains the phase slope index, v is a variance estimate % which only can be computed if the data contains leave-one-out samples, % and n is the number of repetitions in the input data. If the phase slope % index is positive, then the first chan (1st dim) becomes more lagged (or % less leading) with higher frequency, indicating that it is causally % driven by the second channel (2nd dim) % % See also FT_CONNECTIVITYANALYSIS % Copyright (C) 2009-2010 Donders Institute, 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_connectivity_psi.m 7123 2012-12-06 21:21:38Z roboos $ % FIXME: interpretation of the slope hasjack = ft_getopt(varargin, 'hasjack', 0); feedback = ft_getopt(varargin, 'feedback', 'none'); dimord = ft_getopt(varargin, 'dimord'); powindx = ft_getopt(varargin, 'powindx'); normalize = ft_getopt(varargin, 'normalize', 'no'); nbin = ft_getopt(varargin, 'nbin'); if isempty(dimord) error('input parameters should contain a dimord'); end if (length(strfind(dimord, 'chan'))~=2 || ~isempty(strfind(dimord, 'pos'))>0) && ~isempty(powindx), %crossterms are not described with chan_chan_therest, but are linearly indexed siz = size(input); outsum = zeros(siz(2:end)); outssq = zeros(siz(2:end)); pvec = [2 setdiff(1:numel(siz),2)]; ft_progress('init', feedback, 'computing metric...'); %first compute coherency and then phaseslopeindex for j = 1:siz(1) ft_progress(j/siz(1), 'computing metric for replicate %d from %d\n', j, siz(1)); c = reshape(input(j,:,:,:,:), siz(2:end)); p1 = abs(reshape(input(j,powindx(:,1),:,:,:), siz(2:end))); p2 = abs(reshape(input(j,powindx(:,2),:,:,:), siz(2:end))); p = ipermute(phaseslope(permute(c./sqrt(p1.*p2), pvec), nbin, normalize), pvec); outsum = outsum + p; outssq = outssq + p.^2; end ft_progress('close'); elseif length(strfind(dimord, 'chan'))==2 || length(strfind(dimord, 'pos'))==2, %crossterms are described by chan_chan_therest siz = size(input); outsum = zeros(siz(2:end)); outssq = zeros(siz(2:end)); pvec = [3 setdiff(1:numel(siz),3)]; ft_progress('init', feedback, 'computing metric...'); for j = 1:siz(1) ft_progress(j/siz(1), 'computing metric for replicate %d from %d\n', j, siz(1)); p1 = zeros([siz(2) 1 siz(4:end)]); p2 = zeros([1 siz(3) siz(4:end)]); for k = 1:siz(2) p1(k,1,:,:,:,:) = input(j,k,k,:,:,:,:); p2(1,k,:,:,:,:) = input(j,k,k,:,:,:,:); end c = reshape(input(j,:,:,:,:,:,:), siz(2:end)); p1 = p1(:,ones(1,siz(3)),:,:,:,:); p2 = p2(ones(1,siz(2)),:,:,:,:,:); p = ipermute(phaseslope(permute(c./sqrt(p1.*p2), pvec), nbin, normalize), pvec); p(isnan(p)) = 0; outsum = outsum + p; outssq = outssq + p.^2; end ft_progress('close'); end n = siz(1); c = outsum./n; if n>1, n = shiftdim(sum(~isnan(input),1),1); if hasjack bias = (n-1).^2; else bias = 1; end v = bias.*(outssq - (outsum.^2)./n)./(n - 1); else v = []; end %--------------------------------------- function [y] = phaseslope(x, n, norm) m = size(x, 1); %total number of frequency bins y = zeros(size(x)); x(1:end-1,:,:,:,:) = conj(x(1:end-1,:,:,:,:)).*x(2:end,:,:,:,:); if strcmp(norm, 'yes') coh = zeros(size(x)); coh(1:end-1,:,:,:,:) = (abs(x(1:end-1,:,:,:,:)) .* abs(x(2:end,:,:,:,:))) + 1; %FIXME why the +1? get the coherence for k = 1:m begindx = max(1,k-n); endindx = min(m,k+n); y(k,:,:,:,:) = imag(nansum(x(begindx:endindx,:,:,:,:)./coh(begindx:endindx,:,:,:,:),1)); end else for k = 1:m begindx = max(1,k-n); endindx = min(m,k+n); y(k,:,:,:,:) = imag(nansum(x(begindx:endindx,:,:,:,:),1)); end end
github
philippboehmsturm/antx-master
nansum.m
.m
antx-master/xspm8/external/fieldtrip/connectivity/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
sfactorization_wilson2x2.m
.m
antx-master/xspm8/external/fieldtrip/connectivity/private/sfactorization_wilson2x2.m
4,756
utf_8
9d8be7f686ab1325b21f3b94de613d12
function [H, Z, S, psi] = sfactorization_wilson2x2(S,freq,Niterations,tol,cmbindx,fb,init) % Usage : [H, Z, psi] = sfactorization_wilson(S,fs,freq); % Inputs : S (1-sided, 3D-spectral matrix in the form of Channel x Channel x frequency) % : fs (sampling frequency in Hz) % : freq (a vector of frequencies) at which S is given % Outputs: H (transfer function) % : Z (noise covariance) % : S (cross-spectral density 1-sided) % : psi (left spectral factor) % This function is an implemention of Wilson's algorithm (Eq. 3.1) % for spectral matrix factorization % Ref: G.T. Wilson,"The Factorization of Matricial Spectral Densities," % SIAM J. Appl. Math.23,420-426(1972). % Written by M. Dhamala & G. Rangarajan, UF, Aug 3-4, 2006. % Email addresses: [email protected], [email protected] m = size(cmbindx,1); N = length(freq)-1; N2 = 2*N; % preallocate memory for efficiency Sarr = zeros(2,2,m,N2) + 1i.*zeros(2,2,m,N2); I = repmat(eye(2),[1 1 m N2]); % Defining 2 x 2 identity matrix %Step 1: Forming 2-sided spectral densities for ifft routine in matlab for c = 1:m % f_ind = 0; Stmp = S(cmbindx(c,:),cmbindx(c,:),:); for f_ind = 1:(N+1) % for f = freq % f_ind = f_ind+1; Sarr(:,:,c,f_ind) = Stmp(:,:,f_ind); if(f_ind>1) Sarr(:,:,c,2*N+2-f_ind) = Stmp(:,:,f_ind).'; end end end %Step 2: Computing covariance matrices gam = real(reshape(ifft(reshape(Sarr, [4*m N2]), [], 2),[2 2 m N2])); %Step 3: Initializing for iterations gam0 = gam(:,:,:,1); h = complex(zeros(size(gam0))); for k = 1:m switch init case 'chol' [tmp, dum] = chol(gam0(:,:,k)); if dum warning('initialization with ''chol'' for iterations did not work well, using arbitrary starting condition'); tmp = rand(2,2); %arbitrary initial condition tmp = triu(tmp); end case 'rand' tmp = rand(2,2); %arbitrary initial condition tmp = triu(tmp); otherwise error('initialization method should be eithe ''chol'' or ''rand'''); end h(:,:,k) = tmp; %h(:,:,k) = chol(gam0(:,:,k)); end psi = repmat(h, [1 1 1 N2]); %Step 4: Iterating to get spectral factors ft_progress('init', fb, 'computing spectral factorization'); for iter = 1:Niterations ft_progress(iter./Niterations, 'computing iteration %d/%d\n', iter, Niterations); invpsi = inv2x2(psi); g = sandwich2x2(invpsi, Sarr) + I; gp = PlusOperator2x2(g,m,N+1); %gp constitutes positive and half of zero lags psi_old = psi; psi = mtimes2x2(psi, gp); %psierr = sum(sum(abs(psi-psi_old))); psierr = abs(psi-psi_old)./abs(psi); if 0 plot(squeeze(psierr(2,1,1,:))); hold on plot(squeeze(psierr(1,1,1,:)),'r');drawnow end psierrf = mean(psierr(:)); if(psierrf<tol), fprintf('reaching convergence at iteration %d\n',iter); break; end; % checking convergence end ft_progress('close'); %Step 5: Getting covariance matrix from spectral factors gamtmp = reshape(real(ifft(transpose(reshape(psi, [4*m N2]))))', [2 2 m N2]); %Step 6: Getting noise covariance & transfer function (see Example pp. 424) A0 = gamtmp(:,:,:,1); A0inv = inv2x2(A0); Z = zeros(2,2,m); for k = 1:m %Z = A0*A0.'*fs; %Noise covariance matrix Z(:,:,k) = A0(:,:,k)*A0(:,:,k).'; %Noise covariance matrix not multiplied by sampling frequency %FIXME check this; at least not multiplying it removes the need to correct later on %this also makes it more equivalent to the noisecov estimated by biosig's mvar-function end H = complex(zeros(2,2,m,N+1)); S = complex(zeros(2,2,m,N+1)); for k = 1:(N+1) for kk = 1:m H(:,:,kk,k) = psi(:,:,kk,k)*A0inv(:,:,kk); % Transfer function S(:,:,kk,k) = psi(:,:,kk,k)*psi(:,:,kk,k)'; % Cross-spectral density end end siz = [size(H) 1 1]; H = reshape(H, [4*siz(3) siz(4:end)]); siz = [size(S) 1 1]; S = reshape(S, [4*siz(3) siz(4:end)]); siz = [size(Z) 1 1]; Z = reshape(Z, [4*siz(3) siz(4:end)]); siz = [size(psi) 1 1]; psi = reshape(psi, [4*siz(3) siz(4:end)]); %--------------------------------------------------------------------- function gp = PlusOperator2x2(g,ncmb,nfreq) % This function is for [ ]+operation: % to take the positive lags & half of the zero lag and reconstitute % M. Dhamala, UF, August 2006 g = transpose(reshape(g, [4*ncmb 2*(nfreq-1)])); gam = ifft(g); % taking only the positive lags and half of the zero lag gamp = gam; beta0 = 0.5*gam(1,:); %for k = 1:ncmb % gamp(1,(k-1)*4+1:k*4) = reshape(triu(reshape(beta0(1,(k-1)*4+1:k*4),[2 2])),[1 4]); %end beta0(2:4:4*ncmb) = 0; gamp(1,:) = beta0; gamp(nfreq+1:end,:) = 0; % reconstituting gp = fft(gamp); gp = reshape(transpose(gp), [2 2 ncmb 2*(nfreq-1)]);
github
philippboehmsturm/antx-master
nanstd.m
.m
antx-master/xspm8/external/fieldtrip/connectivity/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/connectivity/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/connectivity/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
sfactorization_wilson.m
.m
antx-master/xspm8/external/fieldtrip/connectivity/private/sfactorization_wilson.m
4,706
utf_8
ebcbea0ae06debde297adbb94bfb0e5e
function [H, Z, S, psi] = sfactorization_wilson(S,freq,Niterations,tol,fb,init) % Usage : [H, Z, S, psi] = sfactorization_wilson(S,fs,freq); % Inputs : S (1-sided, 3D-spectral matrix in the form of Channel x Channel x frequency) % : fs (sampling frequency in Hz) % : freq (a vector of frequencies) at which S is given % Outputs: H (transfer function) % : Z (noise covariance) % : psi (left spectral factor) % This function is an implemention of Wilson's algorithm (Eq. 3.1) % for spectral matrix factorization % Ref: G.T. Wilson,"The Factorization of Matricial Spectral Densities," % SIAM J. Appl. Math.23,420-426(1972). % Written by M. Dhamala & G. Rangarajan, UF, Aug 3-4, 2006. % Email addresses: [email protected], [email protected] % number of channels m = size(S,1); N = length(freq)-1; N2 = 2*N; % preallocate memory for efficiency Sarr = zeros(m,m,N2) + 1i.*zeros(m,m,N2); gam = zeros(m,m,N2); gamtmp = zeros(m,m,N2); psi = zeros(m,m,N2); I = eye(m); % Defining m x m identity matrix %Step 1: Forming 2-sided spectral densities for ifft routine in matlab f_ind = 0; for f = freq f_ind = f_ind+1; Sarr(:,:,f_ind) = S(:,:,f_ind); if(f_ind>1) Sarr(:,:,2*N+2-f_ind) = S(:,:,f_ind).'; end end %Step 2: Computing covariance matrices for k1 = 1:m for k2 = 1:m %gam(k1,k2,:) = real(ifft(squeeze(Sarr(k1,k2,:)))*fs); %FIXME think about this gam(k1,k2,:) = real(ifft(squeeze(Sarr(k1,k2,:)))); end end %Step 3: Initializing for iterations gam0 = gam(:,:,1); switch init case 'chol' [tmp, dum] = chol(gam0); if dum warning('initialization with ''chol'' for iterations did not work well, using arbitrary starting condition'); tmp = rand(m,m); %arbitrary initial condition tmp = triu(tmp); end case 'rand' tmp = rand(m,m); %arbitrary initial condition tmp = triu(tmp); otherwise error('initialization method should be eithe ''chol'' or ''rand'''); end h = tmp; for ind = 1:N2 psi(:,:,ind) = h; end %Step 4: Iterating to get spectral factors ft_progress('init', fb, 'computing spectral factorization'); for iter = 1:Niterations ft_progress(iter./Niterations, 'computing iteration %d/%d\n', iter, Niterations); for ind = 1:N2 invpsi = inv(psi(:,:,ind));% + I*eps(psi(:,:,ind))); g(:,:,ind) = invpsi*Sarr(:,:,ind)*invpsi'+I;%Eq 3.1 end gp = PlusOperator(g,m,N+1); %gp constitutes positive and half of zero lags psi_old = psi; for k = 1:N2 psi(:,:,k) = psi(:,:,k)*gp(:,:,k); psierr(k) = norm(psi(:,:,k)-psi_old(:,:,k),1); end psierrf = mean(psierr); if(psierrf<tol), fprintf('reaching convergence at iteration %d\n',iter); break; end; % checking convergence end ft_progress('close'); %Step 5: Getting covariance matrix from spectral factors for k1 = 1:m for k2 = 1:m gamtmp(k1,k2,:) = real(ifft(squeeze(psi(k1,k2,:)))); end end %Step 6: Getting noise covariance & transfer function (see Example pp. 424) A0 = gamtmp(:,:,1); A0inv = inv(A0); %Z = A0*A0.'*fs; %Noise covariance matrix Z = A0*A0.'; %Noise covariance matrix not multiplied by sampling frequency %FIXME check this; at least not multiplying it removes the need to correct later on %this also makes it more equivalent to the noisecov estimated by biosig's mvar-function H = zeros(m,m,N+1) + 1i*zeros(m,m,N+1); for k = 1:N+1 H(:,:,k) = psi(:,:,k)*A0inv; %Transfer function S(:,:,k) = psi(:,:,k)*psi(:,:,k)'; %Updated cross-spectral density end %--------------------------------------------------------------------- function gp = PlusOperator(g,nchan,nfreq) % This function is for [ ]+operation: % to take the positive lags & half of the zero lag and reconstitute % M. Dhamala, UF, August 2006 g = transpose(reshape(g, [nchan^2 2*(nfreq-1)])); gam = ifft(g); % taking only the positive lags and half of the zero lag gamp = gam; beta0 = 0.5*gam(1,:); gamp(1, :) = reshape(triu(reshape(beta0, [nchan nchan])),[1 nchan^2]); gamp(nfreq+1:end,:) = 0; % reconstituting gp = fft(gamp); gp = reshape(transpose(gp), [nchan nchan 2*(nfreq-1)]); %------------------------------------------------------ %this is the original code; above is vectorized version %which is assumed to be faster with many channels present %for k1 = 1:nchan % for k2 = 1:nchan % gam(k1,k2,:) = ifft(squeeze(g(k1,k2,:))); % end %end % %% taking only the positive lags and half of the zero lag %gamp = gam; %beta0 = 0.5*gam(:,:,1); %gamp(:,:,1) = triu(beta0); %this is Stau %gamp(:,:,nfreq+1:end) = 0; % %% reconstituting %for k1 = 1:nchan % for k2 = 1:nchan % gp(k1,k2,:) = fft(squeeze(gamp(k1,k2,:))); % end %end
github
philippboehmsturm/antx-master
nanvar.m
.m
antx-master/xspm8/external/fieldtrip/connectivity/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
beamformer_pcc.m
.m
antx-master/xspm8/external/fieldtrip/inverse/beamformer_pcc.m
11,650
utf_8
9448fde03bcc26701dc45d4191e63e50
function [dipout] = beamformer_pcc(dip, grad, vol, dat, Cf, varargin) % BEAMFORMER_PCC implements an experimental beamformer based on partial canonical % correlations or coherences. % Copyright (C) 2005-2008, 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: beamformer_pcc.m 7123 2012-12-06 21:21:38Z roboos $ if mod(nargin-5,2) % the first 5 arguments are fixed, the other arguments should come in pairs error('invalid number of optional arguments'); end % these optional settings do not have defaults refchan = keyval('refchan', varargin); refdip = keyval('refdip', varargin); supchan = keyval('supchan', varargin); supdip = keyval('supdip', varargin); % these settings pertain to the forward model, the defaults are set in compute_leadfield reducerank = keyval('reducerank', varargin); normalize = keyval('normalize', varargin); normalizeparam = keyval('normalizeparam', varargin); % these optional settings have defaults feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'text'; end keepcsd = keyval('keepcsd', varargin); if isempty(keepcsd), keepcsd = 'no'; end keepfilter = keyval('keepfilter', varargin); if isempty(keepfilter), keepfilter = 'no'; end keepleadfield = keyval('keepleadfield', varargin); if isempty(keepleadfield), keepleadfield = 'no'; end keepmom = keyval('keepmom', varargin); if isempty(keepmom), keepmom = 'yes'; end lambda = keyval('lambda', varargin); if isempty(lambda ), lambda = 0; end projectnoise = keyval('projectnoise', varargin); if isempty(projectnoise), projectnoise = 'yes'; end realfilter = keyval('realfilter', varargin); if isempty(realfilter), realfilter = 'yes'; end fixedori = ft_getopt(varargin,'fixedori','no'); fixedori = strcmp(fixedori, 'yes'); % convert the yes/no arguments to the corresponding logical values keepcsd = strcmp(keepcsd, 'yes'); % see below keepfilter = strcmp(keepfilter, 'yes'); keepleadfield = strcmp(keepleadfield, 'yes'); keepmom = strcmp(keepmom, 'yes'); projectnoise = strcmp(projectnoise, 'yes'); realfilter = strcmp(realfilter, 'yes'); % the postprocessing of the pcc beamformer always requires the csd matrix keepcsd = 1; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % find the dipole positions that are inside/outside the brain %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(dip, 'inside') & ~isfield(dip, 'outside'); insideLogical = ft_inside_vol(dip.pos, vol); dip.inside = find(insideLogical); dip.outside = find(~dip.inside); elseif isfield(dip, 'inside') & ~isfield(dip, 'outside'); dip.outside = setdiff(1:size(dip.pos,1), dip.inside); elseif ~isfield(dip, 'inside') & isfield(dip, 'outside'); dip.inside = setdiff(1:size(dip.pos,1), dip.outside); end % select only the dipole positions inside the brain for scanning dip.origpos = dip.pos; dip.originside = dip.inside; dip.origoutside = dip.outside; if isfield(dip, 'mom') dip.mom = dip.mom(:, dip.inside); end if isfield(dip, 'leadfield') fprintf('using precomputed leadfields\n'); dip.leadfield = dip.leadfield(dip.inside); end if isfield(dip, 'filter') fprintf('using precomputed filters\n'); dip.filter = dip.filter(dip.inside); end dip.pos = dip.pos(dip.inside, :); dip.inside = 1:size(dip.pos,1); dip.outside = []; if ~isempty(refdip) rf = ft_compute_leadfield(refdip, grad, vol, 'reducerank', reducerank, 'normalize', normalize); else rf = []; end if ~isempty(supdip) sf = ft_compute_leadfield(supdip, grad, vol, 'reducerank', reducerank, 'normalize', normalize); else sf = []; end refchan = refchan; % these can be passed as optional inputs supchan = supchan; % these can be passed as optional inputs megchan = setdiff(1:size(Cf,1), [refchan supchan]); Nrefchan = length(refchan); Nsupchan = length(supchan); Nmegchan = length(megchan); Nchan = size(Cf,1); % should equal Nmegchan + Nrefchan + Nsupchan Cmeg = Cf(megchan,megchan); % the filter uses the csd between all MEG channels isrankdeficient = (rank(Cmeg)<size(Cmeg,1)); % it is difficult to give a quantitative estimate of lambda, therefore also % support relative (percentage) measure that can be specified as string (e.g. '10%') if ~isempty(lambda) && ischar(lambda) && lambda(end)=='%' ratio = sscanf(lambda, '%f%%'); ratio = ratio/100; lambda = ratio * trace(Cmeg)/size(Cmeg,1); end if projectnoise % estimate the noise power, which is further assumed to be equal and uncorrelated over channels if isrankdeficient % estimated noise floor is equal to or higher than lambda noise = lambda; else % estimate the noise level in the covariance matrix by the smallest singular value noise = svd(Cmeg); noise = noise(end); % estimated noise floor is equal to or higher than lambda noise = max(noise, lambda); end end if realfilter % construct the filter only on the real part of the CSD matrix, i.e. filter is real invCmeg = pinv(real(Cmeg) + lambda*eye(Nmegchan)); else % construct the filter on the complex CSD matrix, i.e. filter contains imaginary component as well % this results in a phase rotation of the channel data if the filter is applied to the data invCmeg = pinv(Cmeg + lambda*eye(Nmegchan)); end % start the scanning with the proper metric ft_progress('init', feedback, 'beaming sources\n'); for i=1:size(dip.pos,1) if isfield(dip, 'leadfield') && isfield(dip, 'mom') && size(dip.mom, 1)==size(dip.leadfield{i}, 2) % reuse the leadfield that was previously computed and project lf = dip.leadfield{i} * dip.mom(:,i); elseif isfield(dip, 'leadfield') && isfield(dip, 'mom') % reuse the leadfield that was previously computed but don't project lf = dip.leadfield{i}; elseif isfield(dip, 'leadfield') && ~isfield(dip, 'mom'), % reuse the leadfield that was previously computed lf = dip.leadfield{i}; elseif ~isfield(dip, 'leadfield') && isfield(dip, 'mom') % compute the leadfield for a fixed dipole orientation lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam) * dip.mom(:,i); else % compute the leadfield lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam); end % concatenate scandip, refdip and supdip lfa = [lf rf sf]; if fixedori if isempty(refdip) && isempty(supdip) && isempty(refchan) && isempty(supchan) && (size(lf,2)==3) % compute the leadfield for the optimal dipole orientation % subsequently the leadfield for only that dipole orientation will % be used for the final filter computation if isfield(dip, 'filter') && size(dip.filter{i},1)~=1 filt = dip.filter{i}; else filt = pinv(lfa' * invCmeg * lfa) * lfa' * invCmeg; end [u, s, v] = svd(real(filt * Cmeg * ctranspose(filt))); maxpowori = u(:,1); eta = s(1,1)./s(2,2); lfa = lfa * maxpowori; dipout.ori{i} = maxpowori; dipout.eta{i} = eta; else warning_once('Ignoring ''fixedori''. The fixedori option is supported only if there is ONE dipole for location.') end end if isfield(dip, 'filter') % use the provided filter filt = dip.filter{i}; else % construct the spatial filter filt = pinv(lfa' * invCmeg * lfa) * lfa' * invCmeg; % use PINV/SVD to cover rank deficient leadfield end % concatenate the source filters with the channel filters Ndip = size(lfa, 2); filtn = zeros(Ndip+Nrefchan+Nsupchan, Nmegchan+Nrefchan+Nsupchan); % this part of the filter relates to the sources filtn(1:Ndip,megchan) = filt; % this part of the filter relates to the channels filtn((Ndip+1):end,setdiff(1:(Nmegchan+Nrefchan+Nsupchan), megchan)) = eye(Nrefchan+Nsupchan); filt = filtn; clear filtn if keepcsd dipout.csd{i} = filt * Cf * ctranspose(filt); end if projectnoise dipout.noisecsd{i} = noise * (filt * ctranspose(filt)); end if keepmom && ~isempty(dat) dipout.mom{i} = filt * dat; end if keepfilter dipout.filter{i} = filt; end if keepleadfield dipout.leadfield{i} = lf; end ft_progress(i/size(dip.pos,1), 'beaming source %d from %d\n', i, size(dip.pos,1)); end % for all dipoles ft_progress('close'); dipout.inside = dip.originside; dipout.outside = dip.origoutside; dipout.pos = dip.origpos; % remember how all components in the output csd should be interpreted scandiplabel = repmat({'scandip'}, 1, size(lf, 2)); % based on last leadfield refdiplabel = repmat({'refdip'}, 1, size(rf, 2)); supdiplabel = repmat({'supdip'}, 1, size(sf, 2)); refchanlabel = repmat({'refchan'}, 1, Nrefchan); supchanlabel = repmat({'supchan'}, 1, Nsupchan); % concatenate all the labels dipout.csdlabel = [scandiplabel refdiplabel supdiplabel refchanlabel supchanlabel]; % reassign the scan values over the inside and outside grid positions if isfield(dipout, 'leadfield') dipout.leadfield(dipout.inside) = dipout.leadfield; dipout.leadfield(dipout.outside) = {[]}; end if isfield(dipout, 'filter') dipout.filter(dipout.inside) = dipout.filter; dipout.filter(dipout.outside) = {[]}; end if isfield(dipout, 'mom') dipout.mom(dipout.inside) = dipout.mom; dipout.mom(dipout.outside) = {[]}; end if isfield(dipout, 'csd') dipout.csd(dipout.inside) = dipout.csd; dipout.csd(dipout.outside) = {[]}; end if isfield(dipout, 'noisecsd') dipout.noisecsd(dipout.inside) = dipout.noisecsd; dipout.noisecsd(dipout.outside) = {[]}; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function to compute the pseudo inverse. This is the same as the % standard Matlab function, except that the default tolerance is twice as % high. % Copyright 1984-2004 The MathWorks, Inc. % $Revision: 7123 $ $Date: 2009/01/07 13:12:03 $ % default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function X = pinv(A,varargin) [m,n] = size(A); if n > m X = pinv(A',varargin{:})'; else [U,S,V] = svd(A,0); if m > 1, s = diag(S); elseif m == 1, s = S(1); else s = 0; end if nargin == 2 tol = varargin{1}; else tol = 10 * max(m,n) * max(s) * eps; end r = sum(s > tol); if (r == 0) X = zeros(size(A'),class(A)); else s = diag(ones(r,1)./s(1:r)); X = V(:,1:r)*s*U(:,1:r)'; end end
github
philippboehmsturm/antx-master
beamformer_dics.m
.m
antx-master/xspm8/external/fieldtrip/inverse/beamformer_dics.m
24,638
utf_8
9201784dbd8090bd17ebbb75c3c3d1e5
function [dipout] = beamformer_dics(dip, grad, vol, dat, Cf, varargin) % BEAMFORMER_DICS scans on pre-defined dipole locations with a single dipole % and returns the beamformer spatial filter output for a dipole on every % location. Dipole locations that are outside the head will return a % NaN value. % % Use as % [dipout] = beamformer_dics(dipin, grad, vol, dat, cov, varargin) % where % dipin is the input dipole model % grad is the gradiometer definition % vol is the volume conductor definition % dat is the data matrix with the ERP or ERF % cov is the data covariance or cross-spectral density matrix % and % dipout is the resulting dipole model with all details % % The input dipole model consists of % dipin.pos positions for dipole, e.g. regular grid, Npositions x 3 % dipin.mom dipole orientation (optional), 3 x Npositions % % Additional options should be specified in key-value pairs and can be % 'Pr' = power of the external reference channel % 'Cr' = cross spectral density between all data channels and the external reference channel % 'refdip' = location of dipole with which coherence is computed % 'lambda' = regularisation parameter % 'powmethod' = can be 'trace' or 'lambda1' % 'feedback' = give ft_progress indication, can be 'text', 'gui' or 'none' % 'fixedori' = use fixed or free orientation, can be 'yes' or 'no' % 'projectnoise' = project noise estimate through filter, can be 'yes' or 'no' % 'realfilter' = construct a real-valued filter, can be 'yes' or 'no' % 'keepfilter' = remember the beamformer filter, can be 'yes' or 'no' % 'keepleadfield' = remember the forward computation, can be 'yes' or 'no' % 'keepcsd' = remember the estimated cross-spectral density, can be 'yes' or 'no' % % These options influence the forward computation of the leadfield % 'reducerank' = reduce the leadfield rank, can be 'no' or a number (e.g. 2) % 'normalize' = normalize the leadfield % 'normalizeparam' = parameter for depth normalization (default = 0.5) % % If the dipole definition only specifies the dipole location, a rotating % dipole (regional source) is assumed on each location. If a dipole moment % is specified, its orientation will be used and only the strength will % be fitted to the data. % Copyright (C) 2003-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: beamformer_dics.m 7123 2012-12-06 21:21:38Z roboos $ if mod(nargin-5,2) % the first 5 arguments are fixed, the other arguments should come in pairs error('invalid number of optional arguments'); end % these optional settings do not have defaults Pr = keyval('Pr', varargin); Cr = keyval('Cr', varargin); refdip = keyval('refdip', varargin); powmethod = keyval('powmethod', varargin); % the default for this is set below realfilter = keyval('realfilter', varargin); % the default for this is set below % these settings pertain to the forward model, the defaults are set in compute_leadfield reducerank = keyval('reducerank', varargin); normalize = keyval('normalize', varargin); normalizeparam = keyval('normalizeparam', varargin); % these optional settings have defaults feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'text'; end keepcsd = keyval('keepcsd', varargin); if isempty(keepcsd), keepcsd = 'no'; end keepfilter = keyval('keepfilter', varargin); if isempty(keepfilter), keepfilter = 'no'; end keepleadfield = keyval('keepleadfield', varargin); if isempty(keepleadfield), keepleadfield = 'no'; end lambda = keyval('lambda', varargin); if isempty(lambda ), lambda = 0; end projectnoise = keyval('projectnoise', varargin); if isempty(projectnoise), projectnoise = 'yes'; end fixedori = keyval('fixedori', varargin); if isempty(fixedori), fixedori = 'no'; end subspace = keyval('subspace', varargin); % convert the yes/no arguments to the corresponding logical values keepcsd = strcmp(keepcsd, 'yes'); keepfilter = strcmp(keepfilter, 'yes'); keepleadfield = strcmp(keepleadfield, 'yes'); projectnoise = strcmp(projectnoise, 'yes'); fixedori = strcmp(fixedori, 'yes'); % FIXME besides regular/complex lambda1, also implement a real version % default is to use the largest singular value of the csd matrix, see Gross 2001 if isempty(powmethod) powmethod = 'lambda1'; end % default is to be consistent with the original description of DICS in Gross 2001 if isempty(realfilter) realfilter = 'no'; end % use these two logical flags instead of doing the string comparisons each time again powtrace = strcmp(powmethod, 'trace'); powlambda1 = strcmp(powmethod, 'lambda1'); if ~isempty(Cr) % ensure that the cross-spectral density with the reference signal is a column matrix Cr = Cr(:); end if isfield(dip, 'mom') && fixedori error('you cannot specify a dipole orientation and fixedmom simultaneously'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % find the dipole positions that are inside/outside the brain %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(dip, 'inside') && ~isfield(dip, 'outside'); insideLogical = ft_inside_vol(dip.pos, vol); dip.inside = find(insideLogical); dip.outside = find(~dip.inside); elseif isfield(dip, 'inside') && ~isfield(dip, 'outside'); dip.outside = setdiff(1:size(dip.pos,1), dip.inside); elseif ~isfield(dip, 'inside') && isfield(dip, 'outside'); dip.inside = setdiff(1:size(dip.pos,1), dip.outside); end % select only the dipole positions inside the brain for scanning dip.origpos = dip.pos; dip.originside = dip.inside; dip.origoutside = dip.outside; if isfield(dip, 'mom') dip.mom = dip.mom(:,dip.inside); end if isfield(dip, 'leadfield') fprintf('using precomputed leadfields\n'); dip.leadfield = dip.leadfield(dip.inside); end if isfield(dip, 'filter') fprintf('using precomputed filters\n'); dip.filter = dip.filter(dip.inside); end if isfield(dip, 'subspace') fprintf('using subspace projection\n'); dip.subspace = dip.subspace(dip.inside); end dip.pos = dip.pos(dip.inside, :); dip.inside = 1:size(dip.pos,1); dip.outside = []; % dics has the following sub-methods, which depend on the function input arguments % power only, cortico-muscular coherence and cortico-cortical coherence if ~isempty(Cr) && ~isempty(Pr) && isempty(refdip) % compute cortico-muscular coherence, using reference cross spectral density submethod = 'dics_refchan'; elseif isempty(Cr) && isempty(Pr) && ~isempty(refdip) % compute cortico-cortical coherence with a dipole at the reference position submethod = 'dics_refdip'; elseif isempty(Cr) && isempty(Pr) && isempty(refdip) % only compute power of a dipole at the grid positions submethod = 'dics_power'; else error('invalid combination of input arguments for dics'); end isrankdeficient = (rank(Cf)<size(Cf,1)); % it is difficult to give a quantitative estimate of lambda, therefore also % support relative (percentage) measure that can be specified as string (e.g. '10%') if ~isempty(lambda) && ischar(lambda) && lambda(end)=='%' ratio = sscanf(lambda, '%f%%'); ratio = ratio/100; lambda = ratio * trace(Cf)/size(Cf,1); end if projectnoise % estimate the noise power, which is further assumed to be equal and uncorrelated over channels if isrankdeficient % estimated noise floor is equal to or higher than lambda noise = lambda; else % estimate the noise level in the covariance matrix by the smallest singular value noise = svd(Cf); noise = noise(end); % estimated noise floor is equal to or higher than lambda noise = max(noise, lambda); end end % the inverse only has to be computed once for all dipoles if strcmp(realfilter, 'yes') % the filter is computed using only the leadfield and the inverse covariance or CSD matrix % therefore using the real-valued part of the CSD matrix here ensures a real-valued filter invCf = pinv(real(Cf) + lambda * eye(size(Cf))); else invCf = pinv(Cf + lambda * eye(size(Cf))); end if isfield(dip, 'subspace') fprintf('using source-specific subspace projection\n'); % remember the original data prior to the voxel dependent subspace projection dat_pre_subspace = dat; Cf_pre_subspace = Cf; if strcmp(submethod, 'dics_refchan') Cr_pre_subspace = Cr; Pr_pre_subspace = Pr; end elseif ~isempty(subspace) fprintf('using data-specific subspace projection\n'); % TODO implement an "eigenspace beamformer" as described in Sekihara et al. 2002 in HBM if numel(subspace)==1, % interpret this as a truncation of the eigenvalue-spectrum % if <1 it is a fraction of the largest eigenvalue % if >=1 it is the number of largest eigenvalues dat_pre_subspace = dat; Cf_pre_subspace = Cf; [u, s, v] = svd(real(Cf)); if subspace<1, sel = find(diag(s)./s(1,1) > subspace); subspace = max(sel); end Cf = s(1:subspace,1:subspace); % this is equivalent to subspace*Cf*subspace' but behaves well numerically % by construction. invCf = diag(1./diag(Cf)); subspace = u(:,1:subspace)'; dat = subspace*dat; if strcmp(submethod, 'dics_refchan') Cr = subspace*Cr; end else Cf_pre_subspace = Cf; Cf = subspace*Cf*subspace'; % here the subspace can be different from % the singular vectors of Cy, so we have to do the sandwiching as opposed % to line 216 if strcmp(realfilter, 'yes') invCf = pinv(real(Cf)); else invCf = pinv(Cf); end if strcmp(submethod, 'dics_refchan') Cr = subspace*Cr; end end end % start the scanning with the proper metric ft_progress('init', feedback, 'scanning grid'); switch submethod case 'dics_power' % only compute power of a dipole at the grid positions for i=1:size(dip.pos,1) if isfield(dip, 'leadfield') && isfield(dip, 'mom') && size(dip.mom, 1)==size(dip.leadfield{i}, 2) % reuse the leadfield that was previously computed and project lf = dip.leadfield{i} * dip.mom(:,i); elseif isfield(dip, 'leadfield') && isfield(dip, 'mom') % reuse the leadfield that was previously computed but don't project lf = dip.leadfield{i}; elseif isfield(dip, 'leadfield') && ~isfield(dip, 'mom') % reuse the leadfield that was previously computed lf = dip.leadfield{i}; elseif ~isfield(dip, 'leadfield') && isfield(dip, 'mom') % compute the leadfield for a fixed dipole orientation lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam) * dip.mom(:,i); else % compute the leadfield lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam); end if isfield(dip, 'subspace') % do subspace projection of the forward model lf = dip.subspace{i} * lf; % the cross-spectral density becomes voxel dependent due to the projection Cf = dip.subspace{i} * Cf_pre_subspace * dip.subspace{i}'; if strcmp(realfilter, 'yes') invCf = pinv(dip.subspace{i} * (real(Cf_pre_subspace) + lambda * eye(size(Cf_pre_subspace))) * dip.subspace{i}'); else invCf = pinv(dip.subspace{i} * (Cf_pre_subspace + lambda * eye(size(Cf_pre_subspace))) * dip.subspace{i}'); end elseif ~isempty(subspace) % do subspace projection of the forward model only lforig = lf; lf = subspace * lf; % according to Kensuke's paper, the eigenspace bf boils down to projecting % the 'traditional' filter onto the subspace % spanned by the first k eigenvectors [u,s,v] = svd(Cy); filt = ESES*filt; % ESES = u(:,1:k)*u(:,1:k)'; % however, even though it seems that the shape of the filter is identical to % the shape it is obtained with the following code, the w*lf=I does not % hold. end if fixedori % compute the leadfield for the optimal dipole orientation % subsequently the leadfield for only that dipole orientation will % be used for the final filter computation if isfield(dip, 'filter') && size(dip.filter{i},1)~=1 filt = dip.filter{i}; else filt = pinv(lf' * invCf * lf) * lf' * invCf; end [u, s, v] = svd(real(filt * Cf * ctranspose(filt))); maxpowori = u(:,1); eta = s(1,1)./s(2,2); lf = lf * maxpowori; dipout.ori{i} = maxpowori; dipout.eta{i} = eta; if ~isempty(subspace), lforig = lforig * maxpowori; end end if isfield(dip, 'filter') % use the provided filter filt = dip.filter{i}; else % construct the spatial filter filt = pinv(lf' * invCf * lf) * lf' * invCf; % Gross eqn. 3, use PINV/SVD to cover rank deficient leadfield end csd = filt * Cf * ctranspose(filt); % Gross eqn. 4 and 5 if powlambda1 dipout.pow(i) = lambda1(csd); % compute the power at the dipole location, Gross eqn. 8 elseif powtrace dipout.pow(i) = real(trace(csd)); % compute the power at the dipole location end if keepcsd dipout.csd{i} = csd; end if projectnoise if powlambda1 dipout.noise(i) = noise * lambda1(filt * ctranspose(filt)); elseif powtrace dipout.noise(i) = noise * real(trace(filt * ctranspose(filt))); end if keepcsd dipout.noisecsd{i} = noise * filt * ctranspose(filt); end end if keepfilter if ~isempty(subspace) dipout.filter{i} = filt*subspace; %FIXME should this be subspace, or pinv(subspace)? else dipout.filter{i} = filt; end end if keepleadfield if ~isempty(subspace) dipout.leadfield{i} = lforig; else dipout.leadfield{i} = lf; end end ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1)); end case 'dics_refchan' % compute cortico-muscular coherence, using reference cross spectral density for i=1:size(dip.pos,1) if isfield(dip, 'leadfield') % reuse the leadfield that was previously computed lf = dip.leadfield{i}; elseif isfield(dip, 'mom') % compute the leadfield for a fixed dipole orientation lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize) .* dip.mom(i,:)'; else % compute the leadfield lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize); end if isfield(dip, 'subspace') % do subspace projection of the forward model lforig = lf; lf = dip.subspace{i} * lf; % the cross-spectral density becomes voxel dependent due to the projection Cf = dip.subspace{i} * Cf_pre_subspace * dip.subspace{i}'; invCf = pinv(dip.subspace{i} * (Cf_pre_subspace + lambda * eye(size(Cf))) * dip.subspace{i}'); elseif ~isempty(subspace) % do subspace projection of the forward model only lforig = lf; lf = subspace * lf; % according to Kensuke's paper, the eigenspace bf boils down to projecting % the 'traditional' filter onto the subspace % spanned by the first k eigenvectors [u,s,v] = svd(Cy); filt = ESES*filt; % ESES = u(:,1:k)*u(:,1:k)'; % however, even though it seems that the shape of the filter is identical to % the shape it is obtained with the following code, the w*lf=I does not % hold. end if fixedori % compute the leadfield for the optimal dipole orientation % subsequently the leadfield for only that dipole orientation will be used for the final filter computation filt = pinv(lf' * invCf * lf) * lf' * invCf; [u, s, v] = svd(real(filt * Cf * ctranspose(filt))); maxpowori = u(:,1); lf = lf * maxpowori; dipout.ori{i} = maxpowori; end if isfield(dip, 'filter') % use the provided filter filt = dip.filter{i}; else % construct the spatial filter filt = pinv(lf' * invCf * lf) * lf' * invCf; % use PINV/SVD to cover rank deficient leadfield end if powlambda1 [pow, ori] = lambda1(filt * Cf * ctranspose(filt)); % compute the power and orientation at the dipole location, Gross eqn. 4, 5 and 8 elseif powtrace pow = real(trace(filt * Cf * ctranspose(filt))); % compute the power at the dipole location end csd = filt*Cr; % Gross eqn. 6 if powlambda1 % FIXME this should use the dipole orientation with maximum power coh = lambda1(csd)^2 / (pow * Pr); % Gross eqn. 9 elseif powtrace coh = norm(csd)^2 / (pow * Pr); end dipout.pow(i) = pow; dipout.coh(i) = coh; if keepcsd dipout.csd{i} = csd; end if projectnoise if powlambda1 dipout.noise(i) = noise * lambda1(filt * ctranspose(filt)); elseif powtrace dipout.noise(i) = noise * real(trace(filt * ctranspose(filt))); end if keepcsd dipout.noisecsd{i} = noise * filt * ctranspose(filt); end end if keepfilter dipout.filter{i} = filt; end if keepleadfield if ~isempty(subspace) dipout.leadfield{i} = lforig; else dipout.leadfield{i} = lf; end end ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1)); end case 'dics_refdip' if isfield(dip, 'subspace') || ~isempty(subspace) error('subspace projections are not supported for beaming cortico-cortical coherence'); end if fixedori error('fixed orientations are not supported for beaming cortico-cortical coherence'); end % compute cortio-cortical coherence with a dipole at the reference position lf1 = ft_compute_leadfield(refdip, grad, vol, 'reducerank', reducerank, 'normalize', normalize); % construct the spatial filter for the first (reference) dipole location filt1 = pinv(lf1' * invCf * lf1) * lf1' * invCf; % use PINV/SVD to cover rank deficient leadfield if powlambda1 Pref = lambda1(filt1 * Cf * ctranspose(filt1)); % compute the power at the first dipole location, Gross eqn. 8 elseif powtrace Pref = real(trace(filt1 * Cf * ctranspose(filt1))); % compute the power at the first dipole location end for i=1:size(dip.pos,1) if isfield(dip, 'leadfield') % reuse the leadfield that was previously computed lf2 = dip.leadfield{i}; elseif isfield(dip, 'mom') % compute the leadfield for a fixed dipole orientation lf2 = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize) .* dip.mom(i,:)'; else % compute the leadfield lf2 = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize); end if isfield(dip, 'filter') % use the provided filter filt2 = dip.filter{i}; else % construct the spatial filter for the second dipole location filt2 = pinv(lf2' * invCf * lf2) * lf2' * invCf; % use PINV/SVD to cover rank deficient leadfield end csd = filt1 * Cf * ctranspose(filt2); % compute the cross spectral density between the two dipoles, Gross eqn. 4 if powlambda1 pow = lambda1(filt2 * Cf * ctranspose(filt2)); % compute the power at the second dipole location, Gross eqn. 8 elseif powtrace pow = real(trace(filt2 * Cf * ctranspose(filt2))); % compute the power at the second dipole location end if powlambda1 coh = lambda1(csd)^2 / (pow * Pref); % compute the coherence between the first and second dipole elseif powtrace coh = real(trace((csd)))^2 / (pow * Pref); % compute the coherence between the first and second dipole end dipout.pow(i) = pow; dipout.coh(i) = coh; if keepcsd dipout.csd{i} = csd; end if projectnoise if powlambda1 dipout.noise(i) = noise * lambda1(filt2 * ctranspose(filt2)); elseif powtrace dipout.noise(i) = noise * real(trace(filt2 * ctranspose(filt2))); end if keepcsd dipout.noisecsd{i} = noise * filt2 * ctranspose(filt2); end end if keepleadfield dipout.leadfield{i} = lf2; end ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1)); end end % switch submethod ft_progress('close'); dipout.inside = dip.originside; dipout.outside = dip.origoutside; dipout.pos = dip.origpos; % reassign the scan values over the inside and outside grid positions if isfield(dipout, 'leadfield') dipout.leadfield(dipout.inside) = dipout.leadfield; dipout.leadfield(dipout.outside) = {[]}; end if isfield(dipout, 'filter') dipout.filter(dipout.inside) = dipout.filter; dipout.filter(dipout.outside) = {[]}; end if isfield(dipout, 'ori') dipout.ori(dipout.inside) = dipout.ori; dipout.ori(dipout.outside) = {[]}; end if isfield(dipout, 'pow') dipout.pow(dipout.inside) = dipout.pow; dipout.pow(dipout.outside) = nan; end if isfield(dipout, 'noise') dipout.noise(dipout.inside) = dipout.noise; dipout.noise(dipout.outside) = nan; end if isfield(dipout, 'coh') dipout.coh(dipout.inside) = dipout.coh; dipout.coh(dipout.outside) = nan; end if isfield(dipout, 'csd') dipout.csd(dipout.inside) = dipout.csd; dipout.csd(dipout.outside) = {[]}; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function to obtain the largest singular value %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [s, ori] = lambda1(x) % determine the largest singular value, which corresponds to the power along the dominant direction [u, s, v] = svd(x); s = s(1); ori = u(:,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function to compute the pseudo inverse. This is the same as the % standard Matlab function, except that the default tolerance is twice as % high. % Copyright 1984-2004 The MathWorks, Inc. % $Revision: 7123 $ $Date: 2009/06/17 13:40:37 $ % default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function X = pinv(A,varargin) [m,n] = size(A); if n > m X = pinv(A',varargin{:})'; else [U,S,V] = svd(A,0); if m > 1, s = diag(S); elseif m == 1, s = S(1); else s = 0; end if nargin == 2 tol = varargin{1}; else tol = 10 * max(m,n) * max(s) * eps; end r = sum(s > tol); if (r == 0) X = zeros(size(A'),class(A)); else s = diag(ones(r,1)./s(1:r)); X = V(:,1:r)*s*U(:,1:r)'; end end
github
philippboehmsturm/antx-master
beamformer_lcmv.m
.m
antx-master/xspm8/external/fieldtrip/inverse/beamformer_lcmv.m
16,360
utf_8
24543219357b20596a7a2d8f35070a41
function [dipout] = beamformer_lcmv(dip, grad, vol, dat, Cy, varargin) % BEAMFORMER_LCMV scans on pre-defined dipole locations with a single dipole % and returns the beamformer spatial filter output for a dipole on every % location. Dipole locations that are outside the head will return a % NaN value. % % Use as % [dipout] = beamformer_lcmv(dipin, grad, vol, dat, cov, varargin) % where % dipin is the input dipole model % grad is the gradiometer definition % vol is the volume conductor definition % dat is the data matrix with the ERP or ERF % cov is the data covariance or cross-spectral density matrix % and % dipout is the resulting dipole model with all details % % The input dipole model consists of % dipin.pos positions for dipole, e.g. regular grid, Npositions x 3 % dipin.mom dipole orientation (optional), 3 x Npositions % % Additional options should be specified in key-value pairs and can be % 'lambda' = regularisation parameter % 'powmethod' = can be 'trace' or 'lambda1' % 'feedback' = give ft_progress indication, can be 'text', 'gui' or 'none' (default) % 'fixedori' = use fixed or free orientation, can be 'yes' or 'no' % 'projectnoise' = project noise estimate through filter, can be 'yes' or 'no' % 'projectmom' = project the dipole moment timecourse on the direction of maximal power, can be 'yes' or 'no' % 'keepfilter' = remember the beamformer filter, can be 'yes' or 'no' % 'keepleadfield' = remember the forward computation, can be 'yes' or 'no' % 'keepmom' = remember the estimated dipole moment, can be 'yes' or 'no' % 'keepcov' = remember the estimated dipole covariance, can be 'yes' or 'no' % % These options influence the forward computation of the leadfield % 'reducerank' = reduce the leadfield rank, can be 'no' or a number (e.g. 2) % 'normalize' = normalize the leadfield % 'normalizeparam' = parameter for depth normalization (default = 0.5) % % If the dipole definition only specifies the dipole location, a rotating % dipole (regional source) is assumed on each location. If a dipole moment % is specified, its orientation will be used and only the strength will % be fitted to the data. % Copyright (C) 2003-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: beamformer_lcmv.m 7123 2012-12-06 21:21:38Z roboos $ if mod(nargin-5,2) % the first 5 arguments are fixed, the other arguments should come in pairs error('invalid number of optional arguments'); end % these optional settings do not have defaults powmethod = keyval('powmethod', varargin); % the default for this is set below subspace = keyval('subspace', varargin); % used to implement an "eigenspace beamformer" as described in Sekihara et al. 2002 in HBM % these settings pertain to the forward model, the defaults are set in compute_leadfield reducerank = keyval('reducerank', varargin); normalize = keyval('normalize', varargin); normalizeparam = keyval('normalizeparam', varargin); % these optional settings have defaults feedback = keyval('feedback', varargin); if isempty(feedback), feedback = 'text'; end keepfilter = keyval('keepfilter', varargin); if isempty(keepfilter), keepfilter = 'no'; end keepleadfield = keyval('keepleadfield', varargin); if isempty(keepleadfield), keepleadfield = 'no'; end keepcov = keyval('keepcov', varargin); if isempty(keepcov), keepcov = 'no'; end keepmom = keyval('keepmom', varargin); if isempty(keepmom), keepmom = 'yes'; end lambda = keyval('lambda', varargin); if isempty(lambda ), lambda = 0; end projectnoise = keyval('projectnoise', varargin); if isempty(projectnoise), projectnoise = 'yes'; end projectmom = keyval('projectmom', varargin); if isempty(projectmom), projectmom = 'no'; end fixedori = keyval('fixedori', varargin); if isempty(fixedori), fixedori = 'no'; end % convert the yes/no arguments to the corresponding logical values keepfilter = strcmp(keepfilter, 'yes'); keepleadfield = strcmp(keepleadfield, 'yes'); keepcov = strcmp(keepcov, 'yes'); keepmom = strcmp(keepmom, 'yes'); projectnoise = strcmp(projectnoise, 'yes'); projectmom = strcmp(projectmom, 'yes'); fixedori = strcmp(fixedori, 'yes'); % default is to use the trace of the covariance matrix, see Van Veen 1997 if isempty(powmethod) powmethod = 'trace'; end % use these two logical flags instead of doing the string comparisons each time again powtrace = strcmp(powmethod, 'trace'); powlambda1 = strcmp(powmethod, 'lambda1'); if isfield(dip, 'mom') && fixedori error('you cannot specify a dipole orientation and fixedmom simultaneously'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % find the dipole positions that are inside/outside the brain %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if ~isfield(dip, 'inside') && ~isfield(dip, 'outside'); insideLogical = ft_inside_vol(dip.pos, vol); dip.inside = find(insideLogical); dip.outside = find(~dip.inside); elseif isfield(dip, 'inside') && ~isfield(dip, 'outside'); dip.outside = setdiff(1:size(dip.pos,1), dip.inside); elseif ~isfield(dip, 'inside') && isfield(dip, 'outside'); dip.inside = setdiff(1:size(dip.pos,1), dip.outside); end % select only the dipole positions inside the brain for scanning dip.origpos = dip.pos; dip.originside = dip.inside; dip.origoutside = dip.outside; if isfield(dip, 'mom') dip.mom = dip.mom(:, dip.inside); end if isfield(dip, 'leadfield') fprintf('using precomputed leadfields\n'); dip.leadfield = dip.leadfield(dip.inside); end if isfield(dip, 'filter') fprintf('using precomputed filters\n'); dip.filter = dip.filter(dip.inside); end if isfield(dip, 'subspace') fprintf('using subspace projection\n'); dip.subspace = dip.subspace(dip.inside); end dip.pos = dip.pos(dip.inside, :); dip.inside = 1:size(dip.pos,1); dip.outside = []; isrankdeficient = (rank(Cy)<size(Cy,1)); % it is difficult to give a quantitative estimate of lambda, therefore also % support relative (percentage) measure that can be specified as string (e.g. '10%') if ~isempty(lambda) && ischar(lambda) && lambda(end)=='%' ratio = sscanf(lambda, '%f%%'); ratio = ratio/100; lambda = ratio * trace(Cy)/size(Cy,1); end if projectnoise % estimate the noise power, which is further assumed to be equal and uncorrelated over channels if isrankdeficient % estimated noise floor is equal to or higher than lambda noise = lambda; else % estimate the noise level in the covariance matrix by the smallest singular value noise = svd(Cy); noise = noise(end); % estimated noise floor is equal to or higher than lambda noise = max(noise, lambda); end end % the inverse only has to be computed once for all dipoles invCy = pinv(Cy + lambda * eye(size(Cy))); if isfield(dip, 'subspace') fprintf('using source-specific subspace projection\n'); % remember the original data prior to the voxel dependent subspace projection dat_pre_subspace = dat; Cy_pre_subspace = Cy; elseif ~isempty(subspace) fprintf('using data-specific subspace projection\n'); % TODO implement an "eigenspace beamformer" as described in Sekihara et al. 2002 in HBM if numel(subspace)==1, % interpret this as a truncation of the eigenvalue-spectrum % if <1 it is a fraction of the largest eigenvalue % if >=1 it is the number of largest eigenvalues dat_pre_subspace = dat; Cy_pre_subspace = Cy; [u, s, v] = svd(real(Cy)); if subspace<1, sel = find(diag(s)./s(1,1) > subspace); subspace = max(sel); else Cy = s(1:subspace,1:subspace); % this is equivalent to subspace*Cy*subspace' but behaves well numerically % by construction. invCy = diag(1./diag(Cy)); subspace = u(:,1:subspace)'; dat = subspace*dat; end else dat_pre_subspace = dat; Cy_pre_subspace = Cy; Cy = subspace*Cy*subspace'; % here the subspace can be different from % the singular vectors of Cy, so we have to do the sandwiching as opposed % to line 216 invCy = pinv(Cy); dat = subspace*dat; end end % start the scanning with the proper metric ft_progress('init', feedback, 'scanning grid'); for i=1:size(dip.pos,1) if isfield(dip, 'leadfield') && isfield(dip, 'mom') && size(dip.mom, 1)==size(dip.leadfield{i}, 2) % reuse the leadfield that was previously computed and project lf = dip.leadfield{i} * dip.mom(:,i); elseif isfield(dip, 'leadfield') && isfield(dip, 'mom') % reuse the leadfield that was previously computed but don't project lf = dip.leadfield{i}; elseif isfield(dip, 'leadfield') && ~isfield(dip, 'mom') % reuse the leadfield that was previously computed lf = dip.leadfield{i}; elseif ~isfield(dip, 'leadfield') && isfield(dip, 'mom') % compute the leadfield for a fixed dipole orientation lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam) * dip.mom(:,i); else % compute the leadfield lf = ft_compute_leadfield(dip.pos(i,:), grad, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam); end if isfield(dip, 'subspace') % do subspace projection of the forward model lf = dip.subspace{i} * lf; % the data and the covariance become voxel dependent due to the projection dat = dip.subspace{i} * dat_pre_subspace; Cy = dip.subspace{i} * (Cy_pre_subspace + lambda * eye(size(Cy_pre_subspace))) * dip.subspace{i}'; invCy = pinv(dip.subspace{i} * (Cy_pre_subspace + lambda * eye(size(Cy_pre_subspace))) * dip.subspace{i}'); elseif ~isempty(subspace) % do subspace projection of the forward model only lforig = lf; lf = subspace * lf; % according to Kensuke's paper, the eigenspace bf boils down to projecting % the 'traditional' filter onto the subspace % spanned by the first k eigenvectors [u,s,v] = svd(Cy); filt = ESES*filt; % ESES = u(:,1:k)*u(:,1:k)'; % however, even though it seems that the shape of the filter is identical to % the shape it is obtained with the following code, the w*lf=I does not hold. end if fixedori % compute the leadfield for the optimal dipole orientation % subsequently the leadfield for only that dipole orientation will be used for the final filter computation % filt = pinv(lf' * invCy * lf) * lf' * invCy; % [u, s, v] = svd(real(filt * Cy * ctranspose(filt))); % in this step the filter computation is not necessary, use the quick way to compute the voxel level covariance (cf. van Veen 1997) [u, s, v] = svd(real(pinv(lf' * invCy *lf))); eta = u(:,1); lf = lf * eta; if ~isempty(subspace), lforig = lforig * eta; end dipout.ori{i} = eta; end if isfield(dip, 'filter') % use the provided filter filt = dip.filter{i}; else % construct the spatial filter filt = pinv(lf' * invCy * lf) * lf' * invCy; % van Veen eqn. 23, use PINV/SVD to cover rank deficient leadfield end if projectmom [u, s, v] = svd(filt * Cy * ctranspose(filt)); mom = u(:,1); filt = (mom') * filt; end if powlambda1 % dipout.pow(i) = lambda1(pinv(lf' * invCy * lf)); % this is more efficient if the filters are not present dipout.pow(i) = lambda1(filt * Cy * ctranspose(filt)); % this is more efficient if the filters are present elseif powtrace % dipout.pow(i) = trace(pinv(lf' * invCy * lf)); % this is more efficient if the filters are not present, van Veen eqn. 24 dipout.pow(i) = trace(filt * Cy * ctranspose(filt)); % this is more efficient if the filters are present end if keepcov % compute the source covariance matrix dipout.cov{i} = filt * Cy * ctranspose(filt); end if keepmom && ~isempty(dat) % estimate the instantaneous dipole moment at the current position dipout.mom{i} = filt * dat; end if projectnoise % estimate the power of the noise that is projected through the filter if powlambda1 dipout.noise(i) = noise * lambda1(filt * ctranspose(filt)); elseif powtrace dipout.noise(i) = noise * trace(filt * ctranspose(filt)); end if keepcov dipout.noisecov{i} = noise * filt * ctranspose(filt); end end if keepfilter if ~isempty(subspace) dipout.filter{i} = filt*subspace; %dipout.filter{i} = filt*pinv(subspace); else dipout.filter{i} = filt; end end if keepleadfield if ~isempty(subspace) dipout.leadfield{i} = lforig; else dipout.leadfield{i} = lf; end end ft_progress(i/size(dip.pos,1), 'scanning grid %d/%d\n', i, size(dip.pos,1)); end ft_progress('close'); dipout.inside = dip.originside; dipout.outside = dip.origoutside; dipout.pos = dip.origpos; % reassign the scan values over the inside and outside grid positions if isfield(dipout, 'leadfield') dipout.leadfield(dipout.inside) = dipout.leadfield; dipout.leadfield(dipout.outside) = {[]}; end if isfield(dipout, 'filter') dipout.filter(dipout.inside) = dipout.filter; dipout.filter(dipout.outside) = {[]}; end if isfield(dipout, 'mom') dipout.mom(dipout.inside) = dipout.mom; dipout.mom(dipout.outside) = {[]}; end if isfield(dipout, 'ori') dipout.ori(dipout.inside) = dipout.ori; dipout.ori(dipout.outside) = {[]}; end if isfield(dipout, 'cov') dipout.cov(dipout.inside) = dipout.cov; dipout.cov(dipout.outside) = {[]}; end if isfield(dipout, 'noisecov') dipout.noisecov(dipout.inside) = dipout.noisecov; dipout.noisecov(dipout.outside) = {[]}; end if isfield(dipout, 'pow') dipout.pow(dipout.inside) = dipout.pow; dipout.pow(dipout.outside) = nan; end if isfield(dipout, 'noise') dipout.noise(dipout.inside) = dipout.noise; dipout.noise(dipout.outside) = nan; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function to obtain the largest singular value %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function s = lambda1(x) % determine the largest singular value, which corresponds to the power along the dominant direction s = svd(x); s = s(1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function to compute the pseudo inverse. This is the same as the % standard Matlab function, except that the default tolerance is twice as % high. % Copyright 1984-2004 The MathWorks, Inc. % $Revision: 7123 $ $Date: 2009/03/23 21:14:42 $ % default tolerance increased by factor 2 (Robert Oostenveld, 7 Feb 2004) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function X = pinv(A,varargin) [m,n] = size(A); if n > m X = pinv(A',varargin{:})'; else [U,S,V] = svd(A,0); if m > 1, s = diag(S); elseif m == 1, s = S(1); else s = 0; end if nargin == 2 tol = varargin{1}; else tol = 10 * max(m,n) * max(s) * eps; end r = sum(s > tol); if (r == 0) X = zeros(size(A'),class(A)); else s = diag(ones(r,1)./s(1:r)); X = V(:,1:r)*s*U(:,1:r)'; end end
github
philippboehmsturm/antx-master
dipole_fit.m
.m
antx-master/xspm8/external/fieldtrip/inverse/dipole_fit.m
11,095
utf_8
3ed8bcfd404bb481eb98539a1e371239
function [dipout] = dipole_fit(dip, sens, vol, dat, varargin) % DIPOLE_FIT performs an equivalent current dipole fit with a single % or a small number of dipoles to explain an EEG or MEG scalp topography. % % Use as % [dipout] = dipole_fit(dip, sens, vol, dat, ...) % % Additional input arguments should be specified as key-value pairs and can include % 'constr' = Structure with constraints % 'display' = Level of display [ off | iter | notify | final ] % 'optimfun' = Function to use [fminsearch | fminunc ] % 'maxiter' = Maximum number of function evaluations allowed [ positive integer ] % 'metric' = Error measure to be minimised [ rv | var | abs ] % 'checkinside' = Boolean flag to check whether dipole is inside source compartment [ 0 | 1 ] % 'weight' = weight matrix for maximum likelihood estimation, e.g. inverse noise covariance % % The following optional input arguments relate to the computation of the leadfields % 'reducerank' = 'no' or number % 'normalize' = 'no', 'yes' or 'column' % 'normalizeparam' = parameter for depth normalization (default = 0.5) % % The maximum likelihood estimation implements % Lutkenhoner B. "Dipole source localization by means of maximum % likelihood estimation I. Theory and simulations" Electroencephalogr Clin % Neurophysiol. 1998 Apr;106(4):314-21. % Copyright (C) 2003-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: dipole_fit.m 7123 2012-12-06 21:21:38Z roboos $ % It is neccessary to provide backward compatibility support for the old function call % in case people want to use it in conjunction with EEGLAB and the dipfit1 plugin. % old style: function [dipout] = dipole_fit(dip, dat, sens, vol, constr), where constr is optional % new style: function [dipout] = dipole_fit(dip, sens, vol, dat, varargin), where varargin is in key-value pairs if nargin==4 && ~isstruct(sens) && isstruct(dat) % looks like old style, the order of the input arguments has to be changed warning('converting from old style input\n'); olddat = sens; oldsens = vol; oldvol = dat; dat = olddat; sens = oldsens; vol = oldvol; elseif nargin==5 && ~isstruct(sens) && isstruct(dat) % looks like old style, the order of the input arguments has to be changed % furthermore the additional constraint has to be fixed warning('converting from old style input\n'); olddat = sens; oldsens = vol; oldvol = dat; dat = olddat; sens = oldsens; vol = oldvol; varargin = {'constr', varargin{1}}; % convert into a key-value pair else % looks like new style, i.e. with optional key-value arguments % this is dealt with below end constr = keyval('constr', varargin); % default is not to have constraints metric = keyval('metric', varargin); if isempty(metric), metric = 'rv'; end checkinside = keyval('checkinside', varargin); if isempty(checkinside), checkinside = 0; end display = keyval('display', varargin); if isempty(display), display = 'iter'; end optimfun = keyval('optimfun', varargin); if isa(optimfun, 'char'), optimfun = str2fun(optimfun); end maxiter = keyval('maxiter', varargin); reducerank = keyval('reducerank', varargin); % for leadfield computation normalize = keyval('normalize' , varargin); % for leadfield computation normalizeparam = keyval('normalizeparam', varargin); % for leadfield computation weight = keyval('weight', varargin); % for maximum likelihood estimation if isempty(optimfun) % determine whether the Matlab Optimization toolbox is available and can be used if ft_hastoolbox('optim') optimfun = @fminunc; else optimfun = @fminsearch; end end if isempty(maxiter) % set a default for the maximum number of iterations, depends on the optimization function if isequal(optimfun, @fminunc) maxiter = 100; else maxiter = 500; end end % determine whether it is EEG or MEG iseeg = ft_senstype(sens, 'eeg'); ismeg = ft_senstype(sens, 'meg'); if ismeg && iseeg % this is something that I might implement in the future error('simultaneous EEG and MEG not supported'); elseif iseeg % ensure that the potential data is average referenced, just like the model potential dat = avgref(dat); end % ensure correct dipole position and moment specification dip = fixdipole(dip); % reformat the position parameters in case of multiple dipoles, this % should result in the matrix changing from [x1 y1 z1; x2 y2 z2] to % [x1 y1 z1 x2 y2 z2] for the constraints to work numdip = size(dip.pos, 1); param = dip.pos'; param = param(:)'; % add the orientation to the nonlinear parameters if isfield(constr, 'fixedori') && constr.fixedori for i=1:numdip % add the orientation to the list of parameters [th, phi, r] = cart2sph(dip.mom(1,i), dip.mom(2,i), dip.mom(3,i)); param = [param th phi]; end end % reduce the number of parameters to be fitted according to the constraints if isfield(constr, 'mirror') param = param(constr.reduce); end % set the parameters for the optimization function if isequal(optimfun, @fminunc) options = optimset(... 'TolFun',1e-9,... 'TypicalX',ones(size(param)),... 'LargeScale','off',... 'HessUpdate','bfgs',... 'MaxIter',maxiter,... 'MaxFunEvals',2*maxiter*length(param),... 'Display',display); elseif isequal(optimfun, @fminsearch) options = optimset(... 'MaxIter',maxiter,... 'MaxFunEvals',2*maxiter*length(param),... 'Display',display); else warning('unknown optimization function "%s", using default parameters', func2str(optimfun)); end % perform the optimization with either the fminsearch or fminunc function [param, fval, exitflag, output] = optimfun(@dipfit_error, param, options, dat, sens, vol, constr, metric, checkinside, reducerank, normalize, normalizeparam, weight); if exitflag==0 error('Maximum number of iterations exceeded before reaching the minimum, please try with another initial guess.') end % do linear optimization of dipole moment parameters [err, mom] = dipfit_error(param, dat, sens, vol, constr, metric, checkinside, reducerank, normalize, normalizeparam, weight); % expand the number of parameters according to the constraints if isfield(constr, 'mirror') param = constr.mirror .* param(constr.expand); end % get the dipole position and orientation if isfield(constr, 'fixedori') && constr.fixedori numdip = numel(param)/5; ori = zeros(3,numdip); for i=1:numdip th = param(end-(2*i)+1); phi = param(end-(2*i)+2); [ori(1,i), ori(2,i), ori(3,i)] = sph2cart(th, phi, 1); end pos = reshape(param(1:(numdip*3)), 3, numdip)'; else numdip = numel(param)/3; pos = reshape(param, 3, numdip)'; end % return the optimal dipole parameters dipout.pos = pos; if isfield(constr, 'fixedori') && constr.fixedori dipout.mom = ori; % dipole orientation as vector dipout.ampl = mom; % dipole strength else dipout.mom = mom; % dipole moment as vector or matrix, which represents both the orientation and strength as vector end % ensure correct dipole position and moment specification dipout = fixdipole(dipout); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % DIPFIT_ERROR computes the error between measured and model data % and can be used for non-linear fitting of dipole position %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [err, mom] = dipfit_error(param, dat, sens, vol, constr, metric, checkinside, reducerank, normalize, normalizeparam, weight) % flush pending graphics events, ensure that fitting is interruptible drawnow; if ~isempty(get(0, 'currentfigure')) && strcmp(get(gcf, 'tag'), 'stop') % interrupt the fitting close; error('USER ABORT'); end; % expand the number of parameters according to the constraints if isfield(constr, 'mirror') param = constr.mirror .* param(constr.expand); end % get the dipole positions and optionally also the orientation if isfield(constr, 'fixedori') && constr.fixedori numdip = numel(param)/5; ori = zeros(3,numdip); for i=1:numdip th = param(end-(2*i)+1); phi = param(end-(2*i)+2); [ori(1,i), ori(2,i), ori(3,i)] = sph2cart(th, phi, 1); end pos = reshape(param(1:(numdip*3)), 3, numdip)'; else numdip = numel(param)/3; pos = reshape(param, 3, numdip)'; end % check whether the dipole is inside the source compartment if checkinside inside = ft_inside_vol(pos, vol); if ~all(inside) error('Dipole is outside the source compartment'); end end % construct the leadfield matrix for all dipoles lf = ft_compute_leadfield(pos, sens, vol, 'reducerank', reducerank, 'normalize', normalize, 'normalizeparam', normalizeparam); if isfield(constr, 'fixedori') && constr.fixedori lf = lf * ori; end % compute the optimal dipole moment and the model error if ~isempty(weight) % maximum likelihood estimation using the weigth matrix mom = pinv(lf'*weight*lf)*lf'*weight*dat; % Lutkenhoner equation 5 dif = dat - lf*mom; % compute the generalized goodness-of-fit measure switch metric case 'rv' % relative residual variance num = dif' * weight * dif; denom = dat' * weight * dat; err = sum(num(:)) ./ sum(denom(:)); % Lutkenhonner equation 7, except for the gof=1-rv case 'var' % residual variance num = dif' * weight * dif'; err = sum(num(:)); otherwise error('Unsupported error metric for maximum likelihood dipole fitting'); end else % ordinary least squares, this is the same as MLE with weight=eye(nchans,nchans) mom = pinv(lf)*dat; dif = dat - lf*mom; % compute the ordinary goodness-of-fit measures switch metric case 'rv' % relative residual variance err = sum(dif(:).^2) / sum(dat(:).^2); case 'var' % residual variance err = sum(dif(:).^2); case 'abs' % absolute difference err = sum(abs(dif)); otherwise error('Unsupported error metric for dipole fitting'); end end if ~isreal(err) % this happens for complex valued data, i.e. when fitting a dipole to spectrally decomposed data % the error function should return a positive valued real number, otherwise fminunc fails err = abs(err); end
github
philippboehmsturm/antx-master
ft_hastoolbox.m
.m
antx-master/xspm8/external/fieldtrip/inverse/private/ft_hastoolbox.m
21,701
utf_8
7141791b922e3b46334b4d5888532adf
function [status] = ft_hastoolbox(toolbox, autoadd, silent) % FT_HASTOOLBOX tests whether an external toolbox is installed. Optionally % it will try to determine the path to the toolbox and install it % automatically. % % Use as % [status] = ft_hastoolbox(toolbox, autoadd, silent) % % autoadd = 0 means that it will not be added % autoadd = 1 means that give an error if it cannot be added % autoadd = 2 means that give a warning if it cannot be added % autoadd = 3 means that it remains silent if it cannot be added % % silent = 0 means that it will give some feedback about adding the toolbox % silent = 1 means that it will not give feedback % Copyright (C) 2005-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_hastoolbox.m 7172 2012-12-13 11:50:49Z roboos $ % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before % persistent previous previouspath % % if ~isequal(previouspath, path) % previous = []; % end % % if isempty(previous) % previous = struct; % elseif isfield(previous, fixname(toolbox)) % status = previous.(fixname(toolbox)); % return % end % this points the user to the website where he/she can download the toolbox url = { 'AFNI' 'see http://afni.nimh.nih.gov' 'DSS' 'see http://www.cis.hut.fi/projects/dss' 'EEGLAB' 'see http://www.sccn.ucsd.edu/eeglab' 'NWAY' 'see http://www.models.kvl.dk/source/nwaytoolbox' 'SPM99' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM2' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM5' 'see http://www.fil.ion.ucl.ac.uk/spm' 'SPM8' 'see http://www.fil.ion.ucl.ac.uk/spm' 'MEG-PD' 'see http://www.kolumbus.fi/kuutela/programs/meg-pd' 'MEG-CALC' 'this is a commercial toolbox from Neuromag, see http://www.neuromag.com' 'BIOSIG' 'see http://biosig.sourceforge.net' 'EEG' 'see http://eeg.sourceforge.net' 'EEGSF' 'see http://eeg.sourceforge.net' % alternative name 'MRI' 'see http://eeg.sourceforge.net' % alternative name 'NEUROSHARE' 'see http://www.neuroshare.org' 'BESA' 'see http://www.megis.de, or contact Karsten Hoechstetter' 'EEPROBE' 'see http://www.ant-neuro.com, or contact Maarten van der Velde' 'YOKOGAWA' 'this is deprecated, please use YOKOGAWA_MEG_READER instead' 'YOKOGAWA_MEG_READER' 'see http://www.yokogawa.com/me/me-login-en.htm' 'BEOWULF' 'see http://robertoostenveld.nl, or contact Robert Oostenveld' 'MENTAT' 'see http://robertoostenveld.nl, or contact Robert Oostenveld' 'SON2' 'see http://www.kcl.ac.uk/depsta/biomedical/cfnr/lidierth.html, or contact Malcolm Lidierth' '4D-VERSION' 'contact Christian Wienbruch' 'SIGNAL' 'see http://www.mathworks.com/products/signal' 'OPTIM' 'see http://www.mathworks.com/products/optim' 'IMAGE' 'see http://www.mathworks.com/products/image' % Mathworks refers to this as IMAGES 'SPLINES' 'see http://www.mathworks.com/products/splines' 'DISTCOMP' 'see http://www.mathworks.nl/products/parallel-computing/' 'COMPILER' 'see http://www.mathworks.com/products/compiler' 'FASTICA' 'see http://www.cis.hut.fi/projects/ica/fastica' 'BRAINSTORM' 'see http://neuroimage.ucs.edu/brainstorm' 'FILEIO' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PREPROC' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'FORWARD' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'INVERSE' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'SPECEST' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'REALTIME' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'SPIKE' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'CONNECTIVITY' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PEER' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'PLOTTING' 'see http://www.ru.nl/neuroimaging/fieldtrip' 'DENOISE' 'see http://lumiere.ens.fr/Audition/adc/meg, or contact Alain de Cheveigne' 'BCI2000' 'see http://bci2000.org' 'NLXNETCOM' 'see http://www.neuralynx.com' 'DIPOLI' 'see ftp://ftp.fcdonders.nl/pub/fieldtrip/external' 'MNE' 'see http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php' 'TCP_UDP_IP' 'see http://www.mathworks.com/matlabcentral/fileexchange/345, or contact Peter Rydesaeter' 'BEMCP' 'contact Christophe Phillips' 'OPENMEEG' 'see http://gforge.inria.fr/projects/openmeeg and http://gforge.inria.fr/frs/?group_id=435' 'PRTOOLS' 'see http://www.prtools.org' 'ITAB' 'contact Stefania Della Penna' 'BSMART' 'see http://www.brain-smart.org' 'PEER' 'see http://fieldtrip.fcdonders.nl/development/peer' 'FREESURFER' 'see http://surfer.nmr.mgh.harvard.edu/fswiki' 'SIMBIO' 'see https://www.mrt.uni-jena.de/simbio/index.php/Main_Page' 'VGRID' 'see http://www.rheinahrcampus.de/~medsim/vgrid/manual.html' 'FNS' 'see http://hhvn.nmsu.edu/wiki/index.php/FNS' 'GIFTI' 'see http://www.artefact.tk/software/matlab/gifti' 'XML4MAT' 'see http://www.mathworks.com/matlabcentral/fileexchange/6268-xml4mat-v2-0' 'SQDPROJECT' 'see http://www.isr.umd.edu/Labs/CSSL/simonlab' 'BCT' 'see http://www.brain-connectivity-toolbox.net/' 'CCA' 'see http://www.imt.liu.se/~magnus/cca or contact Magnus Borga' 'EGI_MFF' 'see http://www.egi.com/ or contact either Phan Luu or Colin Davey at EGI' 'TOOLBOX_GRAPH' 'see http://www.mathworks.com/matlabcentral/fileexchange/5355-toolbox-graph or contact Gabriel Peyre' 'NETCDF' 'see http://www.mathworks.com/matlabcentral/fileexchange/15177' 'MYSQL' 'see http://www.mathworks.com/matlabcentral/fileexchange/8663-mysql-database-connector' 'ISO2MESH' 'see http://iso2mesh.sourceforge.net/cgi-bin/index.cgi?Home or contact Qianqian Fang' 'DATAHASH' 'see http://www.mathworks.com/matlabcentral/fileexchange/31272' 'IBTB' 'see http://www.ibtb.org' 'ICASSO' 'see http://www.cis.hut.fi/projects/ica/icasso' 'XUNIT' 'see http://www.mathworks.com/matlabcentral/fileexchange/22846-matlab-xunit-test-framework' 'PLEXON' 'available from http://www.plexon.com/assets/downloads/sdk/ReadingPLXandDDTfilesinMatlab-mexw.zip' }; if nargin<2 % default is not to add the path automatically autoadd = 0; end if nargin<3 % default is not to be silent silent = 0; end % determine whether the toolbox is installed toolbox = upper(toolbox); % set fieldtrip trunk path, used for determining ft-subdirs are on path fttrunkpath = unixpath(fileparts(which('ft_defaults'))); switch toolbox case 'AFNI' status = (exist('BrikLoad') && exist('BrikInfo')); case 'DSS' status = exist('denss', 'file') && exist('dss_create_state', 'file'); case 'EEGLAB' status = exist('runica', 'file'); case 'NWAY' status = exist('parafac', 'file'); case 'SPM' status = exist('spm.m'); % any version of SPM is fine case 'SPM99' status = exist('spm.m') && strcmp(spm('ver'),'SPM99'); case 'SPM2' status = exist('spm.m') && strcmp(spm('ver'),'SPM2'); case 'SPM5' status = exist('spm.m') && strcmp(spm('ver'),'SPM5'); case 'SPM8' status = exist('spm.m') && strncmp(spm('ver'),'SPM8', 4); case 'SPM12' status = exist('spm.m') && strncmp(spm('ver'),'SPM12', 5); case 'MEG-PD' status = (exist('rawdata') && exist('channames')); case 'MEG-CALC' status = (exist('megmodel') && exist('megfield') && exist('megtrans')); case 'BIOSIG' status = (exist('sopen') && exist('sread')); case 'EEG' status = (exist('ctf_read_res4') && exist('ctf_read_meg4')); case 'EEGSF' % alternative name status = (exist('ctf_read_res4') && exist('ctf_read_meg4')); case 'MRI' % other functions in the mri section status = (exist('avw_hdr_read') && exist('avw_img_read')); case 'NEUROSHARE' status = (exist('ns_OpenFile') && exist('ns_SetLibrary') && exist('ns_GetAnalogData')); case 'BESA' status = (exist('readBESAtfc') && exist('readBESAswf')); case 'EEPROBE' status = (exist('read_eep_avr') && exist('read_eep_cnt')); case 'YOKOGAWA' status = hasyokogawa('16bitBeta6'); case 'YOKOGAWA12BITBETA3' status = hasyokogawa('12bitBeta3'); case 'YOKOGAWA16BITBETA3' status = hasyokogawa('16bitBeta3'); case 'YOKOGAWA16BITBETA6' status = hasyokogawa('16bitBeta6'); case 'YOKOGAWA_MEG_READER' status = hasyokogawa('1.4'); case 'BEOWULF' status = (exist('evalwulf') && exist('evalwulf') && exist('evalwulf')); case 'MENTAT' status = (exist('pcompile') && exist('pfor') && exist('peval')); case 'SON2' status = (exist('SONFileHeader') && exist('SONChanList') && exist('SONGetChannel')); case '4D-VERSION' status = (exist('read4d') && exist('read4dhdr')); case {'STATS', 'STATISTICS'} status = license('checkout', 'statistics_toolbox'); % also check the availability of a toolbox license case {'OPTIM', 'OPTIMIZATION'} status = license('checkout', 'optimization_toolbox'); % also check the availability of a toolbox license case {'SPLINES', 'CURVE_FITTING'} status = license('checkout', 'curve_fitting_toolbox'); % also check the availability of a toolbox license case 'SIGNAL' status = license('checkout', 'signal_toolbox'); % also check the availability of a toolbox license case 'IMAGE' status = license('checkout', 'image_toolbox'); % also check the availability of a toolbox license case {'DCT', 'DISTCOMP'} status = license('checkout', 'distrib_computing_toolbox'); % also check the availability of a toolbox license case 'COMPILER' status = license('checkout', 'compiler'); % also check the availability of a toolbox license case 'FASTICA' status = exist('fpica', 'file'); case 'BRAINSTORM' status = exist('bem_xfer'); case 'DENOISE' status = (exist('tsr', 'file') && exist('sns', 'file')); case 'CTF' status = (exist('getCTFBalanceCoefs') && exist('getCTFdata')); case 'BCI2000' status = exist('load_bcidat'); case 'NLXNETCOM' status = (exist('MatlabNetComClient', 'file') && exist('NlxConnectToServer', 'file') && exist('NlxGetNewCSCData', 'file')); case 'DIPOLI' status = exist('dipoli.maci', 'file'); case 'MNE' status = (exist('fiff_read_meas_info', 'file') && exist('fiff_setup_read_raw', 'file')); case 'TCP_UDP_IP' status = (exist('pnet', 'file') && exist('pnet_getvar', 'file') && exist('pnet_putvar', 'file')); case 'BEMCP' status = (exist('bem_Cij_cog', 'file') && exist('bem_Cij_lin', 'file') && exist('bem_Cij_cst', 'file')); case 'OPENMEEG' status = exist('om_save_tri.m', 'file'); case 'PRTOOLS' status = (exist('prversion', 'file') && exist('dataset', 'file') && exist('svc', 'file')); case 'ITAB' status = (exist('lcReadHeader', 'file') && exist('lcReadData', 'file')); case 'BSMART' status = exist('bsmart'); case 'FREESURFER' status = exist('MRIread', 'file') && exist('vox2ras_0to1', 'file'); case 'FNS' status = exist('elecsfwd', 'file'); case 'SIMBIO' status = exist('calc_stiff_matrix_val', 'file') && exist('sb_transfer', 'file'); case 'VGRID' status = exist('vgrid.m', 'file'); case 'GIFTI' status = exist('gifti', 'file'); case 'XML4MAT' status = exist('xml2struct.m', 'file') && exist('xml2whos.m', 'file'); case 'SQDPROJECT' status = exist('sqdread.m', 'file') && exist('sqdwrite.m', 'file'); case 'BCT' status = exist('macaque71.mat', 'file') && exist('motif4funct_wei.m', 'file'); case 'CCA' status = exist('ccabss.m', 'file'); case 'EGI_MFF' status = exist('mff_getObject.m', 'file') && exist('mff_getSummaryInfo.m', 'file'); case 'TOOLBOX_GRAPH' status = exist('toolbox_graph'); case 'NETCDF' status = exist('netcdf'); case 'MYSQL' status = exist(['mysql.' mexext], 'file'); % this only consists of a single mex file case 'ISO2MESH' status = exist('vol2surf.m', 'file') && exist('qmeshcut.m', 'file'); case 'QSUB' status = exist('qsubfeval.m', 'file') && exist('qsubcellfun.m', 'file'); case 'ENGINE' status = exist('enginefeval.m', 'file') && exist('enginecellfun.m', 'file'); case 'DATAHASH' status = exist('DataHash.m', 'file'); case 'IBTB' status = exist('make_ibtb.m', 'file') && exist('binr.m', 'file'); case 'ICASSO' status = exist('icassoEst.m', 'file'); case 'XUNIT' status = exist('initTestSuite.m', 'file') && exist('runtests.m', 'file'); case 'PLEXON' status = exist('plx_adchan_gains.m', 'file') && exist('mexPlex'); % the following are fieldtrip modules/toolboxes case 'FILEIO' status = (exist('ft_read_header', 'file') && exist('ft_read_data', 'file') && exist('ft_read_event', 'file') && exist('ft_read_sens', 'file')); case 'FORWARD' status = (exist('ft_compute_leadfield', 'file') && exist('ft_prepare_vol_sens', 'file')); case 'PLOTTING' status = (exist('ft_plot_topo', 'file') && exist('ft_plot_mesh', 'file') && exist('ft_plot_matrix', 'file')); case 'PEER' status = exist('peerslave', 'file') && exist('peermaster', 'file'); case 'CONNECTIVITY' status = exist('ft_connectivity_corr', 'file') && exist('ft_connectivity_granger', 'file'); case 'SPIKE' status = exist('ft_spiketriggeredaverage.m', 'file') && exist('ft_spiketriggeredspectrum.m', 'file'); % these were missing, added them using the below style, see bug 1804 - roevdmei case 'INVERSE' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/inverse'], 'once')); % INVERSE is not added above, consider doing it there -roevdmei case 'REALTIME' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/realtime'], 'once')); % REALTIME is not added above, consider doing it there -roevdmei case 'SPECEST' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/specest'], 'once')); % SPECEST is not added above, consider doing it there -roevdmei case 'PREPROC' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/preproc'], 'once')); % PREPROC is not added above, consider doing it there -roevdmei % the following are not proper toolboxes, but only subdirectories in the fieldtrip toolbox % these are added in ft_defaults and are specified with unix-style forward slashes case 'COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/compat'], 'once')); case 'STATFUN' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/statfun'], 'once')); case 'TRIALFUN' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/trialfun'], 'once')); case 'UTILITIES/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/utilities/compat'], 'once')); case 'FILEIO/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/fileio/compat'], 'once')); case 'PREPROC/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/preproc/compat'], 'once')); case 'FORWARD/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/forward/compat'], 'once')); case 'PLOTTING/COMPAT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/plotting/compat'], 'once')); case 'TEMPLATE/LAYOUT' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/layout'], 'once')); case 'TEMPLATE/ANATOMY' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/anatomy'], 'once')); case 'TEMPLATE/HEADMODEL' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/headmodel'], 'once')); case 'TEMPLATE/ELECTRODE' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/electrode'], 'once')); case 'TEMPLATE/NEIGHBOURS' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/neighbours'], 'once')); case 'TEMPLATE/SOURCEMODEL' status = ~isempty(regexp(unixpath(path), [fttrunkpath '/template/sourcemodel'], 'once')); otherwise if ~silent, warning('cannot determine whether the %s toolbox is present', toolbox); end status = 0; end % it should be a boolean value status = (status~=0); % try to determine the path of the requested toolbox if autoadd>0 && ~status % for core fieldtrip modules prefix = fileparts(which('ft_defaults')); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for external fieldtrip modules prefix = fullfile(fileparts(which('ft_defaults')), 'external'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for contributed fieldtrip extensions prefix = fullfile(fileparts(which('ft_defaults')), 'contrib'); if ~status status = myaddpath(fullfile(prefix, lower(toolbox)), silent); licensefile = [lower(toolbox) '_license']; if status && exist(licensefile, 'file') % this will execute openmeeg_license and mne_license % which display the license on screen for three seconds feval(licensefile); end end % for linux computers in the Donders Centre for Cognitive Neuroimaging prefix = '/home/common/matlab'; if ~status && isunix status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % for windows computers in the Donders Centre for Cognitive Neuroimaging prefix = 'h:\common\matlab'; if ~status && ispc status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end % use the matlab subdirectory in your homedirectory, this works on linux and mac prefix = fullfile(getenv('HOME'), 'matlab'); if ~status && isdir(prefix) status = myaddpath(fullfile(prefix, lower(toolbox)), silent); end if ~status % the toolbox is not on the path and cannot be added sel = find(strcmp(url(:,1), toolbox)); if ~isempty(sel) msg = sprintf('the %s toolbox is not installed, %s', toolbox, url{sel, 2}); else msg = sprintf('the %s toolbox is not installed', toolbox); end if autoadd==1 error(msg); elseif autoadd==2 warning(msg); else % fail silently end end end % this function is called many times in FieldTrip and associated toolboxes % use efficient handling if the same toolbox has been investigated before if status previous.(fixname(toolbox)) = status; end % remember the previous path, allows us to determine on the next call % whether the path has been modified outise of this function previouspath = path; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = myaddpath(toolbox, silent) if isdeployed warning('cannot change path settings for %s in a compiled application', toolbox); elseif exist(toolbox, 'dir') if ~silent, ws = warning('backtrace', 'off'); warning('adding %s toolbox to your Matlab path', toolbox); warning(ws); % return to the previous warning level end addpath(toolbox); status = 1; else status = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function path = unixpath(path) path(path=='\') = '/'; % replace backward slashes with forward slashes %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % helper function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function status = hasfunction(funname, toolbox) try % call the function without any input arguments, which probably is inapropriate feval(funname); % it might be that the function without any input already works fine status = true; catch % either the function returned an error, or the function is not available % availability is influenced by the function being present and by having a % license for the function, i.e. in a concurrent licensing setting it might % be that all toolbox licenses are in use m = lasterror; if strcmp(m.identifier, 'MATLAB:license:checkouterror') if nargin>1 warning('the %s toolbox is available, but you don''t have a license for it', toolbox); else warning('the function ''%s'' is available, but you don''t have a license for it', funname); end status = false; elseif strcmp(m.identifier, 'MATLAB:UndefinedFunction') status = false; else % the function seems to be available and it gave an unknown error, % which is to be expected with inappropriate input arguments status = true; end end
github
philippboehmsturm/antx-master
subsasgn.m
.m
antx-master/xspm8/@nifti/subsasgn.m
14,541
utf_8
ffdb84b7956d93c2f9a0a980ccbe8a22
function obj = subsasgn(obj,subs,varargin) % Subscript assignment % See subsref for meaning of fields. % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: subsasgn.m 4136 2010-12-09 22:22:28Z guillaume $ switch subs(1).type, case {'.'}, if numel(obj)~=nargin-2, error('The number of outputs should match the number of inputs.'); end; objs = struct(obj); for i=1:length(varargin), val = varargin{i}; obji = nifti(objs(i)); obji = fun(obji,subs,val); objs(i) = struct(obji); end; obj = nifti(objs); case {'()'}, objs = struct(obj); if length(subs)>1, t = subsref(objs,subs(1)); % A lot of this stuff is a little flakey, and may cause Matlab to bomb. % %if numel(t) ~= nargin-2, % error('The number of outputs should match the number of inputs.'); %end; for i=1:numel(t), val = varargin{1}; obji = nifti(t(i)); obji = subsasgn(obji,subs(2:end),val); t(i) = struct(obji); end; objs = subsasgn(objs,subs(1),t); else if numel(varargin)>1, error('Illegal right hand side in assignment. Too many elements.'); end; val = varargin{1}; if isa(val,'nifti'), objs = subsasgn(objs,subs,struct(val)); elseif isempty(val), objs = subsasgn(objs,subs,[]); else error('Assignment between unlike types is not allowed.'); end; end; obj = nifti(objs); otherwise error('Cell contents reference from a non-cell array object.'); end; return; %======================================================================= %======================================================================= function obj = fun(obj,subs,val) % Subscript referencing switch subs(1).type, case {'.'}, objs = struct(obj); for ii=1:numel(objs) obj = objs(ii); if any(strcmpi(subs(1).subs,{'dat'})), if length(subs)>1, val = subsasgn(obj.dat,subs(2:end),val); end; obj = assigndat(obj,val); objs(ii) = obj; continue; end; if isempty(obj.hdr), obj.hdr = empty_hdr; end; if ~isfield(obj.hdr,'magic'), error('Not a NIFTI-1 header'); end; if length(subs)>1, % && ~strcmpi(subs(1).subs,{'raw','dat'}), val0 = subsref(nifti(obj),subs(1)); val1 = subsasgn(val0,subs(2:end),val); else val1 = val; end; switch(subs(1).subs) case {'extras'} if length(subs)>1, obj.extras = subsasgn(obj.extras,subs(2:end),val); else obj.extras = val; end; case {'mat0'} if ~isnumeric(val1) || ndims(val1)~=2 || any(size(val1)~=[4 4]) || sum((val1(4,:)-[0 0 0 1]).^2)>1e-8, error('"mat0" should be a 4x4 matrix, with a last row of 0,0,0,1.'); end; if obj.hdr.qform_code==0, obj.hdr.qform_code=2; end; s = double(bitand(obj.hdr.xyzt_units,7)); if s d = findindict(s,'units'); val1 = diag([[1 1 1]/d.rescale 1])*val1; end; obj.hdr = encode_qform0(double(val1), obj.hdr); case {'mat0_intent'} if isempty(val1), obj.hdr.qform_code = 0; else if ~ischar(val1) && ~(isnumeric(val1) && numel(val1)==1), error('"mat0_intent" should be a string or a scalar.'); end; d = findindict(val1,'xform'); if ~isempty(d) obj.hdr.qform_code = d.code; end; end; case {'mat'} if ~isnumeric(val1) || ndims(val1)~=2 || any(size(val1)~=[4 4]) || sum((val1(4,:)-[0 0 0 1]).^2)>1e-8 error('"mat" should be a 4x4 matrix, with a last row of 0,0,0,1.'); end; if obj.hdr.sform_code==0, obj.hdr.sform_code=2; end; s = double(bitand(obj.hdr.xyzt_units,7)); if s d = findindict(s,'units'); val1 = diag([[1 1 1]/d.rescale 1])*val1; end; val1 = val1 * [eye(4,3) [1 1 1 1]']; obj.hdr.srow_x = val1(1,:); obj.hdr.srow_y = val1(2,:); obj.hdr.srow_z = val1(3,:); case {'mat_intent'} if isempty(val1), obj.hdr.sform_code = 0; else if ~ischar(val1) && ~(isnumeric(val1) && numel(val1)==1), error('"mat_intent" should be a string or a scalar.'); end; d = findindict(val1,'xform'); if ~isempty(d), obj.hdr.sform_code = d.code; end; end; case {'intent'} if ~valid_fields(val1,{'code','param','name'}) obj.hdr.intent_code = 0; obj.hdr.intent_p1 = 0; obj.hdr.intent_p2 = 0; obj.hdr.intent_p3 = 0; obj.hdr.intent_name = ''; else if ~isfield(val1,'code'), val1.code = obj.hdr.intent_code; end; d = findindict(val1.code,'intent'); if ~isempty(d), obj.hdr.intent_code = d.code; if isfield(val1,'param'), prm = [double(val1.param(:)) ; 0 ; 0; 0]; prm = [prm(1:length(d.param)) ; 0 ; 0; 0]; obj.hdr.intent_p1 = prm(1); obj.hdr.intent_p2 = prm(2); obj.hdr.intent_p3 = prm(3); end; if isfield(val1,'name'), obj.hdr.intent_name = val1.name; end; end; end; case {'diminfo'} if ~valid_fields(val1,{'frequency','phase','slice','slice_time'}) tmp = obj.hdr.dim_info; for bit=1:6, tmp = bitset(tmp,bit,0); end; obj.hdr.dim_info = tmp; obj.hdr.slice_start = 0; obj.hdr.slice_end = 0; obj.hdr.slice_duration = 0; obj.hdr.slice_code = 0; else if isfield(val1,'frequency'), tmp = val1.frequency; if ~isnumeric(tmp) || numel(tmp)~=1 || tmp<0 || tmp>3, error('Invalid frequency direction'); end; obj.hdr.dim_info = bitset(obj.hdr.dim_info,1,bitget(tmp,1)); obj.hdr.dim_info = bitset(obj.hdr.dim_info,2,bitget(tmp,2)); end; if isfield(val1,'phase'), tmp = val1.phase; if ~isnumeric(tmp) || numel(tmp)~=1 || tmp<0 || tmp>3, error('Invalid phase direction'); end; obj.hdr.dim_info = bitset(obj.hdr.dim_info,3,bitget(tmp,1)); obj.hdr.dim_info = bitset(obj.hdr.dim_info,4,bitget(tmp,2)); end; if isfield(val1,'slice'), tmp = val1.slice; if ~isnumeric(tmp) || numel(tmp)~=1 || tmp<0 || tmp>3, error('Invalid slice direction'); end; obj.hdr.dim_info = bitset(obj.hdr.dim_info,5,bitget(tmp,1)); obj.hdr.dim_info = bitset(obj.hdr.dim_info,6,bitget(tmp,2)); end; if isfield(val1,'slice_time') tim = val1.slice_time; if ~valid_fields(tim,{'start','end','duration','code'}), obj.hdr.slice_code = 0; obj.hdr.slice_start = 0; obj.hdr.end_slice = 0; obj.hdr.slice_duration = 0; else % sld = double(bitget(obj.hdr.dim_info,5)) + 2*double(bitget(obj.hdr.dim_info,6)); if isfield(tim,'start'), ss = double(tim.start); if isnumeric(ss) && numel(ss)==1 && ~rem(ss,1), % && ss>=1 && ss<=obj.hdr.dim(sld+1) obj.hdr.slice_start = ss-1; else error('Inappropriate "slice_time.start".'); end; end; if isfield(tim,'end'), ss = double(tim.end); if isnumeric(ss) && numel(ss)==1 && ~rem(ss,1), % && ss>=1 && ss<=obj.hdr.dim(sld+1) obj.hdr.slice_end = ss-1; else error('Inappropriate "slice_time.end".'); end; end; if isfield(tim,'duration') sd = double(tim.duration); if isnumeric(sd) && numel(sd)==1, s = double(bitand(obj.hdr.xyzt_units,24)); d = findindict(s,'units'); if ~isempty(d) && d.rescale, sd = sd/d.rescale; end; obj.hdr.slice_duration = sd; else error('Inappropriate "slice_time.duration".'); end; end; if isfield(tim,'code'), d = findindict(tim.code,'sliceorder'); if ~isempty(d), obj.hdr.slice_code = d.code; end; end; end; end; end; case {'timing'} if ~valid_fields(val1,{'toffset','tspace'}), obj.hdr.pixdim(5) = 0; obj.hdr.toffset = 0; else s = double(bitand(obj.hdr.xyzt_units,24)); d = findindict(s,'units'); if isfield(val1,'toffset'), if isnumeric(val1.toffset) && numel(val1.toffset)==1, if d.rescale, val1.toffset = val1.toffset/d.rescale; end; obj.hdr.toffset = val1.toffset; else error('"timing.toffset" needs to be numeric with 1 element'); end; end; if isfield(val1,'tspace'), if isnumeric(val1.tspace) && numel(val1.tspace)==1, if d.rescale, val1.tspace = val1.tspace/d.rescale; end; obj.hdr.pixdim(5) = val1.tspace; else error('"timing.tspace" needs to be numeric with 1 element'); end; end; end; case {'descrip'} if isempty(val1), val1 = char(val1); end; if ischar(val1), obj.hdr.descrip = val1; else error('"descrip" must be a string.'); end; case {'cal'} if isempty(val1), obj.hdr.cal_min = 0; obj.hdr.cal_max = 0; else if isnumeric(val1) && numel(val1)==2, obj.hdr.cal_min = val1(1); obj.hdr.cal_max = val1(2); else error('"cal" should contain two elements.'); end; end; case {'aux_file'} if isempty(val1), val1 = char(val1); end; if ischar(val1), obj.hdr.aux_file = val1; else error('"aux_file" must be a string.'); end; case {'hdr'} error('hdr is a read-only field.'); obj.hdr = val1; otherwise error(['Reference to non-existent field ''' subs(1).subs '''.']); end; objs(ii) = obj; end obj = nifti(objs); otherwise error('This should not happen.'); end; return; %======================================================================= %======================================================================= function obj = assigndat(obj,val) if isa(val,'file_array'), sz = size(val); if numel(sz)>7, error('Too many dimensions in data.'); end; sz = [sz 1 1 1 1 1 1 1]; sz = sz(1:7); sval = struct(val); d = findindict(sval.dtype,'dtype'); if isempty(d) error(['Unknown datatype (' num2str(double(sval.datatype)) ').']); end; [pth,nam,suf] = fileparts(sval.fname); if any(strcmp(suf,{'.img','.IMG'})) val.offset = max(sval.offset,0); obj.hdr.magic = ['ni1' char(0)]; elseif any(strcmp(suf,{'.nii','.NII'})) val.offset = max(sval.offset,352); obj.hdr.magic = ['n+1' char(0)]; else error(['Unknown filename extension (' suf ').']); end; val.offset = (ceil(val.offset/16))*16; obj.hdr.vox_offset = val.offset; obj.hdr.dim(2:(numel(sz)+1)) = sz; nd = max(find(obj.hdr.dim(2:end)>1)); if isempty(nd), nd = 3; end; obj.hdr.dim(1) = nd; obj.hdr.datatype = sval.dtype; obj.hdr.bitpix = d.size*8; if ~isempty(sval.scl_slope), obj.hdr.scl_slope = sval.scl_slope; end; if ~isempty(sval.scl_inter), obj.hdr.scl_inter = sval.scl_inter; end; obj.dat = val; else error('"raw" must be of class "file_array"'); end; return; function ok = valid_fields(val,allowed) if isempty(val), ok = false; return; end; if ~isstruct(val), error(['Expecting a structure, not a ' class(val) '.']); end; fn = fieldnames(val); for ii=1:length(fn), if ~any(strcmpi(fn{ii},allowed)), fprintf('Allowed fieldnames are:\n'); for i=1:length(allowed), fprintf(' %s\n', allowed{i}); end; error(['"' fn{ii} '" is not a valid fieldname.']); end end ok = true; return;
github
philippboehmsturm/antx-master
subsref.m
.m
antx-master/xspm8/@nifti/subsref.m
8,741
utf_8
2d67123e4dc7e0b20a7ee19962324fee
function varargout = subsref(opt,subs) % Subscript referencing % % Fields are: % dat - a file-array representing the image data % mat0 - a 9-parameter affine transform (from qform0) % Note that the mapping is from voxels (where the first % is considered to be at [1,1,1], to millimetres. See % mat0_interp for the meaning of the transform. % mat - a 12-parameter affine transform (from sform0) % Note that the mapping is from voxels (where the first % is considered to be at [1,1,1], to millimetres. See % mat1_interp for the meaning of the transform. % mat_intent - intention of mat. This field may be missing/empty. % mat0_intent - intention of mat0. This field may be missing/empty. % intent - interpretation of image. When present, this structure % contains the fields % code - name of interpretation % params - parameters needed to interpret the image % diminfo - MR encoding of different dimensions. This structure may % contain some or all of the following fields % frequency - a value of 1-3 indicating frequency direction % phase - a value of 1-3 indicating phase direction % slice - a value of 1-3 indicating slice direction % slice_time - only present when "slice" field is present. % Contains the following fields % code - ascending/descending etc % start - starting slice number % end - ending slice number % duration - duration of each slice acquisition % Setting frequency, phase or slice to 0 will remove it. % timing - timing information. When present, contains the fields % toffset - acquisition time of first volume (seconds) % tspace - time between sucessive volumes (seconds) % descrip - a brief description of the image % cal - a two-element vector containing cal_min and cal_max % aux_file - name of an auxiliary file % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: subsref.m 4136 2010-12-09 22:22:28Z guillaume $ varargout = rec(opt,subs); return; function c = rec(opt,subs) switch subs(1).type, case {'.'}, c = {}; opts = struct(opt); for ii=1:numel(opts) opt = nifti(opts(ii)); %if ~isstruct(opt) % error('Attempt to reference field of non-structure array.'); %end; h = opt.hdr; if isempty(h), %error('No header.'); h = empty_hdr; end; % NIFTI-1 FORMAT switch(subs(1).subs) case 'extras', t = opt.extras; case 'raw', % A hidden field if isa(opt.dat,'file_array'), tmp = struct(opt.dat); tmp.scl_slope = []; tmp.scl_inter = []; t = file_array(tmp); else t = opt.dat; end; case 'dat', t = opt.dat; case 'mat0', t = decode_qform0(h); s = double(bitand(h.xyzt_units,7)); if s d = findindict(s,'units'); if ~isempty(d) t = diag([d.rescale*[1 1 1] 1])*t; end; end; case 'mat0_intent', d = findindict(h.qform_code,'xform'); if isempty(d) || d.code==0, t = ''; else t = d.label; end; case 'mat', if h.sform_code > 0 t = double([h.srow_x ; h.srow_y ; h.srow_z ; 0 0 0 1]); t = t * [eye(4,3) [-1 -1 -1 1]']; else t = decode_qform0(h); end s = double(bitand(h.xyzt_units,7)); if s d = findindict(s,'units'); t = diag([d.rescale*[1 1 1] 1])*t; end; case 'mat_intent', if h.sform_code>0, t = h.sform_code; else t = h.qform_code; end; d = findindict(t,'xform'); if isempty(d) || d.code==0, t = ''; else t = d.label; end; case 'intent', d = findindict(h.intent_code,'intent'); if isempty(d) || d.code == 0, %t = struct('code','UNKNOWN','param',[]); t = []; else t = struct('code',d.label,'param',... double([h.intent_p1 h.intent_p2 h.intent_p3]), 'name',deblank(h.intent_name)); t.param = t.param(1:length(d.param)); end case 'diminfo', t = []; tmp = bitand( h.dim_info ,3); if tmp, t.frequency = double(tmp); end; tmp = bitand(bitshift(h.dim_info,-2),3); if tmp, t.phase = double(tmp); end; tmp = bitand(bitshift(h.dim_info,-4),3); if tmp, t.slice = double(tmp); end; % t = struct('frequency',bitand( h.dim_info ,3),... % 'phase',bitand(bitshift(h.dim_info,-2),3),... % 'slice',bitand(bitshift(h.dim_info,-4),3)) if isfield(t,'slice') sc = double(h.slice_code); ss = double(h.slice_start)+1; se = double(h.slice_end)+1; ss = max(ss,1); se = min(se,double(h.dim(t.slice+1))); sd = double(h.slice_duration); s = double(bitand(h.xyzt_units,24)); d = findindict(s,'units'); if d.rescale, sd = sd*d.rescale; end; ns = (se-ss+1); d = findindict(sc,'sliceorder'); if isempty(d) label = 'UNKNOWN'; else label = d.label; end; t.slice_time = struct('code',label,'start',ss,'end',se,'duration',sd); if 0, % Never t.times = zeros(1,double(h.dim(t.slice+1)))+NaN; switch sc, case 0, % Unknown t.times(ss:se) = zeros(1,ns); case 1, % sequential increasing t.times(ss:se) = (0:(ns-1))*sd; case 2, % sequential decreasing t.times(ss:se) = ((ns-1):-1:0)*sd; case 3, % alternating increasing t.times(ss:2:se) = (0:floor((ns+1)/2-1))*sd; t.times((ss+1):2:se) = (floor((ns+1)/2):(ns-1))*sd; case 4, % alternating decreasing t.times(se:-2:ss) = (0:floor((ns+1)/2-1))*sd; t.times(se:-2:(ss+1)) = (floor((ns+1)/2):(ns-1))*sd; end; end; end; case 'timing', to = double(h.toffset); dt = double(h.pixdim(5)); if to==0 && dt==0, t = []; else s = double(bitand(h.xyzt_units,24)); d = findindict(s,'units'); if d.rescale, to = to*d.rescale; dt = dt*d.rescale; end; t = struct('toffset',to,'tspace',dt); end; case 'descrip', t = deblank(h.descrip); msk = find(t==0); if any(msk), t=t(1:(msk(1)-1)); end; case 'cal', t = [double(h.cal_min) double(h.cal_max)]; if all(t==0), t = []; end; case 'aux_file', t = deblank(h.aux_file); case 'hdr', % Hidden field t = h; otherwise error(['Reference to non-existent field ''' subs(1).subs '''.']); end; if numel(subs)>1, t = subsref(t,subs(2:end)); end; c{ii} = t; end; case {'{}'}, error('Cell contents reference from a non-cell array object.'); case {'()'}, opt = struct(opt); t = subsref(opt,subs(1)); if length(subs)>1 c = {}; for i=1:numel(t), ti = nifti(t(i)); ti = rec(ti,subs(2:end)); c = {c{:}, ti{:}}; end; else c = {nifti(t)}; end; otherwise error('This should not happen.'); end;
github
philippboehmsturm/antx-master
create.m
.m
antx-master/xspm8/@nifti/create.m
1,963
utf_8
3c70cc73a693e9e93f4a3f3b60c91d1c
function create(obj,wrt) % Create a NIFTI-1 file % FORMAT create(obj) % This writes out the header information for the nifti object % % create(obj,wrt) % This also writes out an empty image volume if wrt==1 % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: create.m 1143 2008-02-07 19:33:33Z spm $ for i=1:numel(obj) create_each(obj(i)); end; function create_each(obj) if ~isa(obj.dat,'file_array'), error('Data must be a file-array'); end; fname = obj.dat.fname; if isempty(fname), error('No filename to write to.'); end; dt = obj.dat.dtype; ok = write_hdr_raw(fname,obj.hdr,dt(end-1)=='B'); if ~ok, error(['Unable to write header for "' fname '".']); end; write_extras(fname,obj.extras); if nargin>2 && any(wrt==1), % Create an empty image file if necessary d = findindict(obj.hdr.datatype, 'dtype'); dim = double(obj.hdr.dim(2:end)); dim((double(obj.hdr.dim(1))+1):end) = 1; nbytes = ceil(d.size*d.nelem*prod(dim(1:2)))*prod(dim(3:end))+double(obj.hdr.vox_offset); [pth,nam,ext] = fileparts(obj.dat.fname); if any(strcmp(deblank(obj.hdr.magic),{'n+1','nx1'})), ext = '.nii'; else ext = '.img'; end; iname = fullfile(pth,[nam ext]); fp = fopen(iname,'a+'); if fp==-1, error(['Unable to create image for "' fname '".']); end; fseek(fp,0,'eof'); pos = ftell(fp); if pos<nbytes, bs = 2048; % Buffer-size nbytes = nbytes - pos; buf = uint8(0); buf(bs) = 0; while(nbytes>0) if nbytes<bs, buf = buf(1:nbytes); end; nw = fwrite(fp,buf,'uint8'); if nw<min(bs,nbytes), fclose(fp); error(['Problem while creating image for "' fname '".']); end; nbytes = nbytes - nw; end; end; fclose(fp); end; return;
github
philippboehmsturm/antx-master
getdict.m
.m
antx-master/xspm8/@nifti/private/getdict.m
5,226
utf_8
94716c88e3d44be3c8207f14a928510a
function d = getdict % Dictionary of NIFTI stuff % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: getdict.m 1143 2008-02-07 19:33:33Z spm $ persistent dict; if ~isempty(dict), d = dict; return; end; % Datatype t = true; f = false; table = {... 0 ,'UNKNOWN' ,'uint8' ,@uint8 ,1,1 ,t,t,f 1 ,'BINARY' ,'uint1' ,@logical,1,1/8,t,t,f 256 ,'INT8' ,'int8' ,@int8 ,1,1 ,t,f,t 2 ,'UINT8' ,'uint8' ,@uint8 ,1,1 ,t,t,t 4 ,'INT16' ,'int16' ,@int16 ,1,2 ,t,f,t 512 ,'UINT16' ,'uint16' ,@uint16 ,1,2 ,t,t,t 8 ,'INT32' ,'int32' ,@int32 ,1,4 ,t,f,t 768 ,'UINT32' ,'uint32' ,@uint32 ,1,4 ,t,t,t 1024,'INT64' ,'int64' ,@int64 ,1,8 ,t,f,f 1280,'UINT64' ,'uint64' ,@uint64 ,1,8 ,t,t,f 16 ,'FLOAT32' ,'float32' ,@single ,1,4 ,f,f,t 64 ,'FLOAT64' ,'double' ,@double ,1,8 ,f,f,t 1536,'FLOAT128' ,'float128',@crash ,1,16 ,f,f,f 32 ,'COMPLEX64' ,'float32' ,@single ,2,4 ,f,f,f 1792,'COMPLEX128','double' ,@double ,2,8 ,f,f,f 2048,'COMPLEX256','float128',@crash ,2,16 ,f,f,f 128 ,'RGB24' ,'uint8' ,@uint8 ,3,1 ,t,t,f}; dtype = struct(... 'code' ,table(:,1),... 'label' ,table(:,2),... 'prec' ,table(:,3),... 'conv' ,table(:,4),... 'nelem' ,table(:,5),... 'size' ,table(:,6),... 'isint' ,table(:,7),... 'unsigned' ,table(:,8),... 'min',-Inf,'max',Inf',... 'supported',table(:,9)); for i=1:length(dtype), if dtype(i).isint if dtype(i).unsigned dtype(i).min = 0; dtype(i).max = 2^(8*dtype(i).size)-1; else dtype(i).min = -2^(8*dtype(i).size-1); dtype(i).max = 2^(8*dtype(i).size-1)-1; end; end; end; % Intent table = {... 0 ,'NONE' ,'None',{} 2 ,'CORREL' ,'Correlation statistic',{'DOF'} 3 ,'TTEST' ,'T-statistic',{'DOF'} 4 ,'FTEST' ,'F-statistic',{'numerator DOF','denominator DOF'} 5 ,'ZSCORE' ,'Z-score',{} 6 ,'CHISQ' ,'Chi-squared distribution',{'DOF'} 7 ,'BETA' ,'Beta distribution',{'a','b'} 8 ,'BINOM' ,'Binomial distribution',... {'number of trials','probability per trial'} 9 ,'GAMMA' ,'Gamma distribution',{'shape','scale'} 10 ,'POISSON' ,'Poisson distribution',{'mean'} 11 ,'NORMAL' ,'Normal distribution',{'mean','standard deviation'} 12 ,'FTEST_NONC' ,'F-statistic noncentral',... {'numerator DOF','denominator DOF','numerator noncentrality parameter'} 13 ,'CHISQ_NONC' ,'Chi-squared noncentral',{'DOF','noncentrality parameter'} 14 ,'LOGISTIC' ,'Logistic distribution',{'location','scale'} 15 ,'LAPLACE' ,'Laplace distribution',{'location','scale'} 16 ,'UNIFORM' ,'Uniform distribition',{'lower end','upper end'} 17 ,'TTEST_NONC' ,'T-statistic noncentral',{'DOF','noncentrality parameter'} 18 ,'WEIBULL' ,'Weibull distribution',{'location','scale','power'} 19 ,'CHI' ,'Chi distribution',{'DOF'} 20 ,'INVGAUSS' ,'Inverse Gaussian distribution',{'mu','lambda'} 21 ,'EXTVAL' ,'Extreme Value distribution',{'location','scale'} 22 ,'PVAL' ,'P-value',{} 23 ,'LOGPVAL' ,'Log P-value',{} 24 ,'LOG10PVAL' ,'Log_10 P-value',{} 1001,'ESTIMATE' ,'Estimate',{} 1002,'LABEL' ,'Label index',{} 1003,'NEURONAMES' ,'NeuroNames index',{} 1004,'MATRIX' ,'General matrix',{'M','N'} 1005,'MATRIX_SYM' ,'Symmetric matrix',{} 1006,'DISPLACEMENT' ,'Displacement vector',{} 1007,'VECTOR' ,'Vector',{} 1008,'POINTS' ,'Pointset',{} 1009,'TRIANGLE' ,'Triangle',{} 1010,'QUATERNION' ,'Quaternion',{} 1011,'DIMLESS' ,'Dimensionless',{} }; intent = struct('code',table(:,1),'label',table(:,2),... 'fullname',table(:,3),'param',table(:,4)); % Units table = {... 0, 1,'UNKNOWN' 1,1000,'m' 2, 1,'mm' 3,1e-3,'um' 8, 1,'s' 16,1e-3,'ms' 24,1e-6,'us' 32, 1,'Hz' 40, 1,'ppm' 48, 1,'rads'}; units = struct('code',table(:,1),'label',table(:,3),'rescale',table(:,2)); % Reference space % code = {0,1,2,3,4}; table = {... 0,'UNKNOWN' 1,'Scanner Anat' 2,'Aligned Anat' 3,'Talairach' 4,'MNI_152'}; anat = struct('code',table(:,1),'label',table(:,2)); % Slice Ordering table = {... 0,'UNKNOWN' 1,'sequential_increasing' 2,'sequential_decreasing' 3,'alternating_increasing' 4,'alternating_decreasing'}; sliceorder = struct('code',table(:,1),'label',table(:,2)); % Q/S Form Interpretation table = {... 0,'UNKNOWN' 1,'Scanner' 2,'Aligned' 3,'Talairach' 4,'MNI152'}; xform = struct('code',table(:,1),'label',table(:,2)); dict = struct('dtype',dtype,'intent',intent,'units',units,... 'space',anat,'sliceorder',sliceorder,'xform',xform); d = dict; return; function varargout = crash(varargin) error('There is a NIFTI-1 data format problem (an invalid datatype).');
github
philippboehmsturm/antx-master
write_extras.m
.m
antx-master/xspm8/@nifti/private/write_extras.m
876
utf_8
f3686c5d5d6e88449972819a302e8c5c
function extras = write_extras(fname,extras) % Write extra bits of information %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: write_extras.m 1143 2008-02-07 19:33:33Z spm $ [pth,nam,ext] = fileparts(fname); switch ext case {'.hdr','.img','.nii'} mname = fullfile(pth,[nam '.mat']); case {'.HDR','.IMG','.NII'} mname = fullfile(pth,[nam '.MAT']); otherwise mname = fullfile(pth,[nam '.mat']); end if isstruct(extras) && ~isempty(fieldnames(extras)), savefields(mname,extras); end; function savefields(fnam,p) if length(p)>1, error('Can''t save fields.'); end; fn = fieldnames(p); for i_=1:length(fn), eval([fn{i_} '= p.' fn{i_} ';']); end; if str2num(version('-release'))>=14, fn = {'-V6',fn{:}}; end; if numel(fn)>0, save(fnam,fn{:}); end; return;
github
philippboehmsturm/antx-master
setpath.m
.m
antx-master/freiburgLight/setpath.m
1,503
utf_8
61605b0bdc54dfec7f0f06543e7c6327
%% SET PATHS For freiburg tools % setpath or setpath(1) : SETS PATHS For freiburg tools % setpath(0) :REMOVES PATHS For freiburg tools function setpath(arg) warning off; if exist('arg')==0; arg=1; end if arg==1 addpath(genpath(fullfile(pwd,'matlab', 'matlab_new'))) addpath(genpath(fullfile(pwd,'matlab', 'diffusion'))) addpath(genpath(fullfile(pwd,'matlab', 'spm8'))) addpath( fullfile(pwd, 'allen')) addpath( fullfile(pwd, 'fiberViewer3D')) addpath( fullfile(pwd, 'AMA')) % disp('PATHS of freiburg-tools added to pathlist'); disp('..PATHS: [matlabToolsFreiburg] added to matlab-path >> useful GUIS: AMA_gui2 , atlasbrowser , fiberViewer3D , Startgui_fv3d'); else rmpath(genpath(fullfile(pwd,'matlab', 'matlab_new'))) rmpath(genpath(fullfile(pwd,'matlab', 'diffusion'))) rmpath(genpath(fullfile(pwd,'matlab', 'spm8'))) rmpath( fullfile(pwd, 'allen')) rmpath( fullfile(pwd, 'fiberViewer3D')) rmpath( fullfile(pwd, 'AMA')) disp('PATHS of freiburg tools removed from pathlist'); end warning on; %% gui main function %atlas: atlasbrowser(allen): BrAt_StartGui % ama: automaticMouseAnalyzer : AMA_gui2 % visualization: fiberViewer3D % Startgui_fv3d: fmri+restingState netzwerke % k=dir(pwd); % k(1:2)=[]; % k([k(:).isdir]==0)=[]; % % for i=1:length(k) % addpath(genpath(pwd,k(i).name)); % end
github
philippboehmsturm/antx-master
buildtable.m
.m
antx-master/freiburgLight/allen/buildtable.m
1,038
utf_8
533e7574bda6931cad1b44fc010347b9
function [table idxLUT] = buildtable(tree) table = recur(tree); cnt = 1; for k = 1:length(table) for j = 1:length(table{k}) str = table{k}(j).allinfo; str.includes = [table{k}(1:j-1).id]; str.children = [table{k}(j).children]; str.nameinlist = [repmat('-',[1 j]) str.name]; idxLUT(cnt) = str; cnt = cnt + 1; end end [dummy ids] = unique([idxLUT.id],'first'); ids = sort(ids,'ascend'); idxLUT = idxLUT(ids); function list = recur(tree) list = []; children = []; for k=1:length(tree.children) clist = recur(tree.children{k}); children = [children ; cellfun(@(x) x(end).id,clist)]; list = [list ; clist]; end item.id = tree.id; item.acro = tree.acronym; item.atlas_id =tree.atlas_id; item.children = children; item.allinfo = rmfield(tree,'children'); if isfield(tree,'name') item.name = tree.name; else item.name = '<>'; end if not(isempty(list)) for k=1:length(list) list{k} = [item list{k}]; end else list = {item}; end
github
philippboehmsturm/antx-master
spm_uitab.m
.m
antx-master/freiburgLight/matlab/spm8/spm_uitab.m
7,695
utf_8
e80b69279b276644a59f0e838bc07817
function [handles] = spm_uitab(hparent,labels,callbacks,... tag,active,height,tab_height) % Create tabs in the SPM Graphics window % FORMAT [handles] = spm_uitab(hfig,labels,callbacks,... % tag,active,height,tab_height) % This functiuon creates tabs in the SPM graphics window. % These tabs may be associated with different sets of axes and uicontrol, % through the use of callback functions linked to the tabs. % IN: % - hparent: the handle of the parent of the tabs (can be the SPM graphics % windows, or the handle of the uipanel of a former spm_uitab...) % - labels: a cell array of string containing the labels of the tabs % - callbacks: a cell array of strings which will be evaluated using the % 'eval' function when clicking on a tab % - tag: a string which is the tags associated with the tabs (useful for % finding them in a window...) % - active: the index of the active tab when creating the uitabs (default % = 1, ie the first tab is active) % - height: the relative height of the tab panels within its parent % spatial extent (default = 1) % - tab_height: the relative height of the tabs within its parent spatial % extent (default = 1) % OUT: % - handles: a structure of handles for the differents tab objects. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Jean Daunizeau % $Id: spm_uitab.m 3062 2009-04-17 14:07:40Z jean $ Ntabs = length(labels); if ~exist('callbacks','var') || isempty(callbacks) for i=1:Ntabs callbacks{i} = []; end end if ~exist('tag','var') || isempty(tag) tag = ''; end if ~exist('active','var') || isempty(active) active = 1; end if ~exist('height','var') || isempty(height) height = 1; end if ~exist('tab_height','var') || isempty(tab_height) tab_height = 0.025; end if ~isequal(get(hparent,'type'),'figure') set(hparent,'units','normalized') POS = get(hparent,'position'); pos1 = [POS(1)+0.02,POS(2)+0.01,POS(3)-0.04,POS(4)-(tab_height+0.035)]; dx = 0.1*(POS(3)-0.04)./0.98; dx2 = [0.04,0.93]*(POS(3)-0.04)./0.98; else pos1 = [0.01 0.005 0.98 1-(tab_height+0.01)]; dx = 0.1; dx2 = [0.04,0.93]; end pos1(4) = pos1(4).*height; COLOR = 0.95*[1 1 1]; handles.hp = uipanel(... 'parent',hparent,... 'position',pos1,... 'BorderType','beveledout',... 'BackgroundColor',COLOR,... 'tag',tag); set(handles.hp,'units','normalized'); xl = pos1(1); yu = pos1(2) +pos1(4); ddx = 0.0025; ddy = 0.005; dy = tab_height; if Ntabs > 9 handles.hs(1) = uicontrol(... 'parent',hparent,...'enable','off',... 'style','pushbutton',... 'units','normalized','position',[xl yu dx2(1) dy],... 'SelectionHighlight','off',... 'BackgroundColor',COLOR,... 'callback',@doScroll,... 'value',0,'min',0,'max',Ntabs-9,... 'string','<',... 'tag',tag,... 'BusyAction','cancel',... 'Interruptible','off'); handles.hs(2) = uicontrol(... 'parent',hparent,... 'style','pushbutton',... 'units','normalized','position',[xl+dx2(2) yu 0.05 dy],... 'SelectionHighlight','off',... 'BackgroundColor',COLOR,... 'callback',@doScroll,... 'value',1,'min',1,'max',Ntabs-9,... 'string','>',... 'tag',tag,... 'BusyAction','cancel',... 'Interruptible','off'); set(handles.hs,'units','normalized') xl = xl + dx2(1); end for i =1:min([Ntabs,9]) pos = [xl+dx*(i-1) yu dx dy]; handles.htab(i) = uicontrol(... 'parent',hparent,... 'style','pushbutton',... 'units','normalized','position',pos,... 'SelectionHighlight','off',... 'string',labels{i},... 'BackgroundColor',COLOR,... 'tag',tag); set(handles.htab(i),'units','normalized') pos = [xl+dx*(i-1)+ddx yu-ddy dx-2*ddx 2*ddy]; handles.hh(i) = uicontrol(... 'parent',hparent,... 'style','text',... 'units','normalized','position',pos,... 'BackgroundColor',COLOR,... 'tag',tag); set(handles.hh(i),'units','normalized') end try set(handles.hh(active),'visible','on') catch active = 1; set(handles.hh(active),'visible','on') end others = setdiff(1:min([Ntabs,9]),active); set(handles.htab(active),... 'FontWeight','bold'); set(handles.hh(others),'visible','off'); set(handles.htab(others),... 'ForegroundColor',0.25*[1 1 1]); ud.handles = handles; ud.Ntabs = Ntabs; for i =1:min([Ntabs,9]) ud.ind = i; ud.callback = callbacks{i}; set(handles.htab(i),'callback',@doChoose,'userdata',ud,... 'BusyAction','cancel',... 'Interruptible','off'); if i > 9 set(handles.htab(i),'visible','off'); end end if Ntabs > 9 UD.in = [1:9]; UD.Ntabs = Ntabs; UD.h = handles; UD.active = active; UD.who = -1; UD.callbacks = callbacks; UD.labels = labels; set(handles.hs(1),'userdata',UD,'enable','off'); UD.who = 1; set(handles.hs(2),'userdata',UD); end %========================================================================== % doChoose %========================================================================== function doChoose(o1,o2) ud = get(o1,'userdata'); % Do nothing if called tab is current (active) tab if ~strcmp(get(ud.handles.htab(ud.ind),'FontWeight'),'bold') spm('pointer','watch'); set(ud.handles.hh(ud.ind),'visible','on'); set(ud.handles.htab(ud.ind),... 'ForegroundColor',0*[1 1 1],... 'FontWeight','bold'); others = setdiff(1:length(ud.handles.hh),ud.ind); set(ud.handles.hh(others),'visible','off'); set(ud.handles.htab(others),... 'ForegroundColor',0.25*[1 1 1],... 'FontWeight','normal'); if ud.Ntabs >9 UD = get(ud.handles.hs(1),'userdata'); UD.active = UD.in(ud.ind); UD.who = -1; set(ud.handles.hs(1),'userdata',UD); UD.who = 1; set(ud.handles.hs(2),'userdata',UD); end drawnow if ~isempty(ud.callback) if isa(ud.callback, 'function_handle') feval(ud.callback); else eval(ud.callback); end end drawnow spm('pointer','arrow'); end %========================================================================== % doScroll %========================================================================== function doScroll(o1,o2) ud = get(o1,'userdata'); % active = ud.in(ud.active); ud.in = ud.in + ud.who; if min(ud.in) ==1 set(ud.h.hs(1),'enable','off'); set(ud.h.hs(2),'enable','on'); elseif max(ud.in) ==ud.Ntabs set(ud.h.hs(1),'enable','on'); set(ud.h.hs(2),'enable','off'); else set(ud.h.hs,'enable','on'); end UD.handles = ud.h; UD.Ntabs = ud.Ntabs; for i = 1:length(ud.in) UD.ind = i; UD.callback = ud.callbacks{ud.in(i)}; set(ud.h.htab(i),'userdata',UD,... 'string',ud.labels{ud.in(i)}); if ismember(ud.active,ud.in) ind = find(ud.in==ud.active); set(ud.h.hh(ind),'visible','on'); set(ud.h.htab(ind),... 'ForegroundColor',0*[1 1 1],... 'FontWeight','bold'); others = setdiff(1:9,ind); set(ud.h.hh(others),'visible','off'); set(ud.h.htab(others),... 'ForegroundColor',0.25*[1 1 1],... 'FontWeight','normal'); else others = 1:9; set(ud.h.hh(others),'visible','off'); set(ud.h.htab(others),... 'ForegroundColor',0.25*[1 1 1],... 'FontWeight','normal'); end end ud.who = -1; set(ud.h.hs(1),'userdata',ud) ud.who = 1; set(ud.h.hs(2),'userdata',ud)
github
philippboehmsturm/antx-master
spm_vb_ppm_anova.m
.m
antx-master/freiburgLight/matlab/spm8/spm_vb_ppm_anova.m
3,873
utf_8
5360b2f4d1d7fe1f61c455b53a468fd5
function spm_vb_ppm_anova(SPM) % Bayesian ANOVA using model comparison % FORMAT spm_vb_ppm_anova(SPM) % % SPM - Data structure corresponding to a full model (ie. one % containing all experimental conditions). % % This function creates images of differences in log evidence % which characterise the average effect, main effects and interactions % in a factorial design. % % The factorial design is specified in SPM.factor. For a one-way ANOVA % the images % % avg_effect.img % main_effect.img % % are produced. For a two-way ANOVA the following images are produced % % avg_effect.img % main_effect_'factor1'.img % main_effect_'factor2'.img % interaction.img % % These images can then be thresholded. For example a threshold of 4.6 % corresponds to a posterior effect probability of [exp(4.6)] = 0.999. % See paper VB4 for more details. %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Will Penny % $Id: spm_vb_ppm_anova.m 1143 2008-02-07 19:33:33Z spm $ disp('Warning: spm_vb_ppm_anova only works for single session data.'); model = spm_vb_models(SPM,SPM.factor); analysis_dir = pwd; for m=1:length(model)-1, model_subdir = ['model_',int2str(m)]; mkdir(analysis_dir,model_subdir); SPM.swd = fullfile(analysis_dir,model_subdir); SPM.Sess(1).U = model(m).U; SPM.Sess(1).U = spm_get_ons(SPM,1); SPM = spm_fMRI_design(SPM,0); % 0 = don't save SPM.mat SPM.PPM.update_F = 1; % Compute evidence for each model SPM.PPM.compute_det_D = 1; spm_spm_vb(SPM); end % Compute differences in contributions to log-evidence images % to assess main effects and interactions nf = length(SPM.factor); if nf==1 % For a single factor % Average effect image1 = fullfile(analysis_dir, 'model_1','LogEv.img'); image2 = fullfile(analysis_dir, 'model_2','LogEv.img'); imout = fullfile(analysis_dir, 'avg_effect.img'); img_subtract(image1,image2,imout); % Main effect of factor image1 = fullfile(analysis_dir, 'model_2','LogEv.img'); image2 = fullfile(analysis_dir, 'LogEv.img'); imout = fullfile(analysis_dir, 'main_effect.img'); img_subtract(image1,image2,imout); elseif nf==2 % For two factors % Average effect image1 = fullfile(analysis_dir, 'model_1','LogEv.img'); image2 = fullfile(analysis_dir, 'model_2','LogEv.img'); imout = fullfile(analysis_dir, 'avg_effect.img'); img_subtract(image1,image2,imout); % Main effect of factor 1 image1 = fullfile(analysis_dir, 'model_2','LogEv.img'); image2 = fullfile(analysis_dir, 'model_3','LogEv.img'); imout = fullfile(analysis_dir, ['main_effect_',SPM.factor(1).name,'.img']); img_subtract(image1,image2,imout); % Main effect of factor 2 image1 = fullfile(analysis_dir, 'model_2','LogEv.img'); image2 = fullfile(analysis_dir, 'model_4','LogEv.img'); imout = fullfile(analysis_dir, ['main_effect_',SPM.factor(2).name,'.img']); img_subtract(image1,image2,imout); % Interaction image1 = fullfile(analysis_dir, 'model_5','LogEv.img'); image2 = fullfile(analysis_dir, 'LogEv.img'); imout = fullfile(analysis_dir, 'interaction.img'); img_subtract(image1,image2,imout); end %----------------------------------------------------------------------- function img_subtract(image1,image2,image_out) % Subtract image 1 from image 2 and write to image out % Note: parameters are names of files Vi = spm_vol(strvcat(image1,image2)); Vo = struct(... 'fname', image_out,... 'dim', [Vi(1).dim(1:3)],... 'dt', [spm_type('float32') spm_platform('bigend')],... 'mat', Vi(1).mat,... 'descrip', 'Difference in Log Evidence'); f = 'i2-i1'; flags = {0,0,1}; Vo = spm_imcalc(Vi,Vo,f,flags);
github
philippboehmsturm/antx-master
spm_coreg_paul.m
.m
antx-master/freiburgLight/matlab/spm8/spm_coreg_paul.m
15,181
utf_8
9d4ef60b26a7fd206c6d5484ab26092e
function [x ffmin] = spm_coreg_paul(varargin) % Between modality coregistration using information theory % FORMAT x = spm_coreg(VG,VF,flags) % VG - handle for reference image (see spm_vol). % VF - handle for source (moved) image. % flags - a structure containing the following elements: % sep - optimisation sampling steps (mm) % default: [4 2] % params - starting estimates (6 elements) % default: [0 0 0 0 0 0] % cost_fun - cost function string: % 'mi' - Mutual Information % 'nmi' - Normalised Mutual Information % 'ecc' - Entropy Correlation Coefficient % 'ncc' - Normalised Cross Correlation % default: 'nmi' % tol - tolerences for accuracy of each param % default: [0.02 0.02 0.02 0.001 0.001 0.001] % fwhm - smoothing to apply to 256x256 joint histogram % default: [7 7] % graphics - display coregistration outputs % default: ~spm('CmdLine') % % x - the parameters describing the rigid body rotation, such that a % mapping from voxels in G to voxels in F is attained by: % VF.mat\spm_matrix(x(:)')*VG.mat % % At the end, the voxel-to-voxel affine transformation matrix is % displayed, along with the histograms for the images in the original % orientations, and the final orientations. The registered images are % displayed at the bottom. %__________________________________________________________________________ % % The registration method used here is based on the work described in: % A Collignon, F Maes, D Delaere, D Vandermeulen, P Suetens & G Marchal % (1995) "Automated Multi-modality Image Registration Based On % Information Theory". In the proceedings of Information Processing in % Medical Imaging (1995). Y. Bizais et al. (eds.). Kluwer Academic % Publishers. % % The original interpolation method described in this paper has been % changed in order to give a smoother cost function. The images are % also smoothed slightly, as is the histogram. This is all in order to % make the cost function as smooth as possible, to give faster convergence % and less chance of local minima. %__________________________________________________________________________ % Copyright (C) 1994-2011 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id: spm_coreg.m 4156 2011-01-11 19:03:31Z guillaume $ %========================================================================== % References %========================================================================== % % Mutual Information % ------------------------------------------------------------------------- % Collignon, Maes, Delaere, Vandermeulen, Suetens & Marchal (1995). % "Automated multi-modality image registration based on information theory". % In Bizais, Barillot & Di Paola, editors, Proc. Information Processing % in Medical Imaging, pages 263--274, Dordrecht, The Netherlands, 1995. % Kluwer Academic Publishers. % % Wells III, Viola, Atsumi, Nakajima & Kikinis (1996). % "Multi-modal volume registration by maximisation of mutual information". % Medical Image Analysis, 1(1):35-51, 1996. % % Entropy Correlation Coefficient % ------------------------------------------------------------------------- % Maes, Collignon, Vandermeulen, Marchal & Suetens (1997). % "Multimodality image registration by maximisation of mutual % information". IEEE Transactions on Medical Imaging 16(2):187-198 % % Normalised Mutual Information % ------------------------------------------------------------------------- % Studholme, Hill & Hawkes (1998). % "A normalized entropy measure of 3-D medical image alignment". % in Proc. Medical Imaging 1998, vol. 3338, San Diego, CA, pp. 132-143. % % Optimisation % ------------------------------------------------------------------------- % Press, Teukolsky, Vetterling & Flannery (1992). % "Numerical Recipes in C (Second Edition)". % Published by Cambridge. %========================================================================== if nargin >= 4 x = optfun(varargin{:}); return; end def_flags = spm_get_defaults('coreg.estimate'); def_flags.params = [0 0 0 0 0 0]; def_flags.graphics = ~spm('CmdLine'); if nargin < 3 flags = def_flags; else flags = varargin{3}; fnms = fieldnames(def_flags); for i=1:length(fnms) if ~isfield(flags,fnms{i}) flags.(fnms{i}) = def_flags.(fnms{i}); end end end if nargin < 1 VG = spm_vol(spm_select(1,'image','Select reference image')); else VG = varargin{1}; if ischar(VG), VG = spm_vol(VG); end end if nargin < 2 VF = spm_vol(spm_select(Inf,'image','Select moved image(s)')); else VF = varargin{2}; if ischar(VF) || iscellstr(VF), VF = spm_vol(char(VF)); end; end if ~isfield(VG, 'uint8') VG.uint8 = loaduint8(VG); vxg = sqrt(sum(VG.mat(1:3,1:3).^2)); fwhmg = sqrt(max([1 1 1]*flags.sep(end)^2 - vxg.^2, [0 0 0]))./vxg; VG = smooth_uint8(VG,fwhmg); % Note side effects end sc = flags.tol(:)'; % Required accuracy sc = sc(1:length(flags.params)); xi = diag(sc*20); x = zeros(numel(VF),numel(flags.params)); for k=1:numel(VF) VFk = VF(k); if ~isfield(VFk, 'uint8') VFk.uint8 = loaduint8(VFk); vxf = sqrt(sum(VFk.mat(1:3,1:3).^2)); fwhmf = sqrt(max([1 1 1]*flags.sep(end)^2 - vxf.^2, [0 0 0]))./vxf; VFk = smooth_uint8(VFk,fwhmf); % Note side effects end xk = flags.params(:); for samp=flags.sep(:)' [xk ffmin ] = spm_powell(xk(:), xi,sc,mfilename,VG,VFk,samp,flags.cost_fun,flags.fwhm); x(k,:) = xk(:)'; ffmin(k,:) = ffmin(:)'; end if flags.graphics display_results(VG(1),VFk(1),xk(:)',flags); end end %========================================================================== % function o = optfun(x,VG,VF,s,cf,fwhm) %========================================================================== function o = optfun(x,VG,VF,s,cf,fwhm) % The function that is minimised. if nargin<6, fwhm = [7 7]; end if nargin<5, cf = 'mi'; end if nargin<4, s = [1 1 1]; end % Voxel sizes vxg = sqrt(sum(VG.mat(1:3,1:3).^2));sg = s./vxg; % Create the joint histogram H = spm_hist2(VG.uint8,VF.uint8, VF.mat\spm_matrix(x(:)')*VG.mat ,sg); % Smooth the histogram lim = ceil(2*fwhm); krn1 = smoothing_kernel(fwhm(1),-lim(1):lim(1)) ; krn1 = krn1/sum(krn1); H = conv2(H,krn1); krn2 = smoothing_kernel(fwhm(2),-lim(2):lim(2))'; krn2 = krn2/sum(krn2); H = conv2(H,krn2); % Compute cost function from histogram H = H+eps; sh = sum(H(:)); H = H/sh; s1 = sum(H,1); s2 = sum(H,2); switch lower(cf) case 'mi' % Mutual Information: H = H.*log2(H./(s2*s1)); mi = sum(H(:)); o = -mi; case 'ecc' % Entropy Correlation Coefficient of: % Maes, Collignon, Vandermeulen, Marchal & Suetens (1997). % "Multimodality image registration by maximisation of mutual % information". IEEE Transactions on Medical Imaging 16(2):187-198 H = H.*log2(H./(s2*s1)); mi = sum(H(:)); ecc = -2*mi/(sum(s1.*log2(s1))+sum(s2.*log2(s2))); o = -ecc; case 'nmi' % Normalised Mutual Information of: % Studholme, Hill & Hawkes (1998). % "A normalized entropy measure of 3-D medical image alignment". % in Proc. Medical Imaging 1998, vol. 3338, San Diego, CA, pp. 132-143. nmi = (sum(s1.*log2(s1))+sum(s2.*log2(s2)))/sum(sum(H.*log2(H))); o = -nmi; case 'ncc' % Normalised Cross Correlation i = 1:size(H,1); j = 1:size(H,2); m1 = sum(s2.*i'); m2 = sum(s1.*j); sig1 = sqrt(sum(s2.*(i'-m1).^2)); sig2 = sqrt(sum(s1.*(j -m2).^2)); [i,j] = ndgrid(i-m1,j-m2); ncc = sum(sum(H.*i.*j))/(sig1*sig2); o = -ncc; otherwise error('Invalid cost function specified'); end %========================================================================== % function udat = loaduint8(V) %========================================================================== function udat = loaduint8(V) % Load data from file indicated by V into an array of unsigned bytes. if size(V.pinfo,2)==1 && V.pinfo(1) == 2 mx = 255*V.pinfo(1) + V.pinfo(2); mn = V.pinfo(2); else spm_progress_bar('Init',V.dim(3),... ['Computing max/min of ' spm_str_manip(V.fname,'t')],... 'Planes complete'); mx = -Inf; mn = Inf; for p=1:V.dim(3) img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1); mx = max([max(img(:))+paccuracy(V,p) mx]); mn = min([min(img(:)) mn]); spm_progress_bar('Set',p); end end % Another pass to find a maximum that allows a few hot-spots in the data. spm_progress_bar('Init',V.dim(3),... ['2nd pass max/min of ' spm_str_manip(V.fname,'t')],... 'Planes complete'); nh = 2048; h = zeros(nh,1); for p=1:V.dim(3) img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1); img = img(isfinite(img)); img = round((img+((mx-mn)/(nh-1)-mn))*((nh-1)/(mx-mn))); h = h + accumarray(img,1,[nh 1]); spm_progress_bar('Set',p); end tmp = [find(cumsum(h)/sum(h)>0.9999); nh]; mx = (mn*nh-mx+tmp(1)*(mx-mn))/(nh-1); % Load data from file indicated by V into an array of unsigned bytes. spm_progress_bar('Init',V.dim(3),... ['Loading ' spm_str_manip(V.fname,'t')],... 'Planes loaded'); udat = zeros(V.dim,'uint8'); st = rand('state'); % st = rng; rand('state',100); % rng(100,'v5uniform'); % rng('defaults'); for p=1:V.dim(3) img = spm_slice_vol(V,spm_matrix([0 0 p]),V.dim(1:2),1); acc = paccuracy(V,p); if acc==0 udat(:,:,p) = uint8(max(min(round((img-mn)*(255/(mx-mn))),255),0)); else % Add random numbers before rounding to reduce aliasing artifact r = rand(size(img))*acc; udat(:,:,p) = uint8(max(min(round((img+r-mn)*(255/(mx-mn))),255),0)); end spm_progress_bar('Set',p); end spm_progress_bar('Clear'); rand('state',st); % rng(st); %========================================================================== % function acc = paccuracy(V,p) %========================================================================== function acc = paccuracy(V,p) if ~spm_type(V.dt(1),'intt') acc = 0; else if size(V.pinfo,2)==1 acc = abs(V.pinfo(1,1)); else acc = abs(V.pinfo(1,p)); end end %========================================================================== % function V = smooth_uint8(V,fwhm) %========================================================================== function V = smooth_uint8(V,fwhm) % Convolve the volume in memory (fwhm in voxels). lim = ceil(2*fwhm); x = -lim(1):lim(1); x = smoothing_kernel(fwhm(1),x); x = x/sum(x); y = -lim(2):lim(2); y = smoothing_kernel(fwhm(2),y); y = y/sum(y); z = -lim(3):lim(3); z = smoothing_kernel(fwhm(3),z); z = z/sum(z); i = (length(x) - 1)/2; j = (length(y) - 1)/2; k = (length(z) - 1)/2; spm_conv_vol(V.uint8,V.uint8,x,y,z,-[i j k]); %========================================================================== % function krn = smoothing_kernel(fwhm,x) %========================================================================== function krn = smoothing_kernel(fwhm,x) % Variance from FWHM s = (fwhm/sqrt(8*log(2)))^2+eps; % The simple way to do it. Not good for small FWHM % krn = (1/sqrt(2*pi*s))*exp(-(x.^2)/(2*s)); % For smoothing images, one should really convolve a Gaussian % with a sinc function. For smoothing histograms, the % kernel should be a Gaussian convolved with the histogram % basis function used. This function returns a Gaussian % convolved with a triangular (1st degree B-spline) basis % function. % Gaussian convolved with 0th degree B-spline % int(exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= -0.5..0.5) % w1 = 1/sqrt(2*s); % krn = 0.5*(erf(w1*(x+0.5))-erf(w1*(x-0.5))); % Gaussian convolved with 1st degree B-spline % int((1-t)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t= 0..1) % +int((t+1)*exp(-((x+t))^2/(2*s))/sqrt(2*pi*s),t=-1..0) w1 = 0.5*sqrt(2/s); w2 = -0.5/s; w3 = sqrt(s/2/pi); krn = 0.5*(erf(w1*(x+1)).*(x+1) + erf(w1*(x-1)).*(x-1) - 2*erf(w1*x ).* x)... +w3*(exp(w2*(x+1).^2) + exp(w2*(x-1).^2) - 2*exp(w2*x.^2)); krn(krn<0) = 0; %========================================================================== % function display_results(VG,VF,x,flags) %========================================================================== function display_results(VG,VF,x,flags) fig = spm_figure('FindWin','Graphics'); if isempty(fig), return; end; set(0,'CurrentFigure',fig); spm_figure('Clear','Graphics'); %txt = 'Information Theoretic Coregistration'; switch lower(flags.cost_fun) case 'mi', txt = 'Mutual Information Coregistration'; case 'ecc', txt = 'Entropy Correlation Coefficient Registration'; case 'nmi', txt = 'Normalised Mutual Information Coregistration'; case 'ncc', txt = 'Normalised Cross Correlation'; otherwise, error('Invalid cost function specified'); end % Display text %-------------------------------------------------------------------------- ax = axes('Position',[0.1 0.8 0.8 0.15],'Visible','off','Parent',fig); text(0.5,0.7, txt,'FontSize',16,... 'FontWeight','Bold','HorizontalAlignment','center','Parent',ax); Q = inv(VF.mat\spm_matrix(x(:)')*VG.mat); text(0,0.5, sprintf('X1 = %0.3f*X %+0.3f*Y %+0.3f*Z %+0.3f',Q(1,:)),'Parent',ax); text(0,0.3, sprintf('Y1 = %0.3f*X %+0.3f*Y %+0.3f*Z %+0.3f',Q(2,:)),'Parent',ax); text(0,0.1, sprintf('Z1 = %0.3f*X %+0.3f*Y %+0.3f*Z %+0.3f',Q(3,:)),'Parent',ax); % Display joint histograms %-------------------------------------------------------------------------- ax = axes('Position',[0.1 0.5 0.35 0.3],'Visible','off','Parent',fig); H = spm_hist2(VG.uint8,VF.uint8,VF.mat\VG.mat,[1 1 1]); tmp = log(H+1); image(tmp*(64/max(tmp(:))),'Parent',ax'); set(ax,'DataAspectRatio',[1 1 1],... 'PlotBoxAspectRatioMode','auto','XDir','normal','YDir','normal',... 'XTick',[],'YTick',[]); title('Original Joint Histogram','Parent',ax); xlabel(spm_str_manip(VG.fname,'k22'),'Parent',ax); ylabel(spm_str_manip(VF.fname,'k22'),'Parent',ax); H = spm_hist2(VG.uint8,VF.uint8,VF.mat\spm_matrix(x(:)')*VG.mat,[1 1 1]); ax = axes('Position',[0.6 0.5 0.35 0.3],'Visible','off','Parent',fig); tmp = log(H+1); image(tmp*(64/max(tmp(:))),'Parent',ax'); set(ax,'DataAspectRatio',[1 1 1],... 'PlotBoxAspectRatioMode','auto','XDir','normal','YDir','normal',... 'XTick',[],'YTick',[]); title('Final Joint Histogram','Parent',ax); xlabel(spm_str_manip(VG.fname,'k22'),'Parent',ax); ylabel(spm_str_manip(VF.fname,'k22'),'Parent',ax); % Display ortho-views %-------------------------------------------------------------------------- spm_orthviews('Reset'); spm_orthviews('Image',VG,[0.01 0.01 .48 .49]); h2 = spm_orthviews('Image',VF,[.51 0.01 .48 .49]); global st st.vols{h2}.premul = inv(spm_matrix(x(:)')); spm_orthviews('Space'); spm_print;
github
philippboehmsturm/antx-master
spm_fmri_spm_ui.m
.m
antx-master/freiburgLight/matlab/spm8/spm_fmri_spm_ui.m
19,710
utf_8
9d0ac73f1907933c2ee6bdad95b8210b
function [SPM] = spm_fmri_spm_ui(SPM) % Setting up the general linear model for fMRI time-series % FORMAT [SPM] = spm_fmri_spm_ui(SPM) % % creates SPM with the following fields % % xY: [1x1 struct] - data structure % nscan: [double] - vector of scans per session % xBF: [1x1 struct] - Basis function structure (see spm_fMRI_design) % Sess: [1x1 struct] - Session structure (see spm_fMRI_design) % xX: [1x1 struct] - Design matrix structure (see spm_fMRI_design) % xGX: [1x1 struct] - Global variate structure % xVi: [1x1 struct] - Non-sphericity structure % xM: [1x1 struct] - Masking structure % xsDes: [1x1 struct] - Design description structure % % % SPM.xY % P: [n x ? char] - filenames % VY: [n x 1 struct] - filehandles % RT: Repeat time % % SPM.xGX % % iGXcalc: {'none'|'Scaling'} - Global normalization option % sGXcalc: 'mean voxel value' - Calculation method % sGMsca: 'session specific' - Grand mean scaling % rg: [n x 1 double] - Global estimate % GM: 100 - Grand mean % gSF: [n x 1 double] - Global scaling factor % % SPM.xVi % Vi: {[n x n sparse]..} - covariance components % form: {'none'|'AR(1)'} - form of non-sphericity % % SPM.xM % T: [n x 1 double] - Masking index % TH: [n x 1 double] - Threshold % I: 0 % VM: - Mask filehandles % xs: [1x1 struct] - cellstr description % % (see also spm_spm_ui) % %__________________________________________________________________________ % % spm_fmri_spm_ui configures the design matrix, data specification and % filtering that specify the ensuing statistical analysis. These % arguments are passed to spm_spm that then performs the actual parameter % estimation. % % The design matrix defines the experimental design and the nature of % hypothesis testing to be implemented. The design matrix has one row % for each scan and one column for each effect or explanatory variable. % (e.g. regressor or stimulus function). The parameters are estimated in % a least squares sense using the general linear model. Specific profiles % within these parameters are tested using a linear compound or contrast % with the T or F statistic. The resulting statistical map constitutes % an SPM. The SPM{T}/{F} is then characterized in terms of focal or regional % differences by assuming that (under the null hypothesis) the components of % the SPM (i.e. residual fields) behave as smooth stationary Gaussian fields. % % spm_fmri_spm_ui allows you to (i) specify a statistical model in terms % of a design matrix, (ii) associate some data with a pre-specified design % [or (iii) specify both the data and design] and then proceed to estimate % the parameters of the model. % Inferences can be made about the ensuing parameter estimates (at a first % or fixed-effect level) in the results section, or they can be re-entered % into a second (random-effect) level analysis by treating the session or % subject-specific [contrasts of] parameter estimates as new summary data. % Inferences at any level obtain by specifying appropriate T or F contrasts % in the results section to produce SPMs and tables of p values and statistics. % % spm_fmri_spm calls spm_fMRI_design which allows you to configure a % design matrix in terms of events or epochs. % % spm_fMRI_design allows you to build design matrices with separable % session-specific partitions. Each partition may be the same (in which % case it is only necessary to specify it once) or different. Responses % can be either event- or epoch related, The only distinction is the duration % of the underlying input or stimulus function. Mathematically they are both % modelled by convolving a series of delta (stick) or box functions (u), % indicating the onset of an event or epoch with a set of basis % functions. These basis functions model the hemodynamic convolution, % applied by the brain, to the inputs. This convolution can be first-order % or a generalized convolution modelled to second order (if you specify the % Volterra option). [The same inputs are used by the hemodynamic model or % or dynamic causal models which model the convolution explicitly in terms of % hidden state variables (see spm_hdm_ui and spm_dcm_ui).] % Basis functions can be used to plot estimated responses to single events % once the parameters (i.e. basis function coefficients) have % been estimated. The importance of basis functions is that they provide % a graceful transition between simple fixed response models (like the % box-car) and finite impulse response (FIR) models, where there is one % basis function for each scan following an event or epoch onset. The % nice thing about basis functions, compared to FIR models, is that data % sampling and stimulus presentation does not have to be synchronized % thereby allowing a uniform and unbiased sampling of peri-stimulus time. % % Event-related designs may be stochastic or deterministic. Stochastic % designs involve one of a number of trial-types occurring with a % specified probably at successive intervals in time. These % probabilities can be fixed (stationary designs) or time-dependent % (modulated or non-stationary designs). The most efficient designs % obtain when the probabilities of every trial type are equal. % A critical issue in stochastic designs is whether to include null events % If you wish to estimate the evoke response to a specific event % type (as opposed to differential responses) then a null event must be % included (even if it is not modelled explicitly). % % The choice of basis functions depends upon the nature of the inference % sought. One important consideration is whether you want to make % inferences about compounds of parameters (i.e. contrasts). This is % the case if (i) you wish to use a SPM{T} to look separately at % activations and deactivations or (ii) you with to proceed to a second % (random-effect) level of analysis. If this is the case then (for % event-related studies) use a canonical hemodynamic response function % (HRF) and derivatives with respect to latency (and dispersion). Unlike % other bases, contrasts of these effects have a physical interpretation % and represent a parsimonious way of characterising event-related % responses. Bases such as a Fourier set require the SPM{F} for % inference. % % See spm_fMRI_design for more details about how designs are specified. % % Serial correlations in fast fMRI time-series are dealt with as % described in spm_spm. At this stage you need to specify the filtering % that will be applied to the data (and design matrix) to give a % generalized least squares (GLS) estimate of the parameters required. % This filtering is important to ensure that the GLS estimate is % efficient and that the error variance is estimated in an unbiased way. % % The serial correlations will be estimated with a ReML (restricted % maximum likelihood) algorithm using an autoregressive AR(1) model % during parameter estimation. This estimate assumes the same % correlation structure for each voxel, within each session. The ReML % estimates are then used to correct for non-sphericity during inference % by adjusting the statistics and degrees of freedom appropriately. The % discrepancy between estimated and actual intrinsic (i.e. prior to % filtering) correlations are greatest at low frequencies. Therefore % specification of the high-pass filter is particularly important. % % High-pass filtering is implemented at the level of the % filtering matrix K (as opposed to entering as confounds in the design % matrix). The default cut-off period is 128 seconds. Use 'explore design' % to ensure this cut-off is not removing too much experimental variance. % Note that high-pass filtering uses a residual forming matrix (i.e. % it is not a convolution) and is simply to a way to remove confounds % without estimating their parameters explicitly. The constant term % is also incorporated into this filter matrix. % %-------------------------------------------------------------------------- % Refs: % % Friston KJ, Holmes A, Poline J-B, Grasby PJ, Williams SCR, Frackowiak % RSJ & Turner R (1995) Analysis of fMRI time-series revisited. NeuroImage % 2:45-53 % % Worsley KJ and Friston KJ (1995) Analysis of fMRI time-series revisited - % again. NeuroImage 2:178-181 % % Friston KJ, Frith CD, Frackowiak RSJ, & Turner R (1995) Characterising % dynamic brain responses with fMRI: A multivariate approach NeuroImage - % 2:166-172 % % Frith CD, Turner R & Frackowiak RSJ (1995) Characterising evoked % hemodynamics with fMRI Friston KJ, NeuroImage 2:157-165 % % Josephs O, Turner R and Friston KJ (1997) Event-related fMRI, Hum. Brain % Map. 0:00-00 % %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Karl Friston, Jean-Baptiste Poline & Christian Buchel % $Id: spm_fmri_spm_ui.m 669 2012-02-27 14:10:24Z vglauche $ SVNid = '$Rev: 669 $'; %-GUI setup %-------------------------------------------------------------------------- [Finter,Fgraph,CmdLine] = spm('FnUIsetup','fMRI stats model setup',0); % get design matrix and/or data %========================================================================== if ~nargin str = 'specify design or data'; if spm_input(str,1,'b',{'design','data'},[1 0]); % specify a design %------------------------------------------------------------------ if sf_abort, spm_clf(Finter), return, end SPM = spm_fMRI_design; spm_fMRI_design_show(SPM); return else % get design %------------------------------------------------------------------ load(spm_select(1,'^SPM\.mat$','Select SPM.mat')); end else % get design matrix %---------------------------------------------------------------------- SPM = spm_fMRI_design(SPM); end % get Repeat time %-------------------------------------------------------------------------- try SPM.xY.RT; catch SPM.xY.RT = spm_input('Interscan interval {secs}','+1'); end % session and scan number %-------------------------------------------------------------------------- nscan = SPM.nscan; nsess = length(nscan); % check data are specified %-------------------------------------------------------------------------- try SPM.xY.P; catch % get filenames %---------------------------------------------------------------------- P = []; for i = 1:nsess str = sprintf('select scans for session %0.0f',i); q = spm_select(nscan(i),'image',str); P = strvcat(P,q); end % place in data field %---------------------------------------------------------------------- SPM.xY.P = P; end % Assemble remaining design parameters %========================================================================== SPM.SPMid = spm('FnBanner',mfilename,SVNid); % Global normalization %-------------------------------------------------------------------------- try SPM.xGX.iGXcalc; catch spm_input('Global intensity normalisation...',1,'d',mfilename) str = 'remove Global effects'; SPM.xGX.iGXcalc = spm_input(str,'+1','scale|none',{'Scaling' 'None'}); end SPM.xGX.sGXcalc = 'mean voxel value'; SPM.xGX.sGMsca = 'session specific'; % High-pass filtering and serial correlations %========================================================================== % low frequency confounds %-------------------------------------------------------------------------- try myLastWarn = 0; HParam = [SPM.xX.K(:).HParam]; if length(HParam) == 1 HParam = HParam*ones(1,nsess); elseif length(HParam) ~= nsess myLastWarn = 1; error('Continue with manual HPF specification in the catch block'); end catch % specify low frequency confounds %---------------------------------------------------------------------- spm_input('Temporal autocorrelation options','+1','d',mfilename) switch spm_input('High-pass filter?','+1','b','none|specify'); case 'specify' % default in seconds %-------------------------------------------------------------- HParam = spm_get_defaults('stats.fmri.hpf')*ones(1,nsess); str = 'cutoff period (secs)'; HParam = spm_input(str,'+1','e',HParam,[1 nsess]); case 'none' % Inf seconds (i.e. constant term only) %-------------------------------------------------------------- HParam = Inf(1,nsess); end if myLastWarn warning('SPM:InvalidHighPassFilterSpec',... ['Different number of High-pass filter values and sessions.\n',... 'HPF filter configured manually. Design setup will proceed.']); clear myLastWarn end end % create and set filter struct %-------------------------------------------------------------------------- for i = 1:nsess K(i) = struct('HParam', HParam(i),... 'row', SPM.Sess(i).row,... 'RT', SPM.xY.RT); end SPM.xX.K = spm_filter(K); % intrinsic autocorrelations (Vi) %-------------------------------------------------------------------------- try cVi = SPM.xVi.form; catch % Construct Vi structure for non-sphericity ReML estimation %---------------------------------------------------------------------- str = 'Correct for serial correlations?'; cVi = {'none','AR(1)'}; cVi = spm_input(str,'+1','b',cVi); end % create Vi struct %-------------------------------------------------------------------------- if isnumeric(cVi) % AR coefficient specified %---------------------------------------------------------------------- SPM.xVi.Vi = spm_Ce(nscan,cVi(1)); cVi = ['AR( ' sprintf('%0.1f ',cVi) ')']; elseif iscell(cVi) % ARFIT selection - 1st element is label string, 2nd % AR order SPM.xVi.arfit.exp = 32; % ACF expansion time if cVi{2} > 0 % fix order (2 passes) [SPM.xVi.arfit.Sess{1:nsess}] = deal(arfit_init(cVi{2})); SPM.xVi.arfit.firstpass=true; else % estimate order up to -cVi{2} [SPM.xVi.arfit.Sess{1:nsess}] = deal(arfit_init(-cVi{2})); end cVi = cVi{1}; else switch lower(cVi) case 'none' % xVi.V is i.i.d %-------------------------------------------------------------- SPM.xVi.V = speye(sum(nscan)); cVi = 'i.i.d'; otherwise % otherwise assume AR(0.2) in xVi.Vi %-------------------------------------------------------------- SPM.xVi.Vi = spm_Ce(nscan,0.2); cVi = 'AR(0.2)'; end end SPM.xVi.form = cVi; %========================================================================== % - C O N F I G U R E D E S I G N %========================================================================== spm_clf(Finter); spm('FigName','Configuring, please wait...',Finter,CmdLine); spm('Pointer','Watch'); % get file identifiers %========================================================================== %-Map files %-------------------------------------------------------------------------- fprintf('%-40s: ','Mapping files') %-# VY = spm_vol(SPM.xY.P); fprintf('%30s\n','...done') %-# %-check internal consistency of images %-------------------------------------------------------------------------- spm_check_orientations(VY); %-place in xY %-------------------------------------------------------------------------- SPM.xY.VY = VY; %-Compute Global variate %========================================================================== GM = 100; q = length(VY); g = zeros(q,1); fprintf('%-40s: %30s','Calculating globals',' ') %-# for i = 1:q fprintf('%s%30s',repmat(sprintf('\b'),1,30),sprintf('%4d/%-4d',i,q))%-# g(i) = spm_global(VY(i)); end fprintf('%s%30s\n',repmat(sprintf('\b'),1,30),'...done') %-# % scale if specified (otherwise session specific grand mean scaling) %-------------------------------------------------------------------------- gSF = GM./g; if strcmpi(SPM.xGX.iGXcalc,'none') for i = 1:nsess gSF(SPM.Sess(i).row) = GM./mean(g(SPM.Sess(i).row)); end end %-Apply gSF to memory-mapped scalefactors to implement scaling %-------------------------------------------------------------------------- for i = 1:q SPM.xY.VY(i).pinfo(1:2,:) = SPM.xY.VY(i).pinfo(1:2,:)*gSF(i); end %-place global variates in global structure %-------------------------------------------------------------------------- SPM.xGX.rg = g; SPM.xGX.GM = GM; SPM.xGX.gSF = gSF; %-Masking structure automatically set to 80% of mean %========================================================================== try TH = g.*gSF*spm_get_defaults('mask.thresh'); catch TH = g.*gSF*0.8; end SPM.xM = struct('T', ones(q,1),... 'TH', TH,... 'I', 0,... 'VM', {[]},... 'xs', struct('Masking','analysis threshold')); %-Design description - for saving and display %========================================================================== for i = 1:nsess, ntr(i) = length(SPM.Sess(i).U); end Fstr = sprintf('[min] Cutoff: %d {s}',min([SPM.xX.K(:).HParam])); SPM.xsDes = struct(... 'Basis_functions', SPM.xBF.name,... 'Number_of_sessions', sprintf('%d',nsess),... 'Trials_per_session', sprintf('%-3d',ntr),... 'Interscan_interval', sprintf('%0.2f {s}',SPM.xY.RT),... 'High_pass_Filter', sprintf('Cutoff: %d {s}',SPM.xX.K(1).HParam),... 'Global_calculation', SPM.xGX.sGXcalc,... 'Grand_mean_scaling', SPM.xGX.sGMsca,... 'Global_normalisation', SPM.xGX.iGXcalc); %-Save SPM.mat %========================================================================== fprintf('%-40s: ','Saving SPM configuration') %-# if spm_check_version('matlab','7') >=0 save('SPM.mat', 'SPM', '-V6'); else save('SPM.mat', 'SPM'); end fprintf('%30s\n','...SPM.mat saved') %-# %-Display Design report %========================================================================== if ~CmdLine fprintf('%-40s: ','Design reporting') %-# fname = cat(1,{SPM.xY.VY.fname}'); spm_DesRep('DesMtx',SPM.xX,fname,SPM.xsDes) fprintf('%30s\n','...done') %-# end %-End: Cleanup GUI %========================================================================== spm_clf(Finter) spm('FigName','Stats: configured',Finter,CmdLine); spm('Pointer','Arrow') %========================================================================== %- S U B - F U N C T I O N S %========================================================================== function abort = sf_abort %========================================================================== if exist(fullfile(pwd,'SPM.mat'),'file') str = { 'Current directory contains existing SPM file:',... 'Continuing will overwrite existing file!'}; abort = spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename); if abort, fprintf('%-40s: %30s\n\n',... 'Abort... (existing SPM files)',spm('time')), end else abort = 0; end
github
philippboehmsturm/antx-master
spm_input.m
.m
antx-master/freiburgLight/matlab/spm8/spm_input.m
89,728
utf_8
d9477978de23772976e2d790d78bf1f4
function varargout = spm_input(varargin) % Comprehensive graphical and command line input function % FORMATs (given in Programmers Help) %_______________________________________________________________________ % % spm_input handles most forms of interactive user input for SPM. % (File selection is handled by spm_select.m) % % There are five types of input: String, Evaluated, Conditions, Buttons % and Menus: These prompt for string input; string input which is % evaluated to give a numerical result; selection of one item from a % set of buttons; selection of an item from a menu. % % - STRING, EVALUATED & CONDITION input - % For STRING, EVALUATED and CONDITION input types, a prompt is % displayed adjacent to an editable text entry widget (with a lilac % background!). Clicking in the entry widget allows editing, pressing % <RETURN> or <ENTER> enters the result. You must enter something, % empty answers are not accepted. A default response may be pre-specified % in the entry widget, which will then be outlined. Clicking the border % accepts the default value. % % Basic editing of the entry widget is supported *without* clicking in % the widget, provided no other graphics widget has the focus. (If a % widget has the focus, it is shown highlighted with a thin coloured % line. Clicking on the window background returns the focus to the % window, enabling keyboard accelerators.). This enables you to type % responses to a sequence of questions without having to repeatedly % click the mouse in the text widgets. Supported are BackSpace and % Delete, line kill (^U). Other standard ASCII characters are appended % to the text in the entry widget. Press <RETURN> or <ENTER> to submit % your response. % % A ContextMenu is provided (in the figure background) giving access to % relevant utilities including the facility to load input from a file % (see spm_load.m and examples given below): Click the right button on % the figure background. % % For EVALUATED input, the string submitted is evaluated in the base % MatLab workspace (see MatLab's `eval` command) to give a numerical % value. This permits the entry of numerics, matrices, expressions, % functions or workspace variables. I.e.: % i) - a number, vector or matrix e.g. "[1 2 3 4]" % "[1:4]" % "1:4" % ii) - an expression e.g. "pi^2" % "exp(-[1:36]/5.321)" % iii) - a function (that will be invoked) e.g. "spm_load('tmp.dat')" % (function must be on MATLABPATH) "input_cov(36,5.321)" % iv) - a variable from the base workspace % e.g. "tmp" % % The last three options provide a great deal of power: spm_load will % load a matrix from an ASCII data file and return the results. When % called without an argument, spm_load will pop up a file selection % dialog. Alternatively, this facility can be gained from the % ContextMenu. The second example assummes a custom funcion called % input_cov has been written which expects two arguments, for example % the following file saved as input_cov.m somewhere on the MATLABPATH % (~/matlab, the matlab subdirectory of your home area, and the current % directory, are on the MATLABPATH by default): % % function [x] = input_cov(n,decay) % % data input routine - mono-exponential covariate % % FORMAT [x] = input_cov(n,decay) % % n - number of time points % % decay - decay constant % x = exp(-[1:n]/decay); % % Although this example is trivial, specifying large vectors of % empirical data (e.g. reaction times for 72 scans) is efficient and % reliable using this device. In the last option, a variable called tmp % is picked up from the base workspace. To use this method, set the % variables in the MatLab base workspace before starting an SPM % procedure (but after starting the SPM interface). E.g. % >> tmp=exp(-[1:36]/5.321) % % Occasionally a vector of a specific length will be required: This % will be indicated in the prompt, which will start with "[#]", where % # is the length of vector(s) required. (If a matrix is entered then % at least one dimension should equal #.) % % Occasionally a specific type of number will be required. This should % be obvious from the context. If you enter a number of the wrong type, % you'll be alerted and asked to re-specify. The types are i) Real % numbers; ii) Integers; iii) Whole numbers [0,1,2,3,...] & iv) Natural % numbers [1,2,3,...] % % CONDITIONS type input is for getting indicator vectors. The features % of evaluated input described above are complimented as follows: % v) - a compressed list of digits 0-9 e.g. "12121212" % ii) - a list of indicator characters e.g. "abababab" % a-z mapped to 1-26 in alphabetical order, *except* r ("rest") % which is mapped to zero (case insensitive, [A:Z,a:z] only) % ...in addition the response is checked to ensure integer condition indices. % Occasionally a specific number of conditions will be required: This % will be indicated in the prompt, which will end with (#), where # is % the number of conditions required. % % CONTRAST type input is for getting contrast weight vectors. Enter % contrasts as row-vectors. Contrast weight vectors will be padded with % zeros to the correct length, and checked for validity. (Valid % contrasts are estimable, which are those whose weights vector is in % the row-space of the design matrix.) % % Errors in string evaluation for EVALUATED & CONDITION types are % handled gracefully, the user notified, and prompted to re-enter. % % - BUTTON input - % For Button input, the prompt is displayed adjacent to a small row of % buttons. Press the approprate button. The default button (if % available) has a dark outline. Keyboard accelerators are available % (provided no graphics widget has the focus): <RETURN> or <ENTER> % selects the default button (if available). Typing the first character % of the button label (case insensitive) "presses" that button. (If % these Keys are not unique, then the integer keys 1,2,... "press" the % appropriate button.) % % The CommandLine variant presents a simple menu of buttons and prompts % for a selection. Any default response is indicated, and accepted if % an empty line is input. % % % - MENU input - % For Menu input, the prompt is displayed in a pull down menu widget. % Using the mouse, a selection is made by pulling down the widget and % releasing the mouse on the appropriate response. The default response % (if set) is marked with an asterisk. Keyboard accelerators are % available (provided no graphic widget has the focus) as follows: 'f', % 'n' or 'd' move forward to next response down; 'b', 'p' or 'u' move % backwards to the previous response up the list; the number keys jump % to the appropriate response number; <RETURN> or <ENTER> slelects the % currently displayed response. If a default is available, then % pressing <RETURN> or <ENTER> when the prompt is displayed jumps to % the default response. % % The CommandLine variant presents a simple menu and prompts for a selection. % Any default response is indicated, and accepted if an empty line is % input. % % % - Combination BUTTON/EDIT input - % In this usage, you will be presented with a set of buttons and an % editable text widget. Click one of the buttons to choose that option, % or type your response in the edit widget. Any default response will % be shown in the edit widget. The edit widget behaves in the same way % as with the STRING/EVALUATED input, and expects a single number. % Keypresses edit the text widget (rather than "press" the buttons) % (provided no other graphics widget has the focus). A default response % can be selected with the mouse by clicking the thick border of the % edit widget. % % % - Command line - % If YPos is 0 or global CMDLINE is true, then the command line is used. % Negative YPos overrides CMDLINE, ensuring the GUI is used, at % YPos=abs(YPos). Similarly relative YPos beginning with '!' % (E.g.YPos='!+1') ensures the GUI is used. % % spm_input uses the SPM 'Interactive' window, which is 'Tag'ged % 'Interactive'. If there is no such window, then the current figure is % used, or an 'Interactive' window created if no windows are open. % %----------------------------------------------------------------------- % Programers help is contained in the main body of spm_input.m %----------------------------------------------------------------------- % See : input.m (MatLab Reference Guide) % See also : spm_select.m (SPM file selector dialog) % : spm_input.m (Input wrapper function - handles batch mode) %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Andrew Holmes % $Id: spm_input.m 4143 2010-12-22 11:55:43Z guillaume $ %======================================================================= % - FORMAT specifications for programers %======================================================================= % generic - [p,YPos] = spm_input(Prompt,YPos,Type,...) % string - [p,YPos] = spm_input(Prompt,YPos,'s',DefStr) % string+ - [p,YPos] = spm_input(Prompt,YPos,'s+',DefStr) % evaluated - [p,YPos] = spm_input(Prompt,YPos,'e',DefStr,n) % - natural - [p,YPos] = spm_input(Prompt,YPos,'n',DefStr,n,mx) % - whole - [p,YPos] = spm_input(Prompt,YPos,'w',DefStr,n,mx) % - integer - [p,YPos] = spm_input(Prompt,YPos,'i',DefStr,n) % - real - [p,YPos] = spm_input(Prompt,YPos,'r',DefStr,n,mm) % condition - [p,YPos] = spm_input(Prompt,YPos,'c',DefStr,n,m) % contrast - [p,YPos] = spm_input(Prompt,YPos,'x',DefStr,n,X) % permutation- [p,YPos] = spm_input(Prompt,YPos,'p',DefStr,P,n) % button - [p,YPos] = spm_input(Prompt,YPos,'b',Labels,Values,DefItem) % button/edit combo's (edit for string or typed scalar evaluated input) % [p,YPos] = spm_input(Prompt,YPos,'b?1',Labels,Values,DefStr,mx) % ...where ? in b?1 specifies edit widget type as with string & eval'd input % - [p,YPos] = spm_input(Prompt,YPos,'n1',DefStr,mx) % - [p,YPos] = spm_input(Prompt,YPos,'w1',DefStr,mx) % button dialog % - [p,YPos] = spm_input(Prompt,YPos,'bd',... % Labels,Values,DefItem,Title) % menu - [p,YPos] = spm_input(Prompt,YPos,'m',Labels,Values,DefItem) % display - spm_input(Message,YPos,'d',Label) % display - (GUI only) spm_input(Alert,YPos,'d!',Label) % % yes/no - [p,YPos] = spm_input(Prompt,YPos,'y/n',Values,DefItem) % buttons (shortcut) where Labels is a bar delimited string % - [p,YPos] = spm_input(Prompt,YPos,Labels,Values,DefItem) % % NB: Natural numbers are [1:Inf), Whole numbers are [0:Inf) % % -- Parameters (input) -- % % Prompt - prompt string % - Defaults (missing or empty) to 'Enter an expression' % % YPos - (numeric) vertical position {1 - 12} % - overriden by global CMDLINE % - 0 for command line % - negative to force GUI % - (string) relative vertical position E.g. '+1' % - relative to last position used % - overriden by global CMDLINE % - YPos(1)=='!' forces GUI E.g. '!+1' % - '_' is a shortcut for the lowest GUI position % - Defaults (missing or empty) to '+1' % % Type - type of interrogation % - 's'tring % - 's+' multi-line string % - p returned as cellstr (nx1 cell array of strings) % - DefStr can be a cellstr or string matrix % - 'e'valuated string % - 'n'atural numbers % - 'w'hole numbers % - 'i'ntegers % - 'r'eals % - 'c'ondition indicator vector % - 'x' - contrast entry % - If n(2) or design matrix X is specified, then % contrast matrices are padded with zeros to have % correct length. % - if design matrix X is specified, then contrasts are % checked for validity (i.e. in the row-space of X) % (checking handled by spm_SpUtil) % - 'b'uttons % - 'bd' - button dialog: Uses MatLab's questdlg % - For up to three buttons % - Prompt can be a cellstr with a long multiline message % - CmdLine support as with 'b' type % - button/edit combo's: 'be1','bn1','bw1','bi1','br1' % - second letter of b?1 specifies type for edit widget % - 'n1' - single natural number (buttons 1,2,... & edit) % - 'w1' - single whole number (buttons 0,1,... & edit) % - 'm'enu pulldown % - 'y/n' : Yes or No buttons % (See shortcuts below) % - bar delimited string : buttons with these labels % (See shortcuts below) % - Defaults (missing or empty) to 'e' % % DefStr - Default string to be placed in entry widget for string and % evaluated types % - Defaults to '' % % n ('e', 'c' & 'p' types) % - Size of matrix requred % - NaN for 'e' type implies no checking - returns input as evaluated % - length of n(:) specifies dimension - elements specify size % - Inf implies no restriction % - Scalar n expanded to [n,1] (i.e. a column vector) % (except 'x' contrast type when it's [n,np] for np % - E.g: [n,1] & [1,n] (scalar n) prompt for an n-vector, % returned as column or row vector respectively % [1,Inf] & [Inf,1] prompt for a single vector, % returned as column or row vector respectively % [n,Inf] & [Inf,n] prompts for any number of n-vectors, % returned with row/column dimension n respectively. % [a,b] prompts for an 2D matrix with row dimension a and % column dimension b % [a,Inf,b] prompt for a 3D matrix with row dimension a, % page dimension b, and any column dimension. % - 'c' type can only deal with single vectors % - NaN for 'c' type treated as Inf % - Defaults (missing or empty) to NaN % % n ('x'type) % - Number of contrasts required by 'x' type (n(1)) % ( n(2) can be used specify length of contrast vectors if ) % ( a design matrix isn't passed ) % - Defaults (missing or empty) to 1 - vector contrast % % mx ('n', 'w', 'n1', 'w1', 'bn1' & 'bw1' types) % - Maximum value (inclusive) % % mm ('r' type) % - Maximum and minimum values (inclusive) % % m - Number of unique conditions required by 'c' type % - Inf implies no restriction % - Defaults (missing or empty) to Inf - no restriction % % P - set (vector) of numbers of which a permutation is required % % X - Design matrix for contrast checking in 'x' type % - Can be either a straight matrix or a space structure (see spm_sp) % - Column dimension of design matrix specifies length of contrast % vectors (overriding n(2) is specified). % % Title - Title for questdlg in 'bd' type % % Labels - Labels for button and menu types. % - string matrix, one label per row % - bar delimited string % E.g. 'AnCova|Scaling|None' % % Values - Return values corresponding to Labels for button and menu types % - j-th row is returned if button / menu item j is selected % (row vectors are transposed) % - Defaults (missing or empty) to - (button) Labels % - ( menu ) menu item numbers % % DefItem - Default item number, for button and menu types. % % -- Parameters (output) -- % p - results % YPos - Optional second output argument returns GUI position just used % %----------------------------------------------------------------------- % WINDOWS: % % spm_input uses the SPM 'Interactive' 'Tag'ged window. If this isn't % available and no figures are open, an 'Interactive' SPM window is % created (`spm('CreateIntWin')`). If figures are available, then the % current figure is used *unless* it is 'Tag'ged. % %----------------------------------------------------------------------- % SHORTCUTS: % % Buttons SHORTCUT - If the Type parameter is a bar delimited string, then % the Type is taken as 'b' with the specified labels, and the next parameter % (if specified) is taken for the Values. % % Yes/No question shortcut - p = spm_input(Prompt,YPos,'y/n') expands % to p = spm_input(Prompt,YPos,'b','yes|no',...), enabling easy use of % spm_input for yes/no dialogue. Values defaults to 'yn', so 'y' or 'n' % is returned as appropriate. % %----------------------------------------------------------------------- % EXAMPLES: % ( Specified YPos is overriden if global CMDLINE is ) % ( true, when the command line versions are used. ) % % p = spm_input % Command line input of an evaluated string, default prompt. % p = spm_input('Enter a value',1) % Evaluated string input, prompted by 'Enter a value', in % position 1 of the dialog figure. % p = spm_input(str,'+1','e',0.001) % Evaluated string input, prompted by contents of string str, % in next position of the dialog figure. % Default value of 0.001 offered. % p = spm_input(str,2,'e',[],5) % Evaluated string input, prompted by contents of string str, % in second position of the dialog figure. % Vector of length 5 required - returned as column vector % p = spm_input(str,2,'e',[],[Inf,5]) % ...as above, but can enter multiple 5-vectors in a matrix, % returned with 5-vectors in rows % p = spm_input(str,0,'c','ababab') % Condition string input, prompted by contents of string str % Uses command line interface. % Default string of 'ababab' offered. % p = spm_input(str,0,'c','010101') % As above, but default string of '010101' offered. % [p,YPos] = spm_input(str,'0','s','Image') % String input, same position as last used, prompted by str, % default of 'Image' offered. YPos returns GUI position used. % p = spm_input(str,'-1','y/n') % Yes/No buttons for question with prompt str, in position one % before the last used Returns 'y' or 'n'. % p = spm_input(str,'-1','y/n',[1,0],2) % As above, but returns 1 for yes response, 0 for no, % with 'no' as the default response % p = spm_input(str,4,'AnCova|Scaling') % Presents two buttons labelled 'AnCova' & 'Scaling', with % prompt str, in position 4 of the dialog figure. Returns the % string on the depresed button, where buttons can be pressed % with the mouse or by the respective keyboard accelerators % 'a' & 's' (or 'A' & 'S'). % p = spm_input(str,-4,'b','AnCova|Scaling',[],2) % As above, but makes "Scaling" the default response, and % overrides global CMDLINE % p = spm_input(str,0,'b','AnCova|Scaling|None',[1,2,3]) % Prompts for [A]ncova / [S]caling / [N]one in MatLab command % window, returns 1, 2, or 3 according to the first character % of the entered string as one of 'a', 's', or 'n' (case % insensitive). % p = spm_input(str,1,'b','AnCova',1) % Since there's only one button, this just displays the response % in GUI position 1 (or on the command line if global CMDLINE % is true), and returns 1. % p = spm_input(str,'+0','br1','None|Mask',[-Inf,NaN],0.8) % Presents two buttons labelled "None" & "Mask" (which return % -Inf & NaN if clicked), together with an editable text widget % for entry of a single real number. The default of 0.8 is % initially presented in the edit window, and can be selected by % pressing return. % Uses the previous GUI position, unless global CMDLINE is true, % in which case a command-line equivalent is used. % p = spm_input(str,'+0','w1') % Prompts for a single whole number using a combination of % buttons and edit widget, using the previous GUI position, % or the command line if global CMDLINE is true. % p = spm_input(str,'!0','m','Single Subject|Multi Subject|Multi Study') % Prints the prompt str in a pull down menu containing items % 'Single Subject', 'Multi Subject' & 'Multi Study'. When OK is % clicked p is returned as the index of the choice, 1,2, or 3 % respectively. Uses last used position in GUI, irrespective of % global CMDLINE % p = spm_input(str,5,'m',... % 'Single Subject|Multi Subject|Multi Study',... % ['SS';'MS';'SP'],2) % As above, but returns strings 'SS', 'MS', or 'SP' according to % the respective choice, with 'MS; as the default response. % p = spm_input(str,0,'m',... % 'Single Subject|Multi Subject|Multi Study',... % ['SS';'MS';'SP'],2) % As above, but the menu is presented in the command window % as a numbered list. % spm_input('AnCova, GrandMean scaling',0,'d') % Displays message in a box in the MatLab command window % [null,YPos]=spm_input('Session 1','+1','d!','fMRI') % Displays 'fMRI: Session 1' in next GUI position of the % 'Interactive' window. If CMDLINE is 1, then nothing is done. % Position used is returned in YPos. % %----------------------------------------------------------------------- % FORMAT h = spm_input(Prompt,YPos,'m!',Labels,cb,UD,XCB); % GUI PullDown menu utility - creates a pulldown menu in the Interactive window % FORMAT H = spm_input(Prompt,YPos,'b!',Labels,cb,UD,XCB); % GUI Buttons utility - creates GUI buttons in the Interactive window % % Prompt, YPos, Labels - as with 'm'enu/'b'utton types % cb - CallBack string % UD - UserData % XCB - Extended CallBack handling - allows different CallBack for each item, % and use of UD in CallBack strings. [Defaults to 1 for PullDown type % when multiple CallBacks specified, 0 o/w.] % H - Handle of 'PullDown' uicontrol / 'Button's % % In "normal" mode (when XCB is false), this is essentially a utility % to create a PullDown menu widget or set of buttons in the SPM % 'Interactive' figure, using positioning and Label definition % conveniences of the spm_input 'm'enu & 'b'utton types. If Prompt is % not empty, then the PullDown/Buttons appears on the right, with the % Prompt on the left, otherwise the PullDown/Buttons use the whole % width of the Interactive figure. The PopUp's CallBack string is % specified in cb, and [optional] UserData may be passed as UD. % % For buttons, a separate callback can be specified for each button, by % passing the callbacks corresponding to the Labels as rows of a % cellstr or string matrix. % % This "different CallBacks" facility can also be extended to the % PullDown type, using the "extended callback" mode (when XCB is % true). % In addition, in "extended callback", you can use UD to % refer to the UserData argument in the CallBack strings. (What happens % is this: The cb & UD are stored as fields in the PopUp's UserData % structure, and the PopUp's callback is set to spm_input('!m_cb'), % which reads UD into the functions workspace and eval's the % appropriate CallBack string. Note that this means that base % workspace variables are inaccessible (put what you need in UD), and % that any return arguments from CallBack functions are not passed back % to the base workspace). % % %----------------------------------------------------------------------- % UTILITY FUNCTIONS: % % FORMAT colour = spm_input('!Colour') % Returns colour for input widgets, as specified in COLOUR parameter at % start of code. % colour - [r,g,b] colour triple % % FORMAT [iCond,msg] = spm_input('!iCond',str,n,m) % Parser for special 'c'ondition type: Handles digit strings and % strings of indicator chars. % str - input string % n - length of condition vector required [defaut Inf - no restriction] % m - number of conditions required [default Inf - no restrictions] % iCond - Integer condition indicator vector % msg - status message % % FORMAT hM = spm_input('!InptConMen',Finter,H) % Sets a basic Input ContextMenu for the figure % Finter - figure to set menu in % H - handles of objects to delete on "crash out" option % hM - handle of UIContextMenu % % FORMAT [CmdLine,YPos] = spm_input('!CmdLine',YPos) % Sorts out whether to use CmdLine or not & canonicalises YPos % CmdLine - Binary flag % YPos - Position index % % FORMAT Finter = spm_input('!GetWin',F) % Locates (or creates) figure to work in % F - Interactive Figure, defaults to 'Interactive' % Finter - Handle of figure to use % % FORMAT [PLoc,cF] = spm_input('!PointerJump',RRec,F,XDisp) % Raise window & jump pointer over question % RRec - Response rectangle of current question % F - Interactive Figure, Defaults to 'Interactive' % XDisp - X-displacement of cursor relative to RRec % PLoc - Pointer location before jumping % cF - Current figure before making F current. % % FORMAT [PLoc,cF] = spm_input('!PointerJumpBack',PLoc,cF) % Replace pointer and reset CurrentFigure back % PLoc - Pointer location before jumping % cF - Previous current figure % % FORMAT spm_input('!PrntPrmpt',Prompt,TipStr,Title) % Print prompt for CmdLine questioning % Prompt - prompt string, callstr, or string matrix % TipStr - tip string % Title - title string % % FORMAT [Frec,QRec,PRec,RRec] = spm_input('!InputRects',YPos,rec,F) % Returns rectangles (pixels) used in GUI % YPos - Position index % rec - Rectangle specifier: String, one of 'Frec','QRec','PRec','RRec' % Defaults to '', which returns them all. % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % FRec - Position of interactive window % QRec - Position of entire question % PRec - Position of prompt % RRec - Position of response % % FORMAT spm_input('!DeleteInputObj',F) % Deltes input objects (only) from figure F % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % % FORMAT [CPos,hCPos] = spm_input('!CurrentPos',F) % Returns currently used GUI question positions & their handles % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % CPos - Vector of position indices % hCPos - (n x CPos) matrix of object handles % % FORMAT h = spm_input('!FindInputObj',F) % Returns handles of input GUI objects in figure F % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % h - vector of object handles % % FORMAT [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine) % Returns next position index, specified by YPos % YPos - Absolute (integer) or relative (string) position index % Defaults to '+1' % F - Interactive Figure, defaults to spm_figure('FindWin','Interactive') % CmdLine - Command line? Defaults to spm_input('!CmdLine',YPos) % NPos - Next position index % CPos & hCPos - as for !CurrentPos % % FORMAT NPos = spm_input('!SetNextPos',YPos,F,CmdLine) % Sets up for input at next position index, specified by YPos. This utility % function can be used stand-alone to implicitly set the next position % by clearing positions NPos and greater. % YPos - Absolute (integer) or relative (string) position index % Defaults to '+1' % F - Interactive Figure, defaults to spm_figure('FindWin','Interactive') % CmdLine - Command line? Defaults to spm_input('!CmdLine',YPos) % NPos - Next position index % % FORMAT MPos = spm_input('!MaxPos',F,FRec3) % Returns maximum position index for figure F % F - Interactive Figure, Defaults to spm_figure('FindWin','Interactive') % Not required if FRec3 is specified % FRec3 - Length of interactive figure in pixels % % FORMAT spm_input('!EditableKeyPressFcn',h,ch) % KeyPress callback for GUI string / eval input % % FORMAT spm_input('!ButtonKeyPressFcn',h,Keys,DefItem,ch) % KeyPress callback for GUI buttons % % FORMAT spm_input('!PullDownKeyPressFcn',h,ch,DefItem) % KeyPress callback for GUI pulldown menus % % FORMAT spm_input('!m_cb') % Extended CallBack handler for 'p' PullDown utility type % % FORMAT spm_input('!dScroll',h,str) % Scroll text string in object h % h - handle of text object % Prompt - Text to scroll (Defaults to 'UserData' of h) % %----------------------------------------------------------------------- % SUBFUNCTIONS: % % FORMAT [Keys,Labs] = sf_labkeys(Labels) % Make unique character keys for the Labels, ignoring case. % Used with 'b'utton types. % % FORMAT [p,msg] = sf_eEval(str,Type,n,m) % Common code for evaluating various input types. % % FORMAT str = sf_SzStr(n,l) % Common code to construct prompt strings for pre-specified vector/matrix sizes % % FORMAT [p,msg] = sf_SzChk(p,n,msg) % Common code to check (& canonicalise) sizes of input vectors/matrices % %_______________________________________________________________________ % @(#)spm_input.m 2.8 Andrew Holmes 03/03/04 %-Parameters %======================================================================= PJump = 1; %-Jumping of pointer to question? TTips = 1; %-Use ToolTipStrings? (which can be annoying!) ConCrash = 1; %-Add "crash out" option to 'Interactive'fig.ContextMenu %-Condition arguments %======================================================================= if nargin<1||isempty(varargin{1}), Prompt=''; else Prompt=varargin{1}; end if ~isempty(Prompt) && ischar(Prompt) && Prompt(1)=='!' %-Utility functions have Prompt string starting with '!' Type = Prompt; else %-Should be an input request: get Type & YPos if nargin<3||isempty(varargin{3}), Type='e'; else Type=varargin{3}; end if any(Type=='|'), Type='b|'; end if nargin<2||isempty(varargin{2}), YPos='+1'; else YPos=varargin{2}; end [CmdLine,YPos] = spm_input('!CmdLine',YPos); if ~CmdLine %-Setup for GUI use %-Locate (or create) figure to work in Finter = spm_input('!GetWin'); COLOUR = get(Finter,'Color'); %-Find out which Y-position to use, setup for use YPos = spm_input('!SetNextPos',YPos,Finter,CmdLine); %-Determine position of objects [FRec,QRec,PRec,RRec]=spm_input('!InputRects',YPos,'',Finter); end end switch lower(Type) case {'s','s+','e','n','w','i','r','c','x','p'} %-String and evaluated input %======================================================================= %-Condition arguments if nargin<6||isempty(varargin{6}), m=[]; else m=varargin{6}; end if nargin<5||isempty(varargin{5}), n=[]; else n=varargin{5}; end if nargin<4, DefStr=''; else DefStr=varargin{4}; end if strcmpi(Type,'s+') %-DefStr should be a cellstr for 's+' type. if isempty(DefStr), DefStr = {}; else DefStr = cellstr(DefStr); end DefStr = DefStr(:); else %-DefStr needs to be a string if ~ischar(DefStr), DefStr=num2str(DefStr); end DefStr = DefStr(:)'; end strM=''; switch lower(Type) %-Type specific defaults/setup case 's', TTstr='enter string'; case 's+',TTstr='enter string - multi-line'; case 'e', TTstr='enter expression to evaluate'; case 'n', TTstr='enter expression - natural number(s)'; if ~isempty(m), strM=sprintf(' (in [1,%d])',m); TTstr=[TTstr,strM]; end case 'w', TTstr='enter expression - whole number(s)'; if ~isempty(m), strM=sprintf(' (in [0,%d])',m); TTstr=[TTstr,strM]; end case 'i', TTstr='enter expression - integer(s)'; case 'r', TTstr='enter expression - real number(s)'; if ~isempty(m), TTstr=[TTstr,sprintf(' in [%g,%g]',min(m),max(m))]; end case 'c', TTstr='enter indicator vector e.g. 0101... or abab...'; if ~isempty(m) && isfinite(m), strM=sprintf(' (%d)',m); end case 'x', TTstr='enter contrast matrix'; case 'p', if isempty(n), error('permutation of what?'), else P=n(:)'; end if isempty(m), n = [1,length(P)]; end m = P; if isempty(setxor(m,[1:max(m)])) TTstr=['enter permutation of [1:',num2str(max(m)),']']; else TTstr=['enter permutation of [',num2str(m),']']; end otherwise TTstr='enter expression'; end strN = sf_SzStr(n); if CmdLine %-Use CmdLine to get answer %----------------------------------------------------------------------- spm_input('!PrntPrmpt',[Prompt,strN,strM],TTstr) %-Do Eval Types in Base workspace, catch errors switch lower(Type), case 's' if ~isempty(DefStr) Prompt=[Prompt,' (Default: ',DefStr,' )']; end str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end while isempty(str) spm('Beep') fprintf('! %s : enter something!\n',mfilename) str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end end p = str; msg = ''; case 's+' fprintf(['Multi-line input: Type ''.'' on a line',... ' of its own to terminate input.\n']) if ~isempty(DefStr) fprintf('Default : (press return to accept)\n') fprintf(' : %s\n',DefStr{:}) end fprintf('\n') str = input('l001 : ','s'); while (isempty(str) || strcmp(str,'.')) && isempty(DefStr) spm('Beep') fprintf('! %s : enter something!\n',mfilename) str = input('l001 : ','s'); end if isempty(str) %-Accept default p = DefStr; else %-Got some input, allow entry of additional lines p = {str}; str = input(sprintf('l%03u : ',length(p)+1),'s'); while ~strcmp(str,'.') p = [p;{str}]; str = input(sprintf('l%03u : ',length(p)+1),'s'); end end msg = ''; otherwise if ~isempty(DefStr) Prompt=[Prompt,' (Default: ',DefStr,' )']; end str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end [p,msg] = sf_eEval(str,Type,n,m); while ischar(p) spm('Beep'), fprintf('! %s : %s\n',mfilename,msg) str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end [p,msg] = sf_eEval(str,Type,n,m); end end if ~isempty(msg), fprintf('\t%s\n',msg), end else %-Use GUI to get answer %----------------------------------------------------------------------- %-Create text and edit control objects %--------------------------------------------------------------- hPrmpt = uicontrol(Finter,'Style','Text',... 'String',[strN,Prompt,strM],... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData','',... 'BackgroundColor',COLOUR,... 'HorizontalAlignment','Right',... 'Position',PRec); if TTips, set(hPrmpt,'ToolTipString',[strN,Prompt,strM]); end %-Default button surrounding edit widget (if a DefStr given) %-Callback sets hPrmpt UserData, and EditWidget string, to DefStr % (Buttons UserData holds handles [hPrmpt,hEditWidget], set later) cb = ['set(get(gcbo,''UserData'')*[1;0],''UserData'',',... 'get(gcbo,''String'')),',... 'set(get(gcbo,''UserData'')*[0;1],''String'',',... 'get(gcbo,''String''))']; if ~isempty(DefStr) if iscellstr(DefStr), str=[DefStr{1},'...']; else str=DefStr; end hDef = uicontrol(Finter,'Style','PushButton',... 'String',DefStr,... 'ToolTipString',... ['Click on border to accept default: ' str],... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData',[],... 'BackgroundColor',COLOUR,... 'CallBack',cb,... 'Position',RRec+[-2,-2,+4,+4]); else hDef = []; end %-Edit widget: Callback puts string into hPrompts UserData cb = 'set(get(gcbo,''UserData''),''UserData'',get(gcbo,''String''))'; h = uicontrol(Finter,'Style','Edit',... 'String',DefStr,... 'Max',strcmpi(Type,'s+')+1,... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData',hPrmpt,... 'CallBack',cb,... 'Horizontalalignment','Left',... 'BackgroundColor','w',... 'Position',RRec); set(hDef,'UserData',[hPrmpt,h]) uifocus(h); if TTips, set(h,'ToolTipString',TTstr), end %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPrmpt,hDef,h]); cb = [ 'set(get(gcbo,''UserData''),''String'',',... '[''spm_load('''''',spm_select(1),'''''')'']), ',... 'set(get(get(gcbo,''UserData''),''UserData''),''UserData'',',... 'get(get(gcbo,''UserData''),''String''))']; uimenu(hM,'Label','load from text file','Separator','on',... 'CallBack',cb,'UserData',h) %-Bring window to fore & jump pointer to edit widget [PLoc,cF] = spm_input('!PointerJump',RRec,Finter); %-Setup FigureKeyPressFcn for editing of entry widget without clicking set(Finter,'KeyPressFcn',[... 'spm_input(''!EditableKeyPressFcn'',',... 'findobj(gcf,''Tag'',''GUIinput_',int2str(YPos),''',',... '''Style'',''edit''),',... 'get(gcbf,''CurrentCharacter''))']) %-Wait for edit, do eval Types in Base workspace, catch errors %--------------------------------------------------------------- waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input window cleared whilst waiting ',... 'for response: Bailing out!']), end str = get(hPrmpt,'UserData'); switch lower(Type), case 's' p = str; msg = ''; case 's+' p = cellstr(str); msg = ''; otherwise [p,msg] = sf_eEval(str,Type,n,m); while ischar(p) set(h,'Style','Text',... 'String',msg,'HorizontalAlignment','Center',... 'ForegroundColor','r') spm('Beep'), pause(2) set(h,'Style','Edit',... 'String',str,... 'HorizontalAlignment','Left',... 'ForegroundColor','k') %set(hPrmpt,'UserData',''); waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input window cleared ',... 'whilst waiting for response: Bailing out!']),end str = get(hPrmpt,'UserData'); [p,msg] = sf_eEval(str,Type,n,m); end end %-Fix edit window, clean up, reposition pointer, set CurrentFig back delete([hM,hDef]), set(Finter,'KeyPressFcn','') set(h,'Style','Text','HorizontalAlignment','Center',... 'ToolTipString',msg,... 'BackgroundColor',COLOUR) spm_input('!PointerJumpBack',PLoc,cF) drawnow end % (if CmdLine) %-Return response %----------------------------------------------------------------------- varargout = {p,YPos}; case {'b','bd','b|','y/n','be1','bn1','bw1','bi1','br1',... '-n1','n1','-w1','w1','m'} %-'b'utton & 'm'enu Types %======================================================================= %-Condition arguments switch lower(Type), case {'b','be1','bi1','br1','m'} m = []; Title = ''; if nargin<6, DefItem=[]; else DefItem=varargin{6}; end if nargin<5, Values=[]; else Values =varargin{5}; end if nargin<4, Labels=''; else Labels =varargin{4}; end case 'bd' if nargin<7, Title=''; else Title =varargin{7}; end if nargin<6, DefItem=[]; else DefItem=varargin{6}; end if nargin<5, Values=[]; else Values =varargin{5}; end if nargin<4, Labels=''; else Labels =varargin{4}; end case 'y/n' Title = ''; if nargin<5, DefItem=[]; else DefItem=varargin{5}; end if nargin<4, Values=[]; else Values =varargin{4}; end if isempty(Values), Values='yn'; end Labels = {'yes','no'}; case 'b|' Title = ''; if nargin<5, DefItem=[]; else DefItem=varargin{5}; end if nargin<4, Values=[]; else Values =varargin{4}; end Labels = varargin{3}; case 'bn1' if nargin<7, m=[]; else m=varargin{7}; end if nargin<6, DefItem=[]; else DefItem=varargin{6}; end if nargin<5, Values=[]; else Values =varargin{5}; end if nargin<4, Labels=[1:5]'; Values=[1:5]; Type='-n1'; else Labels=varargin{4}; end case 'bw1' if nargin<7, m=[]; else m=varargin{7}; end if nargin<6, DefItem=[]; else DefItem=varargin{6}; end if nargin<5, Values=[]; else Values =varargin{5}; end if nargin<4, Labels=[0:4]'; Values=[0:4]; Type='-w1'; else Labels=varargin{4}; end case {'-n1','n1','-w1','w1'} if nargin<5, m=[]; else m=varargin{5}; end if nargin<4, DefItem=[]; else DefItem=varargin{4}; end switch lower(Type) case {'n1','-n1'}, Labels=[1:min([5,m])]'; Values=Labels'; Type='-n1'; case {'w1','-w1'}, Labels=[0:min([4,m])]'; Values=Labels'; Type='-w1'; end end %-Check some labels were specified if isempty(Labels), error('No Labels specified'), end if iscellstr(Labels), Labels=char(Labels); end %-Convert Labels "option" string to string matrix if required if ischar(Labels) && any(Labels(:)=='|') OptStr=Labels; BarPos=find([OptStr=='|',1]); Labels=OptStr(1:BarPos(1)-1); for Bar = 2:sum(OptStr=='|')+1 Labels=strvcat(Labels,OptStr(BarPos(Bar-1)+1:BarPos(Bar)-1)); end end %-Set default Values for the Labels if isempty(Values) if strcmpi(Type,'m') Values=[1:size(Labels,1)]'; else Values=Labels; end else %-Make sure Values are in rows if size(Labels,1)>1 && size(Values,1)==1, Values = Values'; end %-Check numbers of Labels and Values match if (size(Labels,1)~=size(Values,1)) error('Labels & Values incompatible sizes'), end end %-Numeric Labels to strings if isnumeric(Labels) tmp = Labels; Labels = cell(size(tmp,1),1); for i=1:numel(tmp), Labels{i}=num2str(tmp(i,:)); end Labels=char(Labels); end switch lower(Type), case {'b','bd','b|','y/n'} %-Process button types %======================================================================= %-Make unique character keys for the Labels, sort DefItem %--------------------------------------------------------------- nLabels = size(Labels,1); [Keys,Labs] = sf_labkeys(Labels); if ~isempty(DefItem) && any(DefItem==[1:nLabels]) DefKey = Keys(DefItem); else DefItem = 0; DefKey = ''; end if CmdLine %-Display question prompt spm_input('!PrntPrmpt',Prompt,'',Title) %-Build prompt %------------------------------------------------------- if ~isempty(Labs) Prmpt = ['[',Keys(1),']',deblank(Labs(1,:)),' ']; for i = 2:nLabels Prmpt=[Prmpt,'/ [',Keys(i),']',deblank(Labs(i,:)),' ']; end else Prmpt = ['[',Keys(1),'] ']; for i = 2:nLabels, Prmpt=[Prmpt,'/ [',Keys(i),'] ']; end end if DefItem Prmpt = [Prmpt,... ' (Default: ',deblank(Labels(DefItem,:)),')']; end %-Ask for user response %------------------------------------------------------- if nLabels==1 %-Only one choice - auto-pick & display k = 1; fprintf('%s: %s\t(only option)',Prmpt,Labels) else str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end while isempty(str) || ~any(lower(Keys)==lower(str(1))) if ~isempty(str),fprintf('%c\t!Out of range\n',7),end str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end end k = find(lower(Keys)==lower(str(1))); end fprintf('\n') p = Values(k,:); if ischar(p), p=deblank(p); end elseif strcmpi(Type,'bd') if nLabels>3, error('at most 3 labels for GUI ''bd'' type'), end tmp = cellstr(Labels); if DefItem tmp = [tmp; tmp(DefItem)]; Prompt = cellstr(Prompt); Prompt=Prompt(:); Prompt = [Prompt;{' '};... {['[default: ',tmp{DefItem},']']}]; else tmp = [tmp; tmp(1)]; end k = min(find(strcmp(tmp,... questdlg(Prompt,sprintf('%s%s: %s...',spm('ver'),... spm('GetUser',' (%s)'),Title),tmp{:})))); p = Values(k,:); if ischar(p), p=deblank(p); end else Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets %-Create text and edit control objects %-'UserData' of prompt contains answer %------------------------------------------------------- hPrmpt = uicontrol(Finter,'Style','Text',... 'String',Prompt,... 'Tag',Tag,... 'UserData',[],... 'BackgroundColor',COLOUR,... 'HorizontalAlignment','Right',... 'Position',PRec); if TTips, set(hPrmpt,'ToolTipString',Prompt); end if nLabels==1 %-Only one choice - auto-pick k = 1; else %-Draw buttons and process response dX = RRec(3)/nLabels; if TTips, str = ['select with mouse or use kbd: ',... sprintf('%c/',Keys(1:end-1)),Keys(end)]; else str=''; end %-Store button # in buttons 'UserData' property %-Store handle of prompt string in buttons 'Max' property %-Button callback sets UserData of prompt string to % number of pressed button cb = ['set(get(gcbo,''Max''),''UserData'',',... 'get(gcbo,''UserData''))']; H = []; XDisp = []; for i=1:nLabels if i==DefItem %-Default button, outline it h = uicontrol(Finter,'Style','Frame',... 'BackGroundColor','k',... 'ForeGroundColor','k',... 'Tag',Tag,... 'Position',... [RRec(1)+(i-1)*dX ... RRec(2)-1 dX RRec(4)+2]); XDisp = (i-1/3)*dX; H = [H,h]; end h = uicontrol(Finter,'Style','Pushbutton',... 'String',deblank(Labels(i,:)),... 'ToolTipString',sprintf('%s\n%s',deblank(Labels(i,:)),str),... 'Tag',Tag,... 'Max',hPrmpt,... 'UserData',i,... 'BackgroundColor',COLOUR,... 'Callback',cb,... 'Position',[RRec(1)+(i-1)*dX+1 ... RRec(2) dX-2 RRec(4)]); if i == DefItem, uifocus(h); end H = [H,h]; end %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPrmpt,H]); %-Bring window to fore & jump pointer to default button [PLoc,cF]=spm_input('!PointerJump',RRec,Finter,XDisp); %-Callback for KeyPress, to store valid button # in % UserData of Prompt, DefItem if (DefItem~=0) % & return (ASCII-13) is pressed set(Finter,'KeyPressFcn',... ['spm_input(''!ButtonKeyPressFcn'',',... 'findobj(gcf,''Tag'',''',Tag,''',',... '''Style'',''text''),',... '''',lower(Keys),''',',num2str(DefItem),',',... 'get(gcbf,''CurrentCharacter''))']) %-Wait for button press, process results %----------------------------------------------- waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt) error(['Input objects cleared whilst ',... 'waiting for response: Bailing out!']) end k = get(hPrmpt,'UserData'); %-Clean up delete([H,hM]), set(Finter,'KeyPressFcn','') spm_input('!PointerJumpBack',PLoc,cF) end %-Display answer uicontrol(Finter,'Style','Text',... 'String',deblank(Labels(k,:)),... 'Tag',Tag,... 'Horizontalalignment','Center',... 'BackgroundColor',COLOUR,... 'Position',RRec); drawnow p = Values(k,:); if ischar(p), p=deblank(p); end end case {'be1','bn1','bw1','bi1','br1','-n1','-w1'} %-Process button/entry combo types %======================================================================= if ischar(DefItem), DefStr=DefItem; else DefStr=num2str(DefItem); end if isempty(m), strM=''; else strM=sprintf(' (<=%d)',m); end if CmdLine %-Process default item %--------------------------------------------------------------- if ~isempty(DefItem) [DefVal,msg] = sf_eEval(DefStr,Type(2),1); if ischar(DefVal), error(['Invalid DefItem: ',msg]), end Labels = strvcat(Labels,DefStr); Values = [Values;DefVal]; DefItem = size(Labels,1); end %-Add option to specify... Labels = strvcat(Labels,'specify...'); %-Process options nLabels = size(Labels,1); [Keys,Labs] = sf_labkeys(Labels); if ~isempty(DefItem), DefKey = Keys(DefItem); else DefKey = ''; end %-Print banner prompt %--------------------------------------------------------------- spm_input('!PrntPrmpt',Prompt) %-Display question prompt if Type(1)=='-' %-No special buttons - go straight to input k = size(Labels,1); else %-Offer buttons, default or "specify..." %-Build prompt %------------------------------------------------------- if ~isempty(Labs) Prmpt = ['[',Keys(1),']',deblank(Labs(1,:)),' ']; for i = 2:nLabels Prmpt=[Prmpt,'/ [',Keys(i),']',deblank(Labs(i,:)),' ']; end else Prmpt = ['[',Keys(1),'] ']; for i = 2:nLabels, Prmpt=[Prmpt,'/ [',Keys(i),'] ']; end end if DefItem, Prmpt = [Prmpt,... ' (Default: ',deblank(Labels(DefItem,:)),')']; end %-Ask for user response %------------------------------------------------------- if nLabels==1 %-Only one choice - auto-pick & display k = 1; fprintf('%s: %s\t(only option)',Prmpt,Labels) else str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end while isempty(str) || ~any(lower(Keys)==lower(str(1))) if ~isempty(str),fprintf('%c\t!Invalid response\n',7),end str = input([Prmpt,'? '],'s'); if isempty(str), str=DefKey; end end k = find(lower(Keys)==lower(str(1))); end fprintf('\n') end %-Process response: prompt for value if "specify..." option chosen %=============================================================== if k<size(Labels,1) p = Values(k,:); if ischar(p), p=deblank(p); end else %-"specify option chosen: ask user to specify %------------------------------------------------------- switch lower(Type(2)) case 's', tstr=' string'; case 'e', tstr='n expression'; case 'n', tstr=' natural number'; case 'w', tstr=' whole number'; case 'i', tstr='n integer'; case 'r', tstr=' real number'; otherwise, tstr=''; end Prompt = sprintf('%s (a%s%s)',Prompt,tstr,strM); if ~isempty(DefStr) Prompt=sprintf('%s\b, default %s)',Prompt,DefStr); end str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end %-Eval in Base workspace, catch errors [p,msg] = sf_eEval(str,Type(2),1,m); while ischar(p) spm('Beep'), fprintf('! %s : %s\n',mfilename,msg) str = input([Prompt,' : '],'s'); if isempty(str), str=DefStr; end [p,msg] = sf_eEval(str,Type(2),1,m); end end else Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets nLabels = size(Labels,1); %-#buttons %-Create text and edit control objects %-'UserData' of prompt contains answer %--------------------------------------------------------------- hPrmpt = uicontrol(Finter,'Style','Text',... 'String',[Prompt,strM],... 'Tag',Tag,... 'UserData',[],... 'BackgroundColor',COLOUR,... 'HorizontalAlignment','Right',... 'Position',PRec); if TTips, set(hPrmpt,'ToolTipString',[Prompt,strM]); end %-Draw buttons & entry widget, & process response dX = RRec(3)*(2/3)/nLabels; %-Store button # in buttons 'UserData' %-Store handle of prompt string in buttons 'Max' property %-Callback sets UserData of prompt string to button number. cb = ['set(get(gcbo,''Max''),''UserData'',get(gcbo,''UserData''))']; if TTips, str=sprintf('select by mouse or enter value in text widget'); else str=''; end H = []; for i=1:nLabels h = uicontrol(Finter,'Style','Pushbutton',... 'String',deblank(Labels(i,:)),... 'Max',hPrmpt,... 'ToolTipString',sprintf('%s\n%s',deblank(Labels(i,:)),str),... 'Tag',Tag,... 'UserData',i,... 'BackgroundColor',COLOUR,... 'Callback',cb,... 'Position',[RRec(1)+(i-1)*dX+1 RRec(2) dX-2 RRec(4)]); H = [H,h]; end %-Default button surrounding edit widget (if a DefStr given) %-Callback sets hPrmpt UserData, and EditWidget string, to DefStr % (Buttons UserData holds handles [hPrmpt,hEditWidget], set later) cb = ['set(get(gcbo,''UserData'')*[1;0],''UserData'',',... 'get(gcbo,''String'')),',... 'set(get(gcbo,''UserData'')*[0;1],''String'',',... 'get(gcbo,''String''))']; if ~isempty(DefStr) hDef = uicontrol(Finter,'Style','PushButton',... 'String',DefStr,... 'ToolTipString',['Click on border to accept ',... 'default: ' DefStr],... 'Tag',Tag,... 'UserData',[],... 'CallBack',cb,... 'BackgroundColor',COLOUR,... 'Position',... [RRec(1)+RRec(3)*(2/3) RRec(2)-2 RRec(3)/3+2 RRec(4)+4]); H = [H,hDef]; else hDef = []; end %-Edit widget: Callback puts string into hPrompts UserData cb = ['set(get(gcbo,''UserData''),''UserData'',get(gcbo,''String''))']; h = uicontrol(Finter,'Style','Edit',... 'String',DefStr,... 'ToolTipString',str,... 'Tag',Tag,... 'UserData',hPrmpt,... 'CallBack',cb,... 'Horizontalalignment','Center',... 'BackgroundColor','w',... 'Position',... [RRec(1)+RRec(3)*(2/3)+2 RRec(2) RRec(3)/3-2 RRec(4)]); set(hDef,'UserData',[hPrmpt,h]) uifocus(h); H = [H,h]; %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPrmpt,H]); %-Bring window to fore & jump pointer to default button [PLoc,cF] = spm_input('!PointerJump',RRec,Finter,RRec(3)*0.95); %-Setup FigureKeyPressFcn for editing of entry widget without clicking set(Finter,'KeyPressFcn',[... 'spm_input(''!EditableKeyPressFcn'',',... 'findobj(gcf,''Tag'',''GUIinput_',int2str(YPos),''',',... '''Style'',''edit''),',... 'get(gcbf,''CurrentCharacter''))']) %-Wait for button press, process results %--------------------------------------------------------------- waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input objects cleared whilst waiting ',... 'for response: Bailing out!']), end p = get(hPrmpt,'UserData'); if ~ischar(p) k = p; p = Values(k,:); if ischar(p), p=deblank(p); end else Labels = strvcat(Labels,'specify...'); k = size(Labels,1); [p,msg] = sf_eEval(p,Type(2),1,m); while ischar(p) set(H,'Visible','off') h = uicontrol('Style','Text','String',msg,... 'Horizontalalignment','Center',... 'ForegroundColor','r',... 'BackgroundColor',COLOUR,... 'Tag',Tag,'Position',RRec); spm('Beep') pause(2), delete(h), set(H,'Visible','on') set(hPrmpt,'UserData','') waitfor(hPrmpt,'UserData') if ~ishandle(hPrmpt), error(['Input objects cleared ',... 'whilst waiting for response: Bailing out!']),end p = get(hPrmpt,'UserData'); if ischar(p), [p,msg] = sf_eEval(p,Type(2),1,m); end end end %-Clean up delete([H,hM]), set(Finter,'KeyPressFcn','') spm_input('!PointerJumpBack',PLoc,cF) %-Display answer uicontrol(Finter,'Style','Text',... 'String',num2str(p),... 'Tag',Tag,... 'Horizontalalignment','Center',... 'BackgroundColor',COLOUR,... 'Position',RRec); drawnow end % (if CmdLine) case 'm' %-Process menu type %======================================================================= nLabels = size(Labels,1); if ~isempty(DefItem) && ~any(DefItem==[1:nLabels]), DefItem=[]; end %-Process pull down menu type if CmdLine spm_input('!PrntPrmpt',Prompt) nLabels = size(Labels,1); for i = 1:nLabels, fprintf('\t%2d : %s\n',i,Labels(i,:)), end Prmpt = ['Menu choice (1-',int2str(nLabels),')']; if DefItem Prmpt=[Prmpt,' (Default: ',num2str(DefItem),')']; end %-Ask for user response %------------------------------------------------------- if nLabels==1 %-Only one choice - auto-pick & display k = 1; fprintf('Menu choice: 1 - %s\t(only option)',Labels) else k = input([Prmpt,' ? ']); if DefItem && isempty(k), k=DefItem; end while isempty(k) || ~any([1:nLabels]==k) if ~isempty(k),fprintf('%c\t!Out of range\n',7),end k = input([Prmpt,' ? ']); if DefItem && isempty(k), k=DefItem; end end end fprintf('\n') else Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets if nLabels==1 %-Only one choice - auto-pick k = 1; else Labs=[repmat(' ',nLabels,2),Labels]; if DefItem Labs(DefItem,1)='*'; H = uicontrol(Finter,'Style','Frame',... 'BackGroundColor','k',... 'ForeGroundColor','k',... 'Position',QRec+[-1,-1,+2,+2]); else H = []; end cb = ['if (get(gcbo,''Value'')>1),',... 'set(gcbo,''UserData'',''Selected''), end']; hPopUp = uicontrol(Finter,'Style','PopUp',... 'HorizontalAlignment','Left',... 'ForegroundColor','k',... 'BackgroundColor',COLOUR,... 'String',strvcat([Prompt,'...'],Labs),... 'Tag',Tag,... 'UserData',DefItem,... 'CallBack',cb,... 'Position',QRec); if TTips cLabs = cellstr(Labels); cInd = num2cell(1:nLabels); scLabs = [cInd; cLabs']; scLabs = sprintf('%d: %s\n',scLabs{:}); set(hPopUp,'ToolTipString',sprintf(['select with ',... 'mouse or type option number (1-',... num2str(nLabels),') & press return\n%s'],scLabs)); end %-Figure ContextMenu for shortcuts hM = spm_input('!InptConMen',Finter,[hPopUp,H]); %-Bring window to fore & jump pointer to menu widget [PLoc,cF] = spm_input('!PointerJump',RRec,Finter); %-Callback for KeyPresses cb=['spm_input(''!PullDownKeyPressFcn'',',... 'findobj(gcf,''Tag'',''',Tag,'''),',... 'get(gcf,''CurrentCharacter''))']; set(Finter,'KeyPressFcn',cb) %-Wait for menu selection %----------------------------------------------- waitfor(hPopUp,'UserData') if ~ishandle(hPopUp), error(['Input object cleared ',... 'whilst waiting for response: Bailing out!']),end k = get(hPopUp,'Value')-1; %-Clean up delete([H,hM]), set(Finter,'KeyPressFcn','') set(hPopUp,'Style','Text',... 'Horizontalalignment','Center',... 'String',deblank(Labels(k,:)),... 'BackgroundColor',COLOUR) spm_input('!PointerJumpBack',PLoc,cF) end %-Display answer uicontrol(Finter,'Style','Text',... 'String',deblank(Labels(k,:)),... 'Tag',Tag,... 'Horizontalalignment','Center',... 'BackgroundColor',COLOUR,... 'Position',QRec); drawnow end p = Values(k,:); if ischar(p), p=deblank(p); end otherwise, error('unrecognised type') end % (switch lower(Type) within case {'b','b|','y/n'}) %-Return response %----------------------------------------------------------------------- varargout = {p,YPos}; case {'m!','b!'} %-GUI PullDown/Buttons utility %======================================================================= % H = spm_input(Prompt,YPos,'p',Labels,cb,UD,XCB) %-Condition arguments if nargin<7, XCB = 0; else XCB = varargin{7}; end if nargin<6, UD = []; else UD = varargin{6}; end if nargin<5, cb = ''; else cb = varargin{5}; end if nargin<4, Labels = []; else Labels = varargin{4}; end if CmdLine, error('Can''t do CmdLine GUI utilities!'), end if isempty(cb), cb = 'disp(''(CallBack not set)'')'; end if ischar(cb), cb = cellstr(cb); end if length(cb)>1 && strcmpi(Type,'m!'), XCB=1; end if iscellstr(Labels), Labels=char(Labels); end %-Convert Labels "option" string to string matrix if required if any(Labels=='|') OptStr=Labels; BarPos=find([OptStr=='|',1]); Labels=OptStr(1:BarPos(1)-1); for Bar = 2:sum(OptStr=='|')+1 Labels=strvcat(Labels,OptStr(BarPos(Bar-1)+1:BarPos(Bar)-1)); end end %-Check #CallBacks if ~( length(cb)==1 || (length(cb)==size(Labels,1)) ) error('Labels & Callbacks size mismatch'), end %-Draw Prompt %----------------------------------------------------------------------- Tag = ['GUIinput_',int2str(YPos)]; %-Tag for widgets if ~isempty(Prompt) uicontrol(Finter,'Style','Text',... 'String',Prompt,... 'Tag',Tag,... 'HorizontalAlignment','Right',... 'BackgroundColor',COLOUR,... 'Position',PRec) Rec = RRec; else Rec = QRec; end %-Sort out UserData for extended callbacks (handled by spm_input('!m_cb') %----------------------------------------------------------------------- if XCB, if iscell(UD), UD={UD}; end, UD = struct('UD',UD,'cb',{cb}); end %-Draw PullDown or Buttons %----------------------------------------------------------------------- switch lower(Type), case 'm!' if XCB, UD.cb=cb; cb = {'spm_input(''!m_cb'')'}; end H = uicontrol(Finter,'Style','PopUp',... 'HorizontalAlignment','Left',... 'ForegroundColor','k',... 'BackgroundColor',COLOUR,... 'String',Labels,... 'Tag',Tag,... 'UserData',UD,... 'CallBack',char(cb),... 'Position',Rec); case 'b!' nLabels = size(Labels,1); dX = Rec(3)/nLabels; H = []; for i=1:nLabels if length(cb)>1, tcb=cb(i); else tcb=cb; end if XCB, UD.cb=tcb; tcb = {'spm_input(''!m_cb'')'}; end h = uicontrol(Finter,'Style','Pushbutton',... 'String',deblank(Labels(i,:)),... 'ToolTipString','',... 'Tag',Tag,... 'UserData',UD,... 'BackgroundColor',COLOUR,... 'Callback',char(tcb),... 'Position',[Rec(1)+(i-1)*dX+1 ... Rec(2) dX-2 Rec(4)]); H = [H,h]; end end %-Bring window to fore & jump pointer to menu widget [PLoc,cF] = spm_input('!PointerJump',RRec,Finter); varargout = {H}; case {'d','d!'} %-Display message %======================================================================= %-Condition arguments if nargin<4, Label=''; else Label=varargin{4}; end if CmdLine && strcmpi(Type,'d') fprintf('\n +-%s%s+',Label,repmat('-',1,57-length(Label))) Prompt = [Prompt,' ']; while ~isempty(Prompt) tmp = length(Prompt); if tmp>56, tmp=min([max(find(Prompt(1:56)==' ')),56]); end fprintf('\n | %s%s |',Prompt(1:tmp),repmat(' ',1,56-tmp)) Prompt(1:tmp)=[]; end fprintf('\n +-%s+\n',repmat('-',1,57)) elseif ~CmdLine if ~isempty(Label), Prompt = [Label,': ',Prompt]; end figure(Finter) %-Create text axes and edit control objects %--------------------------------------------------------------- h = uicontrol(Finter,'Style','Text',... 'String',Prompt(1:min(length(Prompt),56)),... 'FontWeight','bold',... 'Tag',['GUIinput_',int2str(YPos)],... 'HorizontalAlignment','Left',... 'ForegroundColor','k',... 'BackgroundColor',COLOUR,... 'UserData',Prompt,... 'Position',QRec); if length(Prompt)>56 pause(1) set(h,'ToolTipString',Prompt) spm_input('!dScroll',h) uicontrol(Finter,'Style','PushButton','String','>',... 'ToolTipString','press to scroll message',... 'Tag',['GUIinput_',int2str(YPos)],... 'UserData',h,... 'CallBack',[... 'set(gcbo,''Visible'',''off''),',... 'spm_input(''!dScroll'',get(gcbo,''UserData'')),',... 'set(gcbo,''Visible'',''on'')'],... 'BackgroundColor',COLOUR,... 'Position',[QRec(1)+QRec(3)-10,QRec(2),15,QRec(4)]); end end if nargout>0, varargout={[],YPos}; end %======================================================================= % U T I L I T Y F U N C T I O N S %======================================================================= case '!colour' %======================================================================= % colour = spm_input('!Colour') varargout = {COLOUR}; case '!icond' %======================================================================= % [iCond,msg] = spm_input('!iCond',str,n,m) % Parse condition indicator spec strings: % '2 3 2 3', '0 1 0 1', '2323', '0101', 'abab', 'R A R A' if nargin<4, m=Inf; else m=varargin{4}; end if nargin<3, n=NaN; else n=varargin{3}; end if any(isnan(n(:))) n=Inf; elseif (length(n(:))==2 && ~any(n==1)) || length(n(:))>2 error('condition input can only do vectors') end if nargin<2, i=''; else i=varargin{2}; end if isempty(i), varargout={[],'empty input'}; return, end msg = ''; i=i(:)'; if ischar(i) if i(1)=='0' && all(ismember(unique(i(:)),char(abs('0'):abs('9')))) %-Leading zeros in a digit list msg = sprintf('%s expanded',i); z = min(find([diff(i=='0'),1])); i = [zeros(1,z), spm_input('!iCond',i(z+1:end))']; else %-Try an eval, for functions & string #s i = evalin('base',['[',i,']'],'i'); end end if ischar(i) %-Evaluation error from above: see if it's an 'abab' or 'a b a b' type: [c,null,i] = unique(lower(i(~isspace(i)))); if all(ismember(c,char(abs('a'):abs('z')))) %-Map characters a-z to 1-26, but let 'r' be zero (rest) tmp = c-'a'+1; tmp(tmp=='r'-'a'+1)=0; i = tmp(i); msg = [sprintf('[%s] mapped to [',c),... sprintf('%d,',tmp(1:end-1)),... sprintf('%d',tmp(end)),']']; else i = '!'; msg = 'evaluation error'; end elseif ~all(floor(i(:))==i(:)) i = '!'; msg = 'must be integers'; elseif length(i)==1 && prod(n)>1 msg = sprintf('%d expanded',i); i = floor(i./10.^[floor(log10(i)+eps):-1:0]); i = i-[0,10*i(1:end-1)]; end %-Check size of i & #conditions if ~ischar(i), [i,msg] = sf_SzChk(i,n,msg); end if ~ischar(i) && isfinite(m) && length(unique(i))~=m i = '!'; msg = sprintf('%d conditions required',m); end varargout = {i,msg}; case '!inptconmen' %======================================================================= % hM = spm_input('!InptConMen',Finter,H) if nargin<3, H=[]; else H=varargin{3}; end if nargin<2, varargout={[]}; else Finter=varargin{2}; end hM = uicontextmenu('Parent',Finter); uimenu(hM,'Label','help on spm_input',... 'CallBack','spm_help(''spm_input.m'')') if ConCrash uimenu(hM,'Label','crash out','Separator','on',... 'CallBack','delete(get(gcbo,''UserData''))',... 'UserData',[hM,H]) end set(Finter,'UIContextMenu',hM) varargout={hM}; case '!cmdline' %======================================================================= % [CmdLine,YPos] = spm_input('!CmdLine',YPos) %-Sorts out whether to use CmdLine or not & canonicalises YPos if nargin<2, YPos=''; else YPos=varargin{2}; end if isempty(YPos), YPos='+1'; end CmdLine = []; %-Special YPos specifications if ischar(YPos) if(YPos(1)=='!'), CmdLine=0; YPos(1)=[]; end elseif YPos==0 CmdLine=1; elseif YPos<0 CmdLine=0; YPos=-YPos; end CmdLine = spm('CmdLine',CmdLine); if CmdLine, YPos=0; end varargout = {CmdLine,YPos}; case '!getwin' %======================================================================= % Finter = spm_input('!GetWin',F) %-Locate (or create) figure to work in (Don't use 'Tag'ged figs) if nargin<2, F='Interactive'; else F=varargin{2}; end Finter = spm_figure('FindWin',F); if isempty(Finter) if any(get(0,'Children')) if isempty(get(gcf,'Tag')), Finter = gcf; else Finter = spm('CreateIntWin'); end else Finter = spm('CreateIntWin'); end end varargout = {Finter}; case '!pointerjump' %======================================================================= % [PLoc,cF] = spm_input('!PointerJump',RRec,F,XDisp) %-Raise window & jump pointer over question if nargin<4, XDisp=[]; else XDisp=varargin{4}; end if nargin<3, F='Interactive'; else F=varargin{3}; end if nargin<2, error('Insufficient arguments'), else RRec=varargin{2}; end F = spm_figure('FindWin',F); PLoc = get(0,'PointerLocation'); cF = get(0,'CurrentFigure'); if ~isempty(F) figure(F) FRec = get(F,'Position'); if isempty(XDisp), XDisp=RRec(3)*4/5; end if PJump, set(0,'PointerLocation',... floor([(FRec(1)+RRec(1)+XDisp), (FRec(2)+RRec(2)+RRec(4)/3)])); end end varargout = {PLoc,cF}; case '!pointerjumpback' %======================================================================= % spm_input('!PointerJumpBack',PLoc,cF) %-Replace pointer and reset CurrentFigure back if nargin<4, cF=[]; else F=varargin{3}; end if nargin<2, error('Insufficient arguments'), else PLoc=varargin{2}; end if PJump, set(0,'PointerLocation',PLoc), end cF = spm_figure('FindWin',cF); if ~isempty(cF), set(0,'CurrentFigure',cF); end case '!prntprmpt' %======================================================================= % spm_input('!PrntPrmpt',Prompt,TipStr,Title) %-Print prompt for CmdLine questioning if nargin<4, Title = ''; else Title = varargin{4}; end if nargin<3, TipStr = ''; else TipStr = varargin{3}; end if nargin<2, Prompt = ''; else Prompt = varargin{2}; end if isempty(Prompt), Prompt='Enter an expression'; end Prompt = cellstr(Prompt); if ~isempty(TipStr) tmp = 8 + length(Prompt{end}) + length(TipStr); if tmp < 62 TipStr = sprintf('%s(%s)',repmat(' ',1,70-tmp),TipStr); else TipStr = sprintf('\n%s(%s)',repmat(' ',1,max(0,70-length(TipStr))),TipStr); end end if isempty(Title) fprintf('\n%s\n',repmat('~',1,72)) else fprintf('\n= %s %s\n',Title,repmat('~',1,72-length(Title)-3)) end fprintf('\t%s',Prompt{1}) for i=2:numel(Prompt), fprintf('\n\t%s',Prompt{i}), end fprintf('%s\n%s\n',TipStr,repmat('~',1,72)) case '!inputrects' %======================================================================= % [Frec,QRec,PRec,RRec,Sz,Se] = spm_input('!InputRects',YPos,rec,F) if nargin<4, F='Interactive'; else F=varargin{4}; end if nargin<3, rec=''; else rec=varargin{3}; end if nargin<2, YPos=1; else YPos=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F), error('Figure not found'), end Units = get(F,'Units'); set(F,'Units','pixels') FRec = get(F,'Position'); set(F,'Units',Units); Xdim = FRec(3); Ydim = FRec(4); WS = spm('WinScale'); Sz = round(22*min(WS)); %-Height Pd = Sz/2; %-Pad Se = 2*round(25*min(WS)/2); %-Seperation Yo = round(2*min(WS)); %-Y offset for responses a = 5.5/10; y = Ydim - Se*YPos; QRec = [Pd y Xdim-2*Pd Sz]; %-Question PRec = [Pd y floor(a*Xdim)-2*Pd Sz]; %-Prompt RRec = [ceil(a*Xdim) y+Yo floor((1-a)*Xdim)-Pd Sz]; %-Response % MRec = [010 y Xdim-50 Sz]; %-Menu PullDown % BRec = MRec + [Xdim-50+1, 0+1, 50-Xdim+30, 0]; %-Menu PullDown OK butt if ~isempty(rec) varargout = {eval(rec)}; else varargout = {FRec,QRec,PRec,RRec,Sz,Se}; end case '!deleteinputobj' %======================================================================= % spm_input('!DeleteInputObj',F) if nargin<2, F='Interactive'; else F=varargin{2}; end h = spm_input('!FindInputObj',F); delete(h(h>0)) case {'!currentpos','!findinputobj'} %======================================================================= % [CPos,hCPos] = spm_input('!CurrentPos',F) % h = spm_input('!FindInputObj',F) % hPos contains handles: Columns contain handles corresponding to Pos if nargin<2, F='Interactive'; else F=varargin{2}; end F = spm_figure('FindWin',F); %-Find tags and YPos positions of 'GUIinput_' 'Tag'ged objects H = []; YPos = []; for h = get(F,'Children')' tmp = get(h,'Tag'); if ~isempty(tmp) if strcmp(tmp(1:min(length(tmp),9)),'GUIinput_') H = [H, h]; YPos = [YPos, eval(tmp(10:end))]; end end end switch lower(Type), case '!findinputobj' varargout = {H}; case '!currentpos' if nargout<2 varargout = {max(YPos),[]}; elseif isempty(H) varargout = {[],[]}; else %-Sort out tmp = sort(YPos); CPos = tmp(find([1,diff(tmp)])); nPos = length(CPos); nPerPos = diff(find([1,diff(tmp),1])); hCPos = zeros(max(nPerPos),nPos); for i = 1:nPos hCPos(1:nPerPos(i),i) = H(YPos==CPos(i))'; end varargout = {CPos,hCPos}; end end case '!nextpos' %======================================================================= % [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine) %-Return next position to use if nargin<3, F='Interactive'; else F=varargin{3}; end if nargin<2, YPos='+1'; else YPos=varargin{2}; end if nargin<4, [CmdLine,YPos]=spm_input('!CmdLine',YPos); else CmdLine=varargin{4}; end F = spm_figure('FindWin',F); %-Get current positions if nargout<3 CPos = spm_input('!CurrentPos',F); hCPos = []; else [CPos,hCPos] = spm_input('!CurrentPos',F); end if CmdLine NPos = 0; else MPos = spm_input('!MaxPos',F); if ischar(YPos) %-Relative YPos %-Strip any '!' prefix from YPos if(YPos(1)=='!'), YPos(1)=[]; end if strncmp(YPos,'_',1) %-YPos='_' means bottom YPos=eval(['MPos+',YPos(2:end)],'MPos'); else YPos = max([0,CPos])+eval(YPos); end else %-Absolute YPos YPos=abs(YPos); end NPos = min(max(1,YPos),MPos); end varargout = {NPos,CPos,hCPos}; case '!setnextpos' %======================================================================= % NPos = spm_input('!SetNextPos',YPos,F,CmdLine) %-Set next position to use if nargin<3, F='Interactive'; else F=varargin{3}; end if nargin<2, YPos='+1'; else YPos=varargin{2}; end if nargin<4, [CmdLine,YPos]=spm_input('!CmdLine',YPos); else CmdLine=varargin{4}; end %-Find out which Y-position to use [NPos,CPos,hCPos] = spm_input('!NextPos',YPos,F,CmdLine); %-Delete any previous inputs using positions NPos and after if any(CPos>=NPos), h=hCPos(:,CPos>=NPos); delete(h(h>0)), end varargout = {NPos}; case '!maxpos' %======================================================================= % MPos = spm_input('!MaxPos',F,FRec3) % if nargin<3 if nargin<2, F='Interactive'; else F=varargin{2}; end F = spm_figure('FindWin',F); if isempty(F) FRec3=spm('WinSize','Interactive')*[0;0;0;1]; else %-Get figure size Units = get(F,'Units'); set(F,'Units','pixels') FRec3 = get(F,'Position')*[0;0;0;1]; set(F,'Units',Units); end end Se = round(25*min(spm('WinScale'))); MPos = floor((FRec3-5)/Se); varargout = {MPos}; case '!editablekeypressfcn' %======================================================================= % spm_input('!EditableKeyPressFcn',h,ch,hPrmpt) if nargin<2, error('Insufficient arguments'), else h=varargin{2}; end if isempty(h), set(gcbf,'KeyPressFcn','','UserData',[]), return, end if nargin<3, ch=get(get(h,'Parent'),'CurrentCharacter'); else ch=varargin{3};end if nargin<4, hPrmpt=get(h,'UserData'); else hPrmpt=varargin{4}; end tmp = get(h,'String'); if isempty(tmp), tmp=''; end if iscellstr(tmp) && length(tmp)==1; tmp=tmp{:}; end if isempty(ch) %- shift / control / &c. pressed return elseif any(abs(ch)==[32:126]) %-Character if iscellstr(tmp), return, end tmp = [tmp, ch]; elseif abs(ch)==21 %- ^U - kill tmp = ''; elseif any(abs(ch)==[8,127]) %-BackSpace or Delete if iscellstr(tmp), return, end if ~isempty(tmp), tmp(length(tmp))=''; end elseif abs(ch)==13 %-Return pressed if ~isempty(tmp) set(hPrmpt,'UserData',get(h,'String')) end return else %-Illegal character return end set(h,'String',tmp) case '!buttonkeypressfcn' %======================================================================= % spm_input('!ButtonKeyPressFcn',h,Keys,DefItem,ch) %-Callback for KeyPress, to store valid button # in UserData of Prompt, % DefItem if (DefItem~=0) & return (ASCII-13) is pressed %-Condition arguments if nargin<2, error('Insufficient arguments'), else h=varargin{2}; end if isempty(h), set(gcf,'KeyPressFcn','','UserData',[]), return, end if nargin<3, error('Insufficient arguments'); else Keys=varargin{3}; end if nargin<4, DefItem=0; else DefItem=varargin{4}; end if nargin<5, ch=get(gcf,'CurrentCharacter'); else ch=varargin{5}; end if isempty(ch) %- shift / control / &c. pressed return elseif (DefItem && ch==13) But = DefItem; else But = find(lower(ch)==lower(Keys)); end if ~isempty(But), set(h,'UserData',But), end case '!pulldownkeypressfcn' %======================================================================= % spm_input('!PullDownKeyPressFcn',h,ch,DefItem) if nargin<2, error('Insufficient arguments'), else h=varargin{2}; end if isempty(h), set(gcf,'KeyPressFcn',''), return, end if nargin<3, ch=get(get(h,'Parent'),'CurrentCharacter'); else ch=varargin{3};end if nargin<4, DefItem=get(h,'UserData'); else ch=varargin{4}; end Pmax = get(h,'Max'); Pval = get(h,'Value'); if Pmax==1, return, end if isempty(ch) %- shift / control / &c. pressed return elseif abs(ch)==13 if Pval==1 if DefItem, set(h,'Value',max(2,min(DefItem+1,Pmax))), end else set(h,'UserData','Selected') end elseif any(ch=='bpu') %-Move "b"ack "u"p to "p"revious entry set(h,'Value',max(2,Pval-1)) elseif any(ch=='fnd') %-Move "f"orward "d"own to "n"ext entry set(h,'Value',min(Pval+1,Pmax)) elseif any(ch=='123456789') %-Move to entry n set(h,'Value',max(2,min(eval(ch)+1,Pmax))) else %-Illegal character end case '!m_cb' %-CallBack handler for extended CallBack 'p'ullDown type %======================================================================= % spm_input('!m_cb') %-Get PopUp handle and value h = gcbo; n = get(h,'Value'); %-Get PopUp's UserData, check cb and UD fields exist, extract cb & UD tmp = get(h,'UserData'); if ~(isfield(tmp,'cb') && isfield(tmp,'UD')) error('Invalid UserData structure for spm_input extended callback') end cb = tmp.cb; UD = tmp.UD; %-Evaluate appropriate CallBack string (ignoring any return arguments) % NB: Using varargout={eval(cb{n})}; gives an error if the CallBack % has no return arguments! if length(cb)==1, eval(char(cb)); else eval(cb{n}); end case '!dscroll' %======================================================================= % spm_input('!dScroll',h,Prompt) %-Scroll text in object h if nargin<2, return, else h=varargin{2}; end if nargin<3, Prompt = get(h,'UserData'); else Prompt=varargin{3}; end tmp = Prompt; if length(Prompt)>56 while length(tmp)>56 tic, while(toc<0.1), pause(0.05), end tmp(1)=[]; set(h,'String',tmp(1:min(length(tmp),56))) end pause(1) set(h,'String',Prompt(1:min(length(Prompt),56))) end otherwise %======================================================================= error(['Invalid type/action: ',Type]) %======================================================================= end % (case lower(Type)) %======================================================================= %- S U B - F U N C T I O N S %======================================================================= function [Keys,Labs] = sf_labkeys(Labels) %======================================================================= %-Make unique character keys for the Labels, ignoring case if nargin<1, error('insufficient arguments'), end if iscellstr(Labels), Labels = char(Labels); end if isempty(Labels), Keys=''; Labs=''; return, end Keys=Labels(:,1)'; nLabels = size(Labels,1); if any(~diff(abs(sort(lower(Keys))))) if nLabels<10 Keys = sprintf('%d',[1:nLabels]); elseif nLabels<=26 Keys = sprintf('%c',abs('a')+[0:nLabels-1]); else error('Too many buttons!') end Labs = Labels; else Labs = Labels(:,2:end); end function [p,msg] = sf_eEval(str,Type,n,m) %======================================================================= %-Evaluation and error trapping of typed input if nargin<4, m=[]; end if nargin<3, n=[]; end if nargin<2, Type='e'; end if nargin<1, str=''; end if isempty(str), p='!'; msg='empty input'; return, end switch lower(Type) case 's' p = str; msg = ''; case 'e' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; else [p,msg] = sf_SzChk(p,n); end case 'n' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif any(floor(p(:))~=p(:)|p(:)<1)||~isreal(p) p='!'; msg='natural number(s) required'; elseif ~isempty(m) && any(p(:)>m) p='!'; msg=['max value is ',num2str(m)]; else [p,msg] = sf_SzChk(p,n); end case 'w' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif any(floor(p(:))~=p(:)|p(:)<0)||~isreal(p) p='!'; msg='whole number(s) required'; elseif ~isempty(m) && any(p(:)>m) p='!'; msg=['max value is ',num2str(m)]; else [p,msg] = sf_SzChk(p,n); end case 'i' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif any(floor(p(:))~=p(:))||~isreal(p) p='!'; msg='integer(s) required'; else [p,msg] = sf_SzChk(p,n); end case 'p' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif ~isempty(setxor(p(:)',m)) p='!'; msg='invalid permutation'; else [p,msg] = sf_SzChk(p,n); end case 'r' p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; elseif ~isreal(p) p='!'; msg='real number(s) required'; elseif ~isempty(m) && ( max(p)>max(m) || min(p)<min(m) ) p='!'; msg=sprintf('real(s) in [%g,%g] required',min(m),max(m)); else [p,msg] = sf_SzChk(p,n); end case 'c' if isempty(m), m=Inf; end [p,msg] = spm_input('!iCond',str,n,m); case 'x' X = m; %-Design matrix/space-structure if isempty(n), n=1; end %-Sort out contrast matrix dimensions (contrast vectors in rows) if length(n)==1, n=[n,Inf]; else n=reshape(n(1:2),1,2); end if ~isempty(X) % - override n(2) w/ design column dimension n(2) = spm_SpUtil('size',X,2); end p = evalin('base',['[',str,']'],'''!'''); if ischar(p) msg = 'evaluation error'; else if isfinite(n(2)) && size(p,2)<n(2) tmp = n(2) -size(p,2); p = [p, zeros(size(p,1),tmp)]; if size(p,1)>1, str=' columns'; else str='s'; end msg = sprintf('right padded with %d zero%s',tmp,str); else msg = ''; end if size(p,2)>n(2) p='!'; msg=sprintf('too long - only %d prams',n(2)); elseif isfinite(n(1)) && size(p,1)~=n(1) p='!'; if n(1)==1, msg='vector required'; else msg=sprintf('%d contrasts required',n(1)); end elseif ~isempty(X) && ~spm_SpUtil('allCon',X,p') p='!'; msg='invalid contrast'; end end otherwise error('unrecognised type'); end function str = sf_SzStr(n,l) %======================================================================= %-Size info string construction if nargin<2, l=0; else l=1; end if nargin<1, error('insufficient arguments'), end if isempty(n), n=NaN; end n=n(:); if length(n)==1, n=[n,1]; end, dn=length(n); if any(isnan(n)) || (prod(n)==1 && dn<=2) || (dn==2 && min(n)==1 && isinf(max(n))) str = ''; lstr = ''; elseif dn==2 && min(n)==1 str = sprintf('[%d]',max(n)); lstr = [str,'-vector']; elseif dn==2 && sum(isinf(n))==1 str = sprintf('[%d]',min(n)); lstr = [str,'-vector(s)']; else str=''; for i = 1:dn if isfinite(n(i)), str = sprintf('%s,%d',str,n(i)); else str = sprintf('%s,*',str); end end str = ['[',str(2:end),']']; lstr = [str,'-matrix']; end if l, str=sprintf('\t%s',lstr); else str=[str,' ']; end function [p,msg] = sf_SzChk(p,n,msg) %======================================================================= %-Size checking if nargin<3, msg=''; end if nargin<2, n=[]; end, if isempty(n), n=NaN; else n=n(:)'; end if nargin<1, error('insufficient arguments'), end if ischar(p) || any(isnan(n(:))), return, end if length(n)==1, n=[n,1]; end dn = length(n); sp = size(p); dp = ndims(p); if dn==2 && min(n)==1 %-[1,1], [1,n], [n,1], [1,Inf], [Inf,1] - vector - allow transpose %--------------------------------------------------------------- i = min(find(n==max(n))); if n(i)==1 && max(sp)>1 p='!'; msg='scalar required'; elseif ndims(p)~=2 || ~any(sp==1) || ( isfinite(n(i)) && max(sp)~=n(i) ) %-error: Not2D | not vector | not right length if isfinite(n(i)), str=sprintf('%d-',n(i)); else str=''; end p='!'; msg=[str,'vector required']; elseif sp(i)==1 && n(i)~=1 p=p'; msg=[msg,' (input transposed)']; end elseif dn==2 && sum(isinf(n))==1 %-[n,Inf], [Inf,n] - n vector(s) required - allow transposing %--------------------------------------------------------------- i = find(isfinite(n)); if ndims(p)~=2 || ~any(sp==n(i)) p='!'; msg=sprintf('%d-vector(s) required',min(n)); elseif sp(i)~=n p=p'; msg=[msg,' (input transposed)']; end else %-multi-dimensional matrix required - check dimensions %--------------------------------------------------------------- if ndims(p)~=dn || ~all( size(p)==n | isinf(n) ) p = '!'; msg=''; for i = 1:dn if isfinite(n(i)), msg = sprintf('%s,%d',msg,n(i)); else msg = sprintf('%s,*',msg); end end msg = ['[',msg(2:end),']-matrix required']; end end %========================================================================== function uifocus(h) try if strcmpi(get(h, 'Style'), 'PushButton') == 1 uicontrol(gcbo); else uicontrol(h); end end
github
philippboehmsturm/antx-master
spm_realign.m
.m
antx-master/freiburgLight/matlab/spm8/spm_realign.m
18,205
utf_8
71e4880ae3886c6cff4d532cbaa0810a
function P = spm_realign(P,flags) % Estimation of within modality rigid body movement parameters % FORMAT P = spm_realign(P,flags) % % P - matrix of filenames {one string per row} % All operations are performed relative to the first image. % ie. Coregistration is to the first image, and resampling % of images is into the space of the first image. % For multiple sessions, P should be a cell array, where each % cell should be a matrix of filenames. % % flags - a structure containing various options. The fields are: % quality - Quality versus speed trade-off. Highest quality % (1) gives most precise results, whereas lower % qualities gives faster realignment. % The idea is that some voxels contribute little to % the estimation of the realignment parameters. % This parameter is involved in selecting the number % of voxels that are used. % % fwhm - The FWHM of the Gaussian smoothing kernel (mm) % applied to the images before estimating the % realignment parameters. % % sep - the default separation (mm) to sample the images. % % rtm - Register to mean. If field exists then a two pass % procedure is to be used in order to register the % images to the mean of the images after the first % realignment. % % PW - a filename of a weighting image (reciprocal of % standard deviation). If field does not exist, then % no weighting is done. % % interp - B-spline degree used for interpolation % %__________________________________________________________________________ % % Inputs % A series of *.img conforming to SPM data format (see 'Data Format'). % % Outputs % If no output argument, then an updated voxel to world matrix is written % to the headers of the images (a .mat file is created for 4D images). % The details of the transformation are displayed in the % results window as plots of translation and rotation. % A set of realignment parameters are saved for each session, named: % rp_*.txt. %__________________________________________________________________________ % % The voxel to world mappings. % % These are simply 4x4 affine transformation matrices represented in the % NIFTI headers (see http://nifti.nimh.nih.gov/nifti-1 ). % These are normally modified by the `realignment' and `coregistration' % modules. What these matrixes represent is a mapping from % the voxel coordinates (x0,y0,z0) (where the first voxel is at coordinate % (1,1,1)), to coordinates in millimeters (x1,y1,z1). % % x1 = M(1,1)*x0 + M(1,2)*y0 + M(1,3)*z0 + M(1,4) % y1 = M(2,1)*x0 + M(2,2)*y0 + M(2,3)*z0 + M(2,4) % z1 = M(3,1)*x0 + M(3,2)*y0 + M(3,3)*z0 + M(3,4) % % Assuming that image1 has a transformation matrix M1, and image2 has a % transformation matrix M2, the mapping from image1 to image2 is: M2\M1 % (ie. from the coordinate system of image1 into millimeters, followed % by a mapping from millimeters into the space of image2). % % These matrices allow several realignment or coregistration steps to be % combined into a single operation (without the necessity of resampling the % images several times). The `.mat' files are also used by the spatial % normalisation module. %__________________________________________________________________________ % Ref: % Friston KJ, Ashburner J, Frith CD, Poline J-B, Heather JD & Frackowiak % RSJ (1995) Spatial registration and normalization of images Hum. Brain % Map. 2:165-189 %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id: spm_realign.m 4152 2011-01-11 14:13:35Z volkmar $ if nargin==0, return; end; def_flags = spm_get_defaults('realign.estimate'); def_flags.PW = ''; def_flags.graphics = 1; def_flags.lkp = 1:6; if nargin < 2, flags = def_flags; else fnms = fieldnames(def_flags); for i=1:length(fnms), if ~isfield(flags,fnms{i}), flags.(fnms{i}) = def_flags.(fnms{i}); end; end; end; if ~iscell(P), tmp = cell(1); tmp{1} = P; P = tmp; end; for i=1:length(P), if ischar(P{i}), P{i} = spm_vol(P{i}); end; end; if ~isempty(flags.PW) && ischar(flags.PW), flags.PW = spm_vol(flags.PW); end; % Remove empty cells PN = {}; j = 1; for i=1:length(P), if ~isempty(P{i}), PN{j} = P{i}; j = j+1; end; end; P = PN; if isempty(P), warning('Nothing to do'); return; end; if length(P)==1, P{1} = realign_series(P{1},flags); if nargout==0, save_parameters(P{1}); end; else Ptmp = P{1}(1); for s=2:numel(P), Ptmp = [Ptmp ; P{s}(1)]; end; Ptmp = realign_series(Ptmp,flags); for s=1:numel(P), M = Ptmp(s).mat*inv(P{s}(1).mat); for i=1:numel(P{s}), P{s}(i).mat = M*P{s}(i).mat; end; end; for s=1:numel(P), P{s} = realign_series(P{s},flags); if nargout==0, save_parameters(P{s}); end; end; end; if nargout==0, % Save Realignment Parameters %--------------------------------------------------------------------------- for s=1:numel(P), for i=1:numel(P{s}), spm_get_space([P{s}(i).fname ',' num2str(P{s}(i).n)], P{s}(i).mat); end; end; end; if flags.graphics, plot_parameters(P); end; if length(P)==1, P=P{1}; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function P = realign_series(P,flags) % Realign a time series of 3D images to the first of the series. % FORMAT P = realign_series(P,flags) % P - a vector of volumes (see spm_vol) %----------------------------------------------------------------------- % P(i).mat is modified to reflect the modified position of the image i. % The scaling (and offset) parameters are also set to contain the % optimum scaling required to match the images. %_______________________________________________________________________ if numel(P)<2, return; end; skip = sqrt(sum(P(1).mat(1:3,1:3).^2)).^(-1)*flags.sep; d = P(1).dim(1:3); lkp = flags.lkp; rand('state',0); % want the results to be consistant. if d(3) < 3, lkp = [1 2 6]; [x1,x2,x3] = ndgrid(1:skip(1):d(1)-.5, 1:skip(2):d(2)-.5, 1:skip(3):d(3)); x1 = x1 + rand(size(x1))*0.5; x2 = x2 + rand(size(x2))*0.5; else [x1,x2,x3]=ndgrid(1:skip(1):d(1)-.5, 1:skip(2):d(2)-.5, 1:skip(3):d(3)-.5); x1 = x1 + rand(size(x1))*0.5; x2 = x2 + rand(size(x2))*0.5; x3 = x3 + rand(size(x3))*0.5; end; x1 = x1(:); x2 = x2(:); x3 = x3(:); % Possibly mask an area of the sample volume. %----------------------------------------------------------------------- if ~isempty(flags.PW), [y1,y2,y3]=coords([0 0 0 0 0 0],P(1).mat,flags.PW.mat,x1,x2,x3); wt = spm_sample_vol(flags.PW,y1,y2,y3,1); msk = find(wt>0.01); x1 = x1(msk); x2 = x2(msk); x3 = x3(msk); wt = wt(msk); else wt = []; end; % Compute rate of change of chi2 w.r.t changes in parameters (matrix A) %----------------------------------------------------------------------- V = smooth_vol(P(1),flags.interp,flags.wrap,flags.fwhm); deg = [flags.interp*[1 1 1]' flags.wrap(:)]; [G,dG1,dG2,dG3] = spm_bsplins(V,x1,x2,x3,deg); clear V A0 = make_A(P(1).mat,x1,x2,x3,dG1,dG2,dG3,wt,lkp); b = G; if ~isempty(wt), b = b.*wt; end; %----------------------------------------------------------------------- if numel(P) > 2, % Remove voxels that contribute very little to the final estimate. % Simulated annealing or something similar could be used to % eliminate a better choice of voxels - but this way will do for % now. It basically involves removing the voxels that contribute % least to the determinant of the inverse covariance matrix. spm_plot_convergence('Init','Eliminating Unimportant Voxels',... 'Relative quality','Iteration'); Alpha = [A0 b]; Alpha = Alpha'*Alpha; det0 = det(Alpha); det1 = det0; spm_plot_convergence('Set',det1/det0); while det1/det0 > flags.quality, dets = zeros(size(A0,1),1); for i=1:size(A0,1), tmp = [A0(i,:) b(i)]; dets(i) = det(Alpha - tmp'*tmp); end; clear tmp [junk,msk] = sort(det1-dets); msk = msk(1:round(length(dets)/10)); A0(msk,:) = []; b(msk,:) = []; G(msk,:) = []; x1(msk,:) = []; x2(msk,:) = []; x3(msk,:) = []; dG1(msk,:) = []; dG2(msk,:) = []; dG3(msk,:) = []; if ~isempty(wt), wt(msk,:) = []; end; Alpha = [A0 b]; Alpha = Alpha'*Alpha; det1 = det(Alpha); spm_plot_convergence('Set',single(det1/det0)); end; spm_plot_convergence('Clear'); end; %----------------------------------------------------------------------- if flags.rtm, count = ones(size(b)); ave = G; grad1 = dG1; grad2 = dG2; grad3 = dG3; end; spm_progress_bar('Init',length(P)-1,'Registering Images'); % Loop over images %----------------------------------------------------------------------- for i=2:length(P), V = smooth_vol(P(i),flags.interp,flags.wrap,flags.fwhm); d = [size(V) 1 1]; d = d(1:3); ss = Inf; countdown = -1; for iter=1:64, [y1,y2,y3] = coords([0 0 0 0 0 0],P(1).mat,P(i).mat,x1,x2,x3); msk = find((y1>=1 & y1<=d(1) & y2>=1 & y2<=d(2) & y3>=1 & y3<=d(3))); if length(msk)<32, error_message(P(i)); end; F = spm_bsplins(V, y1(msk),y2(msk),y3(msk),deg); if ~isempty(wt), F = F.*wt(msk); end; A = A0(msk,:); b1 = b(msk); sc = sum(b1)/sum(F); b1 = b1-F*sc; soln = (A'*A)\(A'*b1); p = [0 0 0 0 0 0 1 1 1 0 0 0]; p(lkp) = p(lkp) + soln'; P(i).mat = inv(spm_matrix(p))*P(i).mat; pss = ss; ss = sum(b1.^2)/length(b1); if (pss-ss)/pss < 1e-8 && countdown == -1, % Stopped converging. countdown = 2; end; if countdown ~= -1, if countdown==0, break; end; countdown = countdown -1; end; end; if flags.rtm, % Generate mean and derivatives of mean tiny = 5e-2; % From spm_vol_utils.c msk = find((y1>=(1-tiny) & y1<=(d(1)+tiny) &... y2>=(1-tiny) & y2<=(d(2)+tiny) &... y3>=(1-tiny) & y3<=(d(3)+tiny))); count(msk) = count(msk) + 1; [G,dG1,dG2,dG3] = spm_bsplins(V,y1(msk),y2(msk),y3(msk),deg); ave(msk) = ave(msk) + G*sc; grad1(msk) = grad1(msk) + dG1*sc; grad2(msk) = grad2(msk) + dG2*sc; grad3(msk) = grad3(msk) + dG3*sc; end; spm_progress_bar('Set',i-1); end; spm_progress_bar('Clear'); if ~flags.rtm, return; end; %_______________________________________________________________________ M=P(1).mat; A0 = make_A(M,x1,x2,x3,grad1./count,grad2./count,grad3./count,wt,lkp); if ~isempty(wt), b = (ave./count).*wt; else b = (ave./count); end clear ave grad1 grad2 grad3 % Loop over images %----------------------------------------------------------------------- spm_progress_bar('Init',length(P),'Registering Images to Mean'); for i=1:length(P), V = smooth_vol(P(i),flags.interp,flags.wrap,flags.fwhm); d = [size(V) 1 1 1]; ss = Inf; countdown = -1; for iter=1:64, [y1,y2,y3] = coords([0 0 0 0 0 0],M,P(i).mat,x1,x2,x3); msk = find((y1>=1 & y1<=d(1) & y2>=1 & y2<=d(2) & y3>=1 & y3<=d(3))); if length(msk)<32, error_message(P(i)); end; F = spm_bsplins(V, y1(msk),y2(msk),y3(msk),deg); if ~isempty(wt), F = F.*wt(msk); end; A = A0(msk,:); b1 = b(msk); sc = sum(b1)/sum(F); b1 = b1-F*sc; soln = (A'*A)\(A'*b1); p = [0 0 0 0 0 0 1 1 1 0 0 0]; p(lkp) = p(lkp) + soln'; P(i).mat = inv(spm_matrix(p))*P(i).mat; pss = ss; ss = sum(b1.^2)/length(b1); if (pss-ss)/pss < 1e-8 && countdown == -1 % Stopped converging. % Do three final iterations to finish off with countdown = 2; end; if countdown ~= -1 if countdown==0, break; end; countdown = countdown -1; end; end; spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); % Since we are supposed to be aligning everything to the first % image, then we had better do so %----------------------------------------------------------------------- M = M/P(1).mat; for i=1:length(P) P(i).mat = M*P(i).mat; end return; %_______________________________________________________________________ %_______________________________________________________________________ function [y1,y2,y3]=coords(p,M1,M2,x1,x2,x3) % Rigid body transformation of a set of coordinates. M = (inv(M2)*inv(spm_matrix(p))*M1); y1 = M(1,1)*x1 + M(1,2)*x2 + M(1,3)*x3 + M(1,4); y2 = M(2,1)*x1 + M(2,2)*x2 + M(2,3)*x3 + M(2,4); y3 = M(3,1)*x1 + M(3,2)*x2 + M(3,3)*x3 + M(3,4); return; %_______________________________________________________________________ %_______________________________________________________________________ function V = smooth_vol(P,hld,wrp,fwhm) % Convolve the volume in memory. s = sqrt(sum(P.mat(1:3,1:3).^2)).^(-1)*(fwhm/sqrt(8*log(2))); x = round(6*s(1)); x = -x:x; y = round(6*s(2)); y = -y:y; z = round(6*s(3)); z = -z:z; x = exp(-(x).^2/(2*(s(1)).^2)); y = exp(-(y).^2/(2*(s(2)).^2)); z = exp(-(z).^2/(2*(s(3)).^2)); x = x/sum(x); y = y/sum(y); z = z/sum(z); i = (length(x) - 1)/2; j = (length(y) - 1)/2; k = (length(z) - 1)/2; d = [hld*[1 1 1]' wrp(:)]; V = spm_bsplinc(P,d); spm_conv_vol(V,V,x,y,z,-[i j k]); return; %_______________________________________________________________________ %_______________________________________________________________________ function A = make_A(M,x1,x2,x3,dG1,dG2,dG3,wt,lkp) % Matrix of rate of change of weighted difference w.r.t. parameter changes p0 = [0 0 0 0 0 0 1 1 1 0 0 0]; A = zeros(numel(x1),length(lkp)); for i=1:length(lkp) pt = p0; pt(lkp(i)) = pt(i)+1e-6; [y1,y2,y3] = coords(pt,M,M,x1,x2,x3); tmp = sum([y1-x1 y2-x2 y3-x3].*[dG1 dG2 dG3],2)/(-1e-6); if ~isempty(wt), A(:,i) = tmp.*wt; else A(:,i) = tmp; end end return; %_______________________________________________________________________ %_______________________________________________________________________ function error_message(P) str = { 'There is not enough overlap in the images',... 'to obtain a solution.',... ' ',... 'Offending image:',... P.fname,... ' ',... 'Please check that your header information is OK.',... 'The Check Reg utility will show you the initial',... 'alignment between the images, which must be',... 'within about 4cm and about 15 degrees in order',... 'for SPM to find the optimal solution.'}; spm('alert*',str,mfilename,sqrt(-1)); error('insufficient image overlap') %_______________________________________________________________________ %_______________________________________________________________________ function plot_parameters(P) fg=spm_figure('FindWin','Graphics'); if ~isempty(fg), P = cat(1,P{:}); if length(P)<2, return; end; Params = zeros(numel(P),12); for i=1:numel(P), Params(i,:) = spm_imatrix(P(i).mat/P(1).mat); end % display results % translation and rotation over time series %------------------------------------------------------------------- spm_figure('Clear','Graphics'); ax=axes('Position',[0.1 0.65 0.8 0.2],'Parent',fg,'Visible','off'); set(get(ax,'Title'),'String','Image realignment','FontSize',16,'FontWeight','Bold','Visible','on'); x = 0.1; y = 0.9; for i = 1:min([numel(P) 12]) text(x,y,[sprintf('%-4.0f',i) P(i).fname],'FontSize',10,'Interpreter','none','Parent',ax); y = y - 0.08; end if numel(P) > 12 text(x,y,'................ etc','FontSize',10,'Parent',ax); end ax=axes('Position',[0.1 0.35 0.8 0.2],'Parent',fg,'XGrid','on','YGrid','on'); plot(Params(:,1:3),'Parent',ax) s = ['x translation';'y translation';'z translation']; %text([2 2 2], Params(2, 1:3), s, 'Fontsize',10,'Parent',ax) legend(ax, s, 0) set(get(ax,'Title'),'String','translation','FontSize',16,'FontWeight','Bold'); set(get(ax,'Xlabel'),'String','image'); set(get(ax,'Ylabel'),'String','mm'); ax=axes('Position',[0.1 0.05 0.8 0.2],'Parent',fg,'XGrid','on','YGrid','on'); plot(Params(:,4:6)*180/pi,'Parent',ax) s = ['pitch';'roll ';'yaw ']; %text([2 2 2], Params(2, 4:6)*180/pi, s, 'Fontsize',10,'Parent',ax) legend(ax, s, 0) set(get(ax,'Title'),'String','rotation','FontSize',16,'FontWeight','Bold'); set(get(ax,'Xlabel'),'String','image'); set(get(ax,'Ylabel'),'String','degrees'); % print realigment parameters spm_print end return; %_______________________________________________________________________ %_______________________________________________________________________ function save_parameters(V) fname = [spm_str_manip(prepend(V(1).fname,'rp_'),'s') '.txt']; n = length(V); Q = zeros(n,6); for j=1:n, qq = spm_imatrix(V(j).mat/V(1).mat); Q(j,:) = qq(1:6); end; save(fname,'Q','-ascii'); return; %_______________________________________________________________________ %_______________________________________________________________________ function PO = prepend(PI,pre) [pth,nm,xt,vr] = spm_fileparts(deblank(PI)); PO = fullfile(pth,[pre nm xt vr]); return; %_______________________________________________________________________
github
philippboehmsturm/antx-master
spm_surf.m
.m
antx-master/freiburgLight/matlab/spm8/spm_surf.m
9,740
utf_8
aa92ddde8b875463a0fefee45e0a1d79
function varargout = spm_surf(P,mode,thresh) % Surface extraction % FORMAT spm_surf(P,mode,thresh) % % P - char array of filenames % Usually, this will be c1xxx.img & c2xxx.img - grey and white % matter segments created using the segmentation routine. % mode - operation mode [1: rendering, 2: surface, 3: both] % thresh - vector or threshold values for extraction [default: 0.5] % This is only relevant for extracting surfaces, not rendering. % % Generated files (depending on 'mode'): % A "render_xxx.mat" file can be produced that can be used for % rendering activations on to, see spm_render. % % A "xxx.surf.gii" file can also be written, which is created using % Matlab's isosurface function. % This extracted brain surface can be viewed using code something like: % FV = gifti(spm_select(1,'mesh','Select surface data')); % FV = export(FV,'patch'); % fg = spm_figure('GetWin','Graphics'); % ax = axes('Parent',fg); % p = patch(FV, 'Parent',ax,... % 'FaceColor', [0.8 0.7 0.7], 'FaceVertexCData', [],... % 'EdgeColor', 'none',... % 'FaceLighting', 'phong',... % 'SpecularStrength' ,0.7, 'AmbientStrength', 0.1,... % 'DiffuseStrength', 0.7, 'SpecularExponent', 10); % set(0,'CurrentFigure',fg); % set(fg,'CurrentAxes',ax); % l = camlight(-40, 20); % axis image; % rotate3d on; % % FORMAT out = spm_surf(job) % % Input % A job structure with fields % .data - cell array of filenames % .mode - operation mode % .thresh - thresholds for extraction % Output % A struct with fields (depending on operation mode) % .rendfile - cellstring containing render filename % .surffile - cellstring containing surface filename(s) %__________________________________________________________________________ % % This surface extraction is not particularly sophisticated. It simply % smooths the data slightly and extracts the surface at a threshold of % 0.5. The input segmentation images can be manually cleaned up first using % e.g., MRIcron. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id: spm_surf.m 4341 2011-06-03 11:24:02Z john $ SVNrev = '$Rev: 4341 $'; spm('FnBanner',mfilename,SVNrev); spm('FigName','Surface'); %-Get input: filenames 'P' %-------------------------------------------------------------------------- try if isstruct(P) job = P; P = strvcat(job.data); mode = job.mode; thresh = job.thresh; end catch [P, sts] = spm_select([1 Inf],'image','Select images'); if ~sts, varargout = {}; return; end end %-Get input: operation mode 'mode' %-------------------------------------------------------------------------- try mode; catch mode = spm_input('Save','+1','m',... ['Save Rendering|'... 'Save Extracted Surface|'... 'Save Rendering and Surface'],[1 2 3],3); end %-Get input: threshold for extraction 'thresh' %-------------------------------------------------------------------------- try thresh; catch thresh = 0.5; end %-Surface extraction %-------------------------------------------------------------------------- spm('FigName','Surface: working'); spm('Pointer','Watch'); out = do_it(P,mode,thresh); spm('Pointer','Arrow'); spm('FigName','Surface: done'); if nargout > 0 varargout{1} = out; end return; %========================================================================== function out = do_it(P,mode,thresh) V = spm_vol(P); br = zeros(V(1).dim(1:3)); for i=1:V(1).dim(3), B = spm_matrix([0 0 i]); tmp = spm_slice_vol(V(1),B,V(1).dim(1:2),1); for j=2:length(V), M = V(j).mat\V(1).mat*B; tmp = tmp + spm_slice_vol(V(j),M,V(1).dim(1:2),1); end br(:,:,i) = tmp; end % Build a 3x3x3 seperable smoothing kernel and smooth %-------------------------------------------------------------------------- kx=[0.75 1 0.75]; ky=[0.75 1 0.75]; kz=[0.75 1 0.75]; sm=sum(kron(kron(kz,ky),kx))^(1/3); kx=kx/sm; ky=ky/sm; kz=kz/sm; spm_conv_vol(br,br,kx,ky,kz,-[1 1 1]); [pth,nam,ext] = fileparts(V(1).fname); if any(mode==[1 3]) % Produce rendering %---------------------------------------------------------------------- out.rendfile{1} = fullfile(pth,['render_' nam '.mat']); tmp = struct('dat',br,'dim',size(br),'mat',V(1).mat); renviews(tmp,out.rendfile{1}); end if any(mode==[2 3]) % Produce extracted surface %---------------------------------------------------------------------- for k=1:numel(thresh) [faces,vertices] = isosurface(br,thresh(k)); % Swap around x and y because isosurface does for some % wierd and wonderful reason. Mat = V(1).mat(1:3,:)*[0 1 0 0;1 0 0 0;0 0 1 0; 0 0 0 1]; vertices = (Mat*[vertices' ; ones(1,size(vertices,1))])'; if numel(thresh)==1 nam1 = nam; else nam1 = sprintf('%s-%d',nam,k); end out.surffile{k} = fullfile(pth,[nam1 '.surf.gii']); save(gifti(struct('faces',faces,'vertices',vertices)),out.surffile{k}); end end return; %========================================================================== function renviews(V,oname) % Produce images for rendering activations to % % FORMAT renviews(V,oname) % V - mapped image to render, or alternatively % a structure of: % V.dat - 3D array % V.dim - size of 3D array % V.mat - affine mapping from voxels to millimeters % oname - the name of the render.mat file. %__________________________________________________________________________ % % Produces a matrix file "render_xxx.mat" which contains everything that % "spm_render" is likely to need. % % Ideally, the input image should contain values in the range of zero % and one, and be smoothed slightly. A threshold of 0.5 is used to % distinguish brain from non-brain. %__________________________________________________________________________ linfun = inline('fprintf([''%-30s%s''],x,[repmat(sprintf(''\b''),1,30)])','x'); linfun('Rendering: '); linfun('Rendering: Transverse 1..'); rend{1} = make_struct(V,[pi 0 pi/2]); linfun('Rendering: Transverse 2..'); rend{2} = make_struct(V,[0 0 pi/2]); linfun('Rendering: Sagittal 1..'); rend{3} = make_struct(V,[0 pi/2 pi]); linfun('Rendering: Sagittal 2..'); rend{4} = make_struct(V,[0 pi/2 0]); linfun('Rendering: Coronal 1..'); rend{5} = make_struct(V,[pi/2 pi/2 0]); linfun('Rendering: Coronal 2..'); rend{6} = make_struct(V,[pi/2 pi/2 pi]); linfun('Rendering: Save..'); if spm_check_version('matlab','7') >= 0 save(oname,'-V6','rend'); else save(oname,'rend'); end linfun(' '); if ~spm('CmdLine') disp_renderings(rend); spm_print; end return; %========================================================================== function str = make_struct(V,thetas) [D,M] = matdim(V.dim(1:3),V.mat,thetas); [ren,dep] = make_pic(V,M*V.mat,D); str = struct('M',M,'ren',ren,'dep',dep); return; %========================================================================== function [ren,zbuf] = make_pic(V,M,D) % A bit of a hack to try and make spm_render_vol produce some slightly % prettier output. It kind of works... if isfield(V,'dat'), vv = V.dat; else vv = V; end; [REN, zbuf, X, Y, Z] = spm_render_vol(vv, M, D, [0.5 1]); fw = max(sqrt(sum(M(1:3,1:3).^2))); msk = find(zbuf==1024); brn = ones(size(X)); brn(msk) = 0; brn = spm_conv(brn,fw); X(msk) = 0; Y(msk) = 0; Z(msk) = 0; msk = find(brn<0.5); tmp = brn; tmp(msk) = 100000; sX = spm_conv(X,fw)./tmp; sY = spm_conv(Y,fw)./tmp; sZ = spm_conv(Z,fw)./tmp; zbuf = spm_conv(zbuf,fw)./tmp; zbuf(msk) = 1024; vec = [-1 1 3]; % The direction of the lighting. vec = vec/norm(vec); [t,dx,dy,dz] = spm_sample_vol(vv,sX,sY,sZ,3); IM = inv(diag([0.5 0.5 1])*M(1:3,1:3))'; ren = IM(1:3,1:3)*[dx(:)' ; dy(:)' ; dz(:)']; len = sqrt(sum(ren.^2,1))+eps; ren = [ren(1,:)./len ; ren(2,:)./len ; ren(3,:)./len]; ren = reshape(vec*ren,[size(dx) 1]); ren(ren<0) = 0; ren(msk) = ren(msk)-0.2; ren = ren*0.8+0.2; mx = max(ren(:)); ren = ren/mx; return; %========================================================================== function disp_renderings(rend) Fgraph = spm_figure('GetWin','Graphics'); spm_results_ui('Clear',Fgraph); hght = 0.95; nrow = ceil(length(rend)/2); ax=axes('Parent',Fgraph,'units','normalized','Position',[0, 0, 1, hght],'Visible','off'); image(0,'Parent',ax); set(ax,'YTick',[],'XTick',[]); for i=1:length(rend), ren = rend{i}.ren; ax=axes('Parent',Fgraph,'units','normalized',... 'Position',[rem(i-1,2)*0.5, floor((i-1)/2)*hght/nrow, 0.5, hght/nrow],... 'Visible','off'); image(ren*64,'Parent',ax); set(ax,'DataAspectRatio',[1 1 1], ... 'PlotBoxAspectRatioMode','auto',... 'YTick',[],'XTick',[],'XDir','normal','YDir','normal'); end drawnow; return; %========================================================================== function [d,M] = matdim(dim,mat,thetas) R = spm_matrix([0 0 0 thetas]); bb = [[1 1 1];dim(1:3)]; c = [ bb(1,1) bb(1,2) bb(1,3) 1 bb(1,1) bb(1,2) bb(2,3) 1 bb(1,1) bb(2,2) bb(1,3) 1 bb(1,1) bb(2,2) bb(2,3) 1 bb(2,1) bb(1,2) bb(1,3) 1 bb(2,1) bb(1,2) bb(2,3) 1 bb(2,1) bb(2,2) bb(1,3) 1 bb(2,1) bb(2,2) bb(2,3) 1]'; tc = diag([2 2 1 1])*R*mat*c; tc = tc(1:3,:)'; mx = max(tc); mn = min(tc); M = spm_matrix(-mn(1:2))*diag([2 2 1 1])*R; d = ceil(abs(mx(1:2)-mn(1:2)))+1; return;
github
philippboehmsturm/antx-master
spm_eeg_plotScalpData.m
.m
antx-master/freiburgLight/matlab/spm8/spm_eeg_plotScalpData.m
11,761
utf_8
47767f883d6ed147946a3f14900db01d
function [ZI,f] = spm_eeg_plotScalpData(Z,pos,ChanLabel,in) % Display interpolated sensor data on the scalp in a new figure % FORMAT [ZI,f] = spm_eeg_plotScalpData(Z,pos,ChanLabel,in) % % INPUT: % Z - the data matrix at the sensors % pos - the positions of the sensors % ChanLabel - the names of the sensors % in - a structure containing some informations related to the % main PRESELECTDATA window. This entry is not necessary % OUTPUT % ZI - an image of interpolated data onto the scalp % f - the handle of the figure which displays the interpolated % data %__________________________________________________________________________ % % This function creates a figure whose purpose is to display an % interpolation of the sensor data on the scalp (an image) %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Jean Daunizeau % $Id: spm_eeg_plotScalpData.m 4375 2011-06-23 10:00:06Z vladimir $ ParentAxes = []; f = []; clim = [min(Z(:))-( max(Z(:))-min(Z(:)) )/63 , max(Z(:))]; figName = 'Image Scalp data'; noButtons = 0; if nargin < 4 || isempty(in) in = []; else if isfield(in,'min') && ... isfield(in,'max') && ... isfield(in,'type') clim = [in.min, in.max]; dc = abs(diff(clim))./63; clim(1) = clim(1) - dc; figName = ['Image Scalp data: ',in.type,' sensors']; if isfield(in,'trN') figName = [figName ', trial #',num2str(in.trN),'.']; end end if isfield(in,'ParentAxes') ParentAxes = in.ParentAxes; end if isfield(in,'f') f = in.f; end if isfield(in,'noButtons') noButtons = ~~in.noButtons; end end if ~isfield(in,'cbar') in.cbar = 1; end if ~isfield(in,'plotpos') in.plotpos = 1; end if size(pos,2) ~= length(ChanLabel) pos = pos'; end nD = size(pos,1); if nD ~= 2 % get 2D positions from 3D positions xyz = pos; [pos] = get2Dfrom3D(xyz); pos = pos'; end % exclude channels ? goodChannels = find(~isnan(pos(1,:))); pos = pos(:,goodChannels); Z = Z(goodChannels,:); ChanLabel = ChanLabel(goodChannels); if ~isempty(in) && isfield(in,'type') && strcmp(in.type, 'MEGPLANAR') [cZ, cpos, cChanLabel] = combineplanar(Z, pos, ChanLabel); else cZ = Z; cpos = pos; cChanLabel = ChanLabel; end xmin = min(cpos(1,:)); xmax = max(cpos(1,:)); dx = (xmax-xmin)./100; ymin = min(cpos(2,:)); ymax = max(cpos(2,:)); dy = (ymax-ymin)./100; x = xmin:dx:xmax; y = ymin:dy:ymax; [XI,YI] = meshgrid(x,y); ZI = griddata(cpos(1,:)',cpos(2,:)',full(double(cZ')),XI,YI); try figure(f) catch f=figure(... 'name',figName,... 'color',[1 1 1],... 'deleteFcn',@dFcn); ParentAxes = axes('parent',f); end COLOR = get(f,'color'); d.hi = image(flipud(ZI),... 'CDataMapping','scaled',... 'Parent',ParentAxes); set(ParentAxes,'nextPlot','add',... 'tag','spm_eeg_plotScalpData') try if length(unique(ZI)) ~= 1 [C,d.hc] = contour(ParentAxes,flipud(ZI),... 'linecolor',0.5.*ones(3,1)); end end caxis(ParentAxes,clim); col = jet; col(1,:) = COLOR; colormap(ParentAxes,col) if in.cbar d.cbar = colorbar('peer',ParentAxes); end axis(ParentAxes,'off') axis(ParentAxes,'equal') axis(ParentAxes,'tight') fpos = cpos; fpos(1,:) = fpos(1,:) - xmin; fpos(2,:) = fpos(2,:) - ymin; fpos(1,:) = fpos(1,:)./(dx); fpos(2,:) = fpos(2,:)./(dy); fpos(2,:) = 100-fpos(2,:); % for display purposes (flipud imagesc) figure(f); if in.plotpos d.hp = plot(ParentAxes,... fpos(1,:),fpos(2,:),... 'ko'); end d.ht = text(fpos(1,:),fpos(2,:),cChanLabel,... 'Parent',ParentAxes,... 'visible','off'); axis(ParentAxes,'image') d.interp.XI = XI; d.interp.YI = YI; d.interp.pos = cpos; d.f = f; d.pos = fpos; d.goodChannels = goodChannels; d.ChanLabel = cChanLabel; d.origChanLabel = ChanLabel; d.origpos = pos; d.ParentAxes = ParentAxes; d.in = in; if ~noButtons d.hsp = uicontrol(f,... 'style','pushbutton',... 'callback',{@dosp},... 'BusyAction','cancel',... 'Interruptible','off',... 'position',[10 50 80 20],... 'string','channel pos'); d.hsn = uicontrol(f,... 'style','pushbutton',... 'callback',{@dosn},... 'BusyAction','cancel',... 'Interruptible','off',... 'position',[10 80 80 20],... 'string','channel names'); end if ~isempty(in) && isfield(in,'handles') ud = get(in.handles.hfig,'userdata'); nT = ud.Nsamples; d.hti = uicontrol(f,... 'style','text',... 'BackgroundColor',COLOR,... 'string',[num2str(in.gridTime(in.x)),' (',in.unit,')'],... 'position',[10 10 120 20]); d.hts = uicontrol(f,... 'style','slider',... 'Position',[130 10 250 20],... 'min',1,'max',nT,... 'value',in.x,'sliderstep',[1./(nT-1) 1./(nT-1)],... 'callback',{@doChangeTime},... 'BusyAction','cancel',... 'Interruptible','off'); set(d.hti,'userdata',d); set(d.hts,'userdata',d); end if ~noButtons set(d.hsp,'userdata',d); set(d.hsn,'userdata',d); end set(d.ParentAxes,'userdata',d); %========================================================================== % dFcn %========================================================================== function dFcn(btn,evd) hf = findobj('tag','Graphics'); D = get(hf,'userdata'); try delete(D.PSD.handles.hli); end %========================================================================== % dosp %========================================================================== function dosp(btn,evd) d = get(btn,'userdata'); switch get(d.hp,'visible'); case 'on' set(d.hp,'visible','off'); case 'off' set(d.hp,'visible','on'); end %========================================================================== % dosn %========================================================================== function dosn(btn,evd) d = get(btn,'userdata'); switch get(d.ht(1),'visible') case 'on' set(d.ht,'visible','off'); case 'off' set(d.ht,'visible','on'); end %========================================================================== % %========================================================================== function doChangeTime(btn,evd) d = get(btn,'userdata'); v = get(btn,'value'); % get data if ishandle(d.in.handles.hfig) D = get(d.in.handles.hfig,'userdata'); if ~isfield(d.in,'trN') trN = 1; else trN = d.in.trN; end if isfield(D,'data') Z = D.data.y(d.in.ind,v,trN); Z = Z(d.goodChannels); if strcmp(d.in.type, 'MEGPLANAR') Z = combineplanar(Z, d.origpos, d.origChanLabel); end clear ud; % interpolate data ZI = griddata(d.interp.pos(1,:),d.interp.pos(2,:),full(double(Z)),d.interp.XI,d.interp.YI); % update data display set(d.hi,'Cdata',flipud(ZI)); % update time index display v = round(v); set(d.hti,'string',[num2str(d.in.gridTime(v)), ' (', d.in.unit, ')']); % update display marker position try;set(d.in.hl,'xdata',[v;v]);end set(d.ParentAxes,'nextPlot','add') try % delete current contour plot delete(findobj(d.ParentAxes,'type','hggroup')); % create new one [C,hc] = contour(d.ParentAxes,flipud(ZI),... 'linecolor',[0.5.*ones(3,1)]); end axis(d.ParentAxes,'image') drawnow else error('Did not find the data!') end else error('SPM Graphics Figure has been deleted!') end %========================================================================== % get2Dfrom3D %========================================================================== function [xy] = get2Dfrom3D(xyz) % function [xy] = get2Dfrom3D(xyz) % This function is used to flatten 3D sensor positions onto the 2D plane % using a modified spherical projection operation. % It is used to visualize channel data. % IN: % - xyz: the carthesian sensor position in 3D space % OUT: % - xy: the (x,y) carthesian coordinates of the sensors after projection % onto the best-fitting sphere if size(xyz,2) ~= 3 xyz = xyz'; end % exclude channels ? badChannels = find(isnan(xyz(:,1))); goodChannels = find(isnan(xyz(:,1))~=1); xyz = xyz(goodChannels,:); % Fit sphere to 3d sensors and center frame [C,R,out] = fitSphere(xyz(:,1),xyz(:,2),xyz(:,3)); xyz = xyz - repmat(C,size(xyz,1),1); % apply transformation using spherical coordinates [TH,PHI,RAD] = cart2sph(xyz(:,1),xyz(:,2),xyz(:,3)); TH = TH - mean(TH); [X,Y,Z] = sph2cart(TH,zeros(size(TH)),RAD.*(cos(PHI+pi./2)+1)); xy = [X(:),Y(:)]; %========================================================================== % combineplanar %========================================================================== function [Z, pos, ChanLabel] = combineplanar(Z, pos, ChanLabel) chanind = zeros(1, numel(ChanLabel)); for i = 1:numel(ChanLabel) chanind(i) = sscanf(ChanLabel{i}, 'MEG%d'); end pairs = []; unpaired = []; paired = zeros(length(chanind)); for i = 1:length(chanind) if ~paired(i) cpair = find(abs(chanind - chanind(i))<2); if length(cpair) == 1 unpaired = [unpaired cpair]; else pairs = [pairs; cpair(:)']; end paired(cpair) = 1; end end if ~isempty(unpaired) warning(['Could not pair all channels. Ignoring ' num2str(length(unpaired)) ' unpaired channels.']); end Z = sqrt(Z(pairs(:, 1)).^2 + Z(pairs(:, 2)).^2); pos = (pos(:, pairs(:, 1)) + pos(:, pairs(:, 2)))./2; ChanLabel = {}; for i = 1:size(pairs,1) ChanLabel{i} = ['MEG' num2str(min(pairs(i,:))) '+' num2str(max(pairs(i,:)))]; end %========================================================================== % fitSphere %========================================================================== function [C,R,out] = fitSphere(x,y,z) % fitSphere Fit sphere. % A = fitSphere(x,y,z) returns the parameters of the best-fit % [C,R,out] = fitSphere(x,y,z) returns the center and radius % sphere to data points in vectors (x,y,z) using Taubin's method. % IN: % - x/y/z: 3D carthesian ccordinates % OUT: % - C: the center of sphere coordinates % - R: the radius of the sphere % - out: an output structure devoted to graphical display of the best fit % sphere % Make sugary one and zero vectors l = ones(length(x),1); O = zeros(length(x),1); % Make design mx D = [(x.*x + y.*y + z.*z) x y z l]; Dx = [2*x l O O O]; Dy = [2*y O l O O]; Dz = [2*z O O l O]; % Create scatter matrices M = D'*D; N = Dx'*Dx + Dy'*Dy + Dz'*Dz; % Extract eigensystem [v, evalues] = eig(M); evalues = diag(evalues); Mrank = sum(evalues > eps*5*norm(M)); if (Mrank == 5) % Full rank -- min ev corresponds to solution Minverse = v'*diag(1./evalues)*v; [v,evalues] = eig(inv(M)*N); [dmin,dminindex] = max(diag(evalues)); pvec = v(:,dminindex(1))'; else % Rank deficient -- just extract nullspace of M pvec = null(M)'; [m,n] = size(pvec); if m > 1 pvec = pvec(1,:) end end % Convert to (R,C) if nargout == 1, if pvec(1) < 0 pvec = -pvec; end C = pvec; else C = -0.5*pvec(2:4) / pvec(1); R = sqrt(sum(C*C') - pvec(5)/pvec(1)); end [X,Y,Z] = sphere; [TH,PHI,R0] = cart2sph(X,Y,Z); [X,Y,Z] = sph2cart(TH,PHI,R); X = X + C(1); Y = Y + C(2); Z = Z + C(3); out.X = X; out.Y = Y; out.Z = Z;
github
philippboehmsturm/antx-master
spm_eeg_render.m
.m
antx-master/freiburgLight/matlab/spm8/spm_eeg_render.m
10,872
utf_8
52b7ba99932d4227bf2efefcc8766540
function [out] = spm_eeg_render(m,options) % Visualisation routine for the cortical surface % FORMAT [out] = spm_eeg_render(m,options) % % INPUT: % - m = MATLAB mesh (containing the fields .faces et .vertices) or GIFTI % format file. % - options = structure variable: % .texture = texture to be projected onto the mesh % .clusters = cortical parcelling (cell variable containing the % vertex indices of each cluster) % .clustersName = name of the clusters % .figname = name to be given to the window % .ParentAxes = handle of the axes within which the mesh should be % displayed % .hfig = handle of existing figure. If this option is provided, then % visu_maillage_surf adds the (textured) mesh to the figure hfig, and % a control for its transparancy. % % OUTPUT: % - out: a structure containing the fields: % .hfra: frame structure for movie building % .handles: a structure containing the handles of the created % uicontrols and mesh objects. % .m: the structure used to create the mesh %__________________________________________________________________________ % % This function is a visualization routine, mainly for texture and % clustering on the cortical surface. % NB: The texture and the clusters can not be visualized at the same time. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Jean Daunizeau % $Id: spm_eeg_render.m 3051 2009-04-06 14:47:09Z jean $ %----------------------------------------------------------------------% %------------- Common features for any visualization ------------------% %----------------------------------------------------------------------% % Check mesh format try if ischar(m) && exist(m,'file')==2 try m = gifti(m);end end m0.faces = m.faces; m0.vertices = m.vertices; m = m0; clear m0; catch disp('spm_eeg_render: unknown mesh format!') return end % Default options handles.fi = figure(... 'visible','off',... 'color',ones(1,3),... 'NumberTitle','Off',... 'Name','Mesh visualization',... 'tag','visu_maillage_surf'); ns = 0; texture = 'none'; clusters = 'none'; subplotBIN = 0; addMesh = 0; tag = ''; visible = 'on'; ParentAxes = axes('parent',handles.fi); try, options; catch options = [];end % Now get options if ~isempty(options) % get texture if provided try texture = options.texture;end % get ParentAxes try ParentAxes = options.ParentAxes;end % get tag try tag = options.tag;end % get flag for visibility: useful for displaying all objects at once try visible = options.visible;end % get custers if provided try clusters = options.clusters; IND = zeros(1,length(m.vertices)); K = length(clusters); for k = 1:K IND(clusters{k}) = k+1./K; end texture = IND'; end % get figname if provided try set(handles.fi,'NumberTitle','Off','Name',options.figname); end % get figure handle (should be parent of ParentAxes) try figure(options.hfig) if isempty(ParentAxes) ParentAxes = axes('parent',options.hfig,... 'nextplot','add'); end close(handles.fi); handles.fi = options.hfig; addMesh = 1; try % get number of transparency sliders in current figure... hh=get(handles.fi,'children'); ns=length(findobj(hh,'userdata','tag_UIC_transparency')); catch ns=1; end end end handles.ParentAxes = ParentAxes; oldRenderer = get(handles.fi,'renderer'); try if ismac set(handles.fi,'renderer','zbuffer'); else set(handles.fi,'renderer','OpenGL'); end catch set(handles.fi,'renderer','OpenGL'); end % Plot mesh and texture/clusters if isequal(texture,'none') figure(handles.fi) handles.p = patch(m,... 'facecolor', [.5 .5 .5], 'EdgeColor', 'none',... 'FaceLighting','gouraud',... 'parent',ParentAxes,... 'userdata',oldRenderer,... 'visible',visible,... 'tag',tag); else texture = texture(:); figure(handles.fi) if isequal(length(texture),length(m.vertices)) handles.p = patch(m,... 'facevertexcdata',texture,... 'facecolor','interp',... 'EdgeColor', 'none',... 'FaceLighting','gouraud',... 'parent',ParentAxes,... 'userdata',oldRenderer,... 'visible',visible,... 'tag',tag,... 'deleteFcn',@doDelMesh); col = colormap(ParentAxes,jet(256)); udd.tex = texture; udd.cax = caxis(ParentAxes); else texture = 'none'; disp('Warning: size of texture does not match number of vertices!') handles.p = patch(m,'facecolor', [.5 .5 .5], 'EdgeColor', 'none',... 'parent',ParentAxes,... 'userdata',oldRenderer,... 'visible',visible,... 'tag',tag,... 'deleteFcn',@doDelMesh); end end daspect(ParentAxes,[1 1 1]); axis(ParentAxes,'tight'); axis(ParentAxes,'off') camva(ParentAxes,'auto'); set(ParentAxes,'view',[25,45]); % build internal userdata structure udd.p = handles.p; %----------------------------------------------------------------------% %---------------------- GUI tools and buttons -------------------------% %----------------------------------------------------------------------% % Transparancy sliders pos = [20 100 20 245]; pos(1) = pos(1) + ns.*25; handles.transp = uicontrol(handles.fi,... 'style','slider',... 'position',pos,... 'min',0,... 'max',1,... 'value',1,... 'sliderstep',[0.01 0.05],... 'userdata',handles.p,... 'tooltipstring',['mesh #',num2str(ns+1),' transparency control'],... 'callback',{@doTransp},... 'BusyAction','cancel',... 'Interruptible','off',... 'visible',visible,... 'tag',tag); set(handles.transp,'units','normalized') handles.tag = uicontrol(handles.fi,... 'style','text',... 'visible','off',... 'tag',tag,... 'userdata','tag_UIC_transparency'); udd.transp = handles.transp; % Clustering buttons and popup menu if ~isequal(clusters,'none') if subplotBIN subplot(2,1,1) end % set(p,'FaceColor','flat'); col=lines; nc = floor(256./K); col = [repmat([0.8157 0.6666 0.5762],nc/2,1);... kron(col(1:K,:),ones(nc,1))]; if K > 1 col(end-nc/2:end,:) = []; end colormap(ParentAxes,col); tex = zeros(length(m.vertices),length(clusters)+1); tex(:,1) = texture; string = cell(length(clusters)+1,1); string{1} = 'all clusters'; for i = 1:length(clusters) if ~isfield(options,'clustersName') string{i+1} = ['cluster ',num2str(i)]; else string{i+1} = options.clustersName{i}; end tex(clusters{i},i+1) = 1; end udd.tex = tex; udd.tex0 = tex; udd.p = handles.p; udd.col = col; udd.nc = length(clusters); handles.pop = uicontrol(handles.fi,... 'style','popupmenu',... 'position',[20 20 100 40],... 'string',string,... 'callback',{@doSelectCluster},... 'BusyAction','cancel',... 'Interruptible','off',... 'visible',visible,'tag',tag); set(handles.pop,'units','normalized') handles.sli = uicontrol(handles.fi,... 'style','slider',... 'position',[50 10 30 20],'max',udd.nc,... 'sliderstep',[1./(udd.nc+0) 1./(udd.nc+0)],... 'callback',{@doSwitch2nextCluster},... 'BusyAction','cancel',... 'Interruptible','off',... 'visible',visible,'tag',tag); set(handles.sli,'units','normalized') udd.pop = handles.pop; udd.sli = handles.sli; set(handles.pop,'userdata',udd); set(handles.sli,'userdata',udd); end % Texture thresholding sliders if ~isequal(texture,'none') && isequal(clusters,'none') if subplotBIN subplot(2,1,1) end udd.tex0 = texture; udd.col = col; handles.hc = colorbar('peer',ParentAxes); set(handles.hc,'visible',visible) increment = 0.01; % right slider handles.s1 = uicontrol(handles.fi,... 'style','slider',... 'position',[440 28 20 380],... 'min',0,'max',length(udd.col),'value',0,... 'sliderstep',[increment increment],... 'tooltipstring','texture thresholding control',... 'callback',{@doThresh},... 'BusyAction','cancel',... 'Interruptible','off',... 'visible',visible,'tag',tag); set(handles.s1,'units','normalized') udd.s1 = handles.s1; % left slider handles.s2 = uicontrol(handles.fi,... 'style','slider',... 'position',[420 28 20 380],... 'min',1,'max',length(udd.col),... 'value',length(udd.col),... 'sliderstep',[increment increment],... 'tooltipstring','texture thresholding control',... 'callback',{@doThresh},... 'BusyAction','cancel',... 'Interruptible','off',... 'visible',visible,'tag',tag); set(handles.s2,'units','normalized') udd.s2 = handles.s2; set(handles.s1,'userdata',udd); set(handles.s2,'userdata',udd); end set(handles.fi,'visible','on'); drawnow % if ~addMesh camlight % end cameratoolbar(handles.fi,'setmode','orbit') out.hfra = getframe(gcf); out.handles = handles; out.m = m; %--------- subfunctions : BUTTONS CALLBACKS ------------% function doDelMesh(btn,evd) renderer=get(btn,'userdata'); set(gcf,'renderer',renderer); function doTransp(btn,evd) v00=get(btn,'value'); p00=get(btn,'userdata'); set(p00,'facealpha',v00); function doThresh(btn,evd) udd00 = get(btn,'userdata'); ind00 = round(get(udd00.s1,'value')); ind200 = round(get(udd00.s2,'value')); if(ind200>ind00) udd00.col(1:ind00,:)=0.5*ones(ind00,3); udd00.col(ind200+1:end,:)=0.5*ones(size(udd00.col(ind200+1:end,:))); else udd00.col(ind200:ind00,:)=0.5*ones(size(udd00.col(ind200:ind00,:))); end colormap(udd00.col); udd00.cax = caxis; function doSelectCluster(btn,evd) udd00 = get(btn,'userdata'); ind00=get(gcbo,'value'); set(udd00.sli,'value',ind00-1); set(udd00.p,'facevertexcdata',udd00.tex(:,ind00)); if ind00 == 1 colormap(udd00.col); else col00 = colormap(jet); col00(1:end/2,:)=0.5*ones(size(col00(1:end/2,:))); colormap(col00); end udd00.cax = caxis; function doSwitch2nextCluster(btn,evd) v00=get(btn,'value')+1; udd00=get(gcbo,'userdata'); ind00=min([v00 udd00.nc+1]); set(udd00.pop,'value',ind00); set(udd00.p,'facevertexcdata',udd00.tex(:,ind00)); if ind00 == 1 colormap(udd00.col); else col00 = colormap(jet); col00(1:end/2,:)=0.5; colormap(col00); end udd00.cax = caxis;
github
philippboehmsturm/antx-master
spm_write_sn.m
.m
antx-master/freiburgLight/matlab/spm8/spm_write_sn.m
19,859
utf_8
0ea1c7ae2ba1644c71deaf8ae1518452
function VO = spm_write_sn(V,prm,flags,extras) % Write out warped images % FORMAT VO = spm_write_sn(V,prm,flags,msk) % V - Images to transform (filenames or volume structure). % prm - Transformation information (filename or structure). % flags - flags structure, with fields... % interp - interpolation method (0-7) % wrap - wrap edges (e.g., [1 1 0] for 2D MRI sequences) % vox - voxel sizes (3 element vector - in mm) % Non-finite values mean use template vox. % bb - bounding box (2x3 matrix - in mm) % Non-finite values mean use template bb. % preserve - either 0 or 1. A value of 1 will "modulate" % the spatially normalised images so that total % units are preserved, rather than just % concentrations. % prefix - Prefix for normalised images. Defaults to 'w'. % msk - An optional cell array for masking the spatially % normalised images (see below). % % Warped images are written prefixed by "w". % % Non-finite vox or bounding box suggests that values should be derived % from the template image. % % Don't use interpolation methods greater than one for data containing % NaNs. %__________________________________________________________________________ % % FORMAT msk = spm_write_sn(V,prm,flags,'mask') % V - Images to transform (filenames or volume structure). % prm - Transformation information (filename or structure). % flags - flags structure, with fields... % wrap - wrap edges (e.g., [1 1 0] for 2D MRI sequences) % vox - voxel sizes (3 element vector - in mm) % Non-finite values mean use template vox. % bb - bounding box (2x3 matrix - in mm) % Non-finite values mean use template bb. % msk - a cell array for masking a series of spatially normalised % images. % % %_________________________________________________________________________ % % FORMAT VO = spm_write_sn(V,prm,'modulate') % V - Spatially normalised images to modulate (filenames or % volume structure). % prm - Transformation information (filename or structure). % % After nonlinear spatial normalization, the relative volumes of some % brain structures will have decreased, whereas others will increase. % The resampling of the images preserves the concentration of pixel % units in the images, so the total counts from structures that have % reduced volumes after spatial normalization will be reduced by an % amount proportional to the volume reduction. % % This routine rescales images after spatial normalization, so that % the total counts from any structure are preserved. It was written % as an optional step in performing voxel based morphometry. % %__________________________________________________________________________ % Copyright (C) 1996-2011 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id: spm_write_sn.m 4201 2011-02-15 10:52:00Z ged $ if isempty(V), return; end; if ischar(prm), prm = load(prm); end; if ischar(V), V = spm_vol(V); end; if nargin==3 && ischar(flags) && strcmpi(flags,'modulate'), if nargout==0, modulate(V,prm); else VO = modulate(V,prm); end; return; end; def_flags = spm_get_defaults('normalise.write'); def_flags.prefix = 'w'; if nargin < 3, flags = def_flags; else fnms = fieldnames(def_flags); for i=1:length(fnms), if ~isfield(flags,fnms{i}), flags.(fnms{i}) = def_flags.(fnms{i}); end; end; end; [x,y,z,mat] = get_xyzmat(prm,flags.bb,flags.vox); if nargin==4, if ischar(extras) && strcmpi(extras,'mask'), VO = get_snmask(V,prm,x,y,z,flags.wrap); return; end; if iscell(extras), msk = extras; end; end; if nargout>0 && length(V)>8, error('Too many images to save in memory'); end; if ~exist('msk','var') msk = get_snmask(V,prm,x,y,z,flags.wrap); end; if nargout==0, if isempty(prm.Tr), affine_transform(V,prm,x,y,z,mat,flags,msk); else nonlin_transform(V,prm,x,y,z,mat,flags,msk); end; else if isempty(prm.Tr), VO = affine_transform(V,prm,x,y,z,mat,flags,msk); else VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk); end; end; return; %========================================================================== %========================================================================== function VO = affine_transform(V,prm,x,y,z,mat,flags,msk) [X,Y] = ndgrid(x,y); d = [flags.interp*[1 1 1]' flags.wrap(:)]; spm_progress_bar('Init',numel(V),'Resampling','volumes/slices completed'); for i=1:numel(V), VO = make_hdr_struct(V(i),x,y,z,mat, flags.prefix); if flags.preserve VO.fname = prepend(VO.fname,'m'); end detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat); if flags.preserve, VO.pinfo(1:2,:) = VO.pinfo(1:2,:)/detAff; end; %Dat= zeros(VO.dim(1:3)); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; C = spm_bsplinc(V(i),d); for j=1:length(z), % Cycle over planes [X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\prm.VF(1).mat*prm.Affine); dat = spm_bsplins(C,X2,Y2,Z2,d); if flags.preserve, dat = dat*detAff; end; dat(msk{j}) = NaN; Dat(:,:,j) = single(dat); if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; if nargout~=0, VO.pinfo = [1 0]'; VO.dt = [spm_type('float32') spm_platform('bigend')]; VO.dat = Dat; else spm_write_vol(VO, Dat); end; spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %========================================================================== %========================================================================== function VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk) [X,Y] = ndgrid(x,y); Tr = prm.Tr; BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1); BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1); BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1); if flags.preserve, DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff'); DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff'); DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff'); end; d = [flags.interp*[1 1 1]' flags.wrap(:)]; spm_progress_bar('Init',numel(V),'Resampling','volumes completed'); for i=1:numel(V), VO = make_hdr_struct(V(i),x,y,z,mat, flags.prefix); if flags.preserve VO.fname = prepend(VO.fname,'m'); end detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat); % Accumulate data %Dat= zeros(VO.dim(1:3)); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; C = spm_bsplinc(V(i),d); for j=1:length(z), % Cycle over planes % Nonlinear deformations %------------------------------------------------------------------ tx = get_2Dtrans(Tr(:,:,:,1),BZ,j); ty = get_2Dtrans(Tr(:,:,:,2),BZ,j); tz = get_2Dtrans(Tr(:,:,:,3),BZ,j); X1 = X + BX*tx*BY'; Y1 = Y + BX*ty*BY'; Z1 = z(j) + BX*tz*BY'; [X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\prm.VF(1).mat*prm.Affine); dat = spm_bsplins(C,X2,Y2,Z2,d); dat(msk{j}) = NaN; if ~flags.preserve, Dat(:,:,j) = single(dat); else j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY'; j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY'; j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1; % The determinant of the Jacobian reflects relative volume changes %----------------------------------------------------------------- dat = dat .* (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff; Dat(:,:,j) = single(dat); end; if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; if nargout==0, if flags.preserve, VO = rmfield(VO,'pinfo'); end VO = spm_write_vol(VO,Dat); else VO.pinfo = [1 0]'; VO.dt = [spm_type('float32') spm_platform('bigend')]; VO.dat = Dat; end; spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %========================================================================== %========================================================================== function VO = modulate(V,prm) spm_progress_bar('Init',numel(V),'Modulating','volumes completed'); for i=1:numel(V), VO = V(i); VO = rmfield(VO,'pinfo'); VO.fname = prepend(VO.fname,'m'); detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat); %Dat = zeros(VO.dim(1:3)); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; [x,y,z,mat] = get_xyzmat(prm,NaN,NaN,VO); if sum((mat(:)-VO.mat(:)).^2)>1e-7, error('Orientations not compatible'); end; Tr = prm.Tr; if isempty(Tr), for j=1:length(z), % Cycle over planes dat = spm_slice_vol(V(i),spm_matrix([0 0 j]),V(i).dim(1:2),0); Dat(:,:,j) = single(dat); if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; else BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1); BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1); BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1); DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff'); DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff'); DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff'); for j=1:length(z), % Cycle over planes tx = get_2Dtrans(Tr(:,:,:,1),BZ,j); ty = get_2Dtrans(Tr(:,:,:,2),BZ,j); tz = get_2Dtrans(Tr(:,:,:,3),BZ,j); j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY'; j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY'; j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1; % The determinant of the Jacobian reflects relative volume changes %----------------------------------------------------------------- dat = spm_slice_vol(V(i),spm_matrix([0 0 j]),V(i).dim(1:2),0); dat = dat .* (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff; Dat(:,:,j) = single(dat); if numel(V)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; end; if nargout==0, VO = spm_write_vol(VO,Dat); else VO.pinfo = [1 0]'; VO.dt = [spm_type('float32') spm_platform('bigend')]; VO.dat = Dat; end; spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %========================================================================== %========================================================================== function VO = make_hdr_struct(V,x,y,z,mat,prefix) VO = V; VO.fname = prepend(V.fname,prefix); VO.mat = mat; VO.dim(1:3) = [length(x) length(y) length(z)]; VO.pinfo = V.pinfo; VO.descrip = 'spm - 3D normalized'; return; %========================================================================== %========================================================================== function T2 = get_2Dtrans(T3,B,j) d = [size(T3) 1 1 1]; tmp = reshape(T3,d(1)*d(2),d(3)); T2 = reshape(tmp*B(j,:)',d(1),d(2)); return; %========================================================================== %_______________________________________________________________________ function PO = prepend(PI,pre) [pth,nm,xt,vr] = spm_fileparts(deblank(PI)); PO = fullfile(pth,[pre nm xt vr]); return; %========================================================================== %========================================================================== function Mask = getmask(X,Y,Z,dim,wrp) % Find range of slice tiny = 5e-2; Mask = true(size(X)); if ~wrp(1), Mask = Mask & (X >= (1-tiny) & X <= (dim(1)+tiny)); end; if ~wrp(2), Mask = Mask & (Y >= (1-tiny) & Y <= (dim(2)+tiny)); end; if ~wrp(3), Mask = Mask & (Z >= (1-tiny) & Z <= (dim(3)+tiny)); end; return; %========================================================================== %========================================================================== function [X2,Y2,Z2] = mmult(X1,Y1,Z1,Mult) if length(Z1) == 1, X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + (Mult(1,3)*Z1 + Mult(1,4)); Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + (Mult(2,3)*Z1 + Mult(2,4)); Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + (Mult(3,3)*Z1 + Mult(3,4)); else X2= Mult(1,1)*X1 + Mult(1,2)*Y1 + Mult(1,3)*Z1 + Mult(1,4); Y2= Mult(2,1)*X1 + Mult(2,2)*Y1 + Mult(2,3)*Z1 + Mult(2,4); Z2= Mult(3,1)*X1 + Mult(3,2)*Y1 + Mult(3,3)*Z1 + Mult(3,4); end; return; %========================================================================== %========================================================================== function msk = get_snmask(V,prm,x,y,z,wrap) % Generate a mask for where there is data for all images %-------------------------------------------------------------------------- msk = cell(length(z),1); t1 = cat(3,V.mat); t2 = cat(1,V.dim); t = [reshape(t1,[16 length(V)])' t2(:,1:3)]; Tr = prm.Tr; [X,Y] = ndgrid(x,y); BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1); BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1); BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1); if numel(V)>1 && any(any(diff(t,1,1))), spm_progress_bar('Init',length(z),'Computing available voxels','planes completed'); for j=1:length(z), % Cycle over planes Count = zeros(length(x),length(y)); if isempty(Tr), % Generate a mask for where there is data for all images %-------------------------------------------------------------- for i=1:numel(V), [X2,Y2,Z2] = mmult(X,Y,z(j),V(i).mat\prm.VF(1).mat*prm.Affine); Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap); end; else % Nonlinear deformations %-------------------------------------------------------------- X1 = X + BX*get_2Dtrans(Tr(:,:,:,1),BZ,j)*BY'; Y1 = Y + BX*get_2Dtrans(Tr(:,:,:,2),BZ,j)*BY'; Z1 = z(j) + BX*get_2Dtrans(Tr(:,:,:,3),BZ,j)*BY'; % Generate a mask for where there is data for all images %-------------------------------------------------------------- for i=1:numel(V), [X2,Y2,Z2] = mmult(X1,Y1,Z1,V(i).mat\prm.VF(1).mat*prm.Affine); Count = Count + getmask(X2,Y2,Z2,V(i).dim(1:3),wrap); end; end; msk{j} = uint32(find(Count ~= numel(V))); spm_progress_bar('Set',j); end; spm_progress_bar('Clear'); else for j=1:length(z), msk{j} = uint32([]); end; end; return; %========================================================================== %========================================================================== function [x,y,z,mat] = get_xyzmat(prm,bb,vox,VG) % The old voxel size and origin notation is used here. % This requires that the position and orientation % of the template is transverse. It would not be % straitforward to account for templates that are % in different orientations because the basis functions % would no longer be seperable. The seperable basis % functions mean that computing the deformation field % from the parameters is much faster. % bb = sort(bb); % vox = abs(vox); if nargin<4, VG = prm.VG(1); if all(~isfinite(bb(:))) && all(~isfinite(vox(:))), x = 1:VG.dim(1); y = 1:VG.dim(2); z = 1:VG.dim(3); mat = VG.mat; return; end end [bb0 vox0] = spm_get_bbox(VG, 'old'); if ~all(isfinite(vox(:))), vox = vox0; end; if ~all(isfinite(bb(:))), bb = bb0; end; msk = find(vox<0); bb = sort(bb); bb(:,msk) = flipud(bb(:,msk)); % Adjust bounding box slightly - so it rounds to closest voxel. % Comment out if not needed. %bb(:,1) = round(bb(:,1)/vox(1))*vox(1); %bb(:,2) = round(bb(:,2)/vox(2))*vox(2); %bb(:,3) = round(bb(:,3)/vox(3))*vox(3); M = prm.VG(1).mat; vxg = sqrt(sum(M(1:3,1:3).^2)); if det(M(1:3,1:3))<0, vxg(1) = -vxg(1); end; ogn = M\[0 0 0 1]'; ogn = ogn(1:3)'; % Convert range into range of voxels within template image x = (bb(1,1):vox(1):bb(2,1))/vxg(1) + ogn(1); y = (bb(1,2):vox(2):bb(2,2))/vxg(2) + ogn(2); z = (bb(1,3):vox(3):bb(2,3))/vxg(3) + ogn(3); og = -vxg.*ogn; % Again, chose whether to round to closest voxel. %of = -vox.*(round(-bb(1,:)./vox)+1); of = bb(1,:)-vox; M1 = [vxg(1) 0 0 og(1) ; 0 vxg(2) 0 og(2) ; 0 0 vxg(3) og(3) ; 0 0 0 1]; M2 = [vox(1) 0 0 of(1) ; 0 vox(2) 0 of(2) ; 0 0 vox(3) of(3) ; 0 0 0 1]; mat = prm.VG(1).mat*inv(M1)*M2; LEFTHANDED = true; if (LEFTHANDED && det(mat(1:3,1:3))>0) || (~LEFTHANDED && det(mat(1:3,1:3))<0), Flp = [-1 0 0 (length(x)+1); 0 1 0 0; 0 0 1 0; 0 0 0 1]; mat = mat*Flp; x = flipud(x(:))'; end; return; %========================================================================== %========================================================================== function VO = write_dets(P,bb,vox) if nargin==1, job = P; P = job.P; bb = job.bb; vox = job.vox; end; spm_progress_bar('Init',numel(P),'Writing','volumes completed'); for i=1:numel(V), prm = load(deblank(P{i})); [x,y,z,mat] = get_xyzmat(prm,bb,vox); Tr = prm.Tr; BX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1); BY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1); BZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1); DX = spm_dctmtx(prm.VG(1).dim(1),size(Tr,1),x-1,'diff'); DY = spm_dctmtx(prm.VG(1).dim(2),size(Tr,2),y-1,'diff'); DZ = spm_dctmtx(prm.VG(1).dim(3),size(Tr,3),z-1,'diff'); [pth,nam,ext,nm] = spm_fileparts(P{i}); VO = struct('fname',fullfile(pth,['jy_' nam ext nm]),... 'dim',[numel(x),numel(y),numel(z)],... 'dt',[spm_type('float32') spm_platform('bigend')],... 'pinfo',[1 0 0]',... 'mat',mat,... 'n',1,... 'descrip','Jacobian determinants'); VO = spm_create_vol(VO); detAff = det(prm.VF(1).mat*prm.Affine/prm.VG(1).mat); Dat = single(0); Dat(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; for j=1:length(z), % Cycle over planes % Nonlinear deformations tx = get_2Dtrans(Tr(:,:,:,1),BZ,j); ty = get_2Dtrans(Tr(:,:,:,2),BZ,j); tz = get_2Dtrans(Tr(:,:,:,3),BZ,j); %------------------------------------------------------------------ j11 = DX*tx*BY' + 1; j12 = BX*tx*DY'; j13 = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY'; j21 = DX*ty*BY'; j22 = BX*ty*DY' + 1; j23 = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY'; j31 = DX*tz*BY'; j32 = BX*tz*DY'; j33 = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1; % The determinant of the Jacobian reflects relative volume changes. %------------------------------------------------------------------ dat = (j11.*(j22.*j33-j23.*j32) - j21.*(j12.*j33-j13.*j32) + j31.*(j12.*j23-j13.*j22)) * detAff; Dat(:,:,j) = single(dat); if numel(P)<5, spm_progress_bar('Set',i-1+j/length(z)); end; end; VO = spm_write_vol(VO,Dat); spm_progress_bar('Set',i); end; spm_progress_bar('Clear'); return; %==========================================================================