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
tbx_run_fbi_dicom_dti.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/FBIDicom/tbx_run_fbi_dicom_dti.m
6,847
utf_8
bcd21d678faa8a40b734a5af3de31348
function out = tbx_run_fbi_dicom_dti(job) % SPM job execution function % takes a harvested job data structure and call SPM functions to perform % computations on the data. % Input: % job - harvested job data structure (see matlabbatch help) % Output: % out - computation results, usually a struct variable. % tbx_run_fbi_dicom.m,v 1.3 2008/05/21 11:43:30 vglauche Exp %_______________________________________________________________________ % Copyright (C) 2007 Freiburg Brain Imaging % Volkmar Glauche % $Id: tbx_run_fbi_dicom_dti.m 30 2010-06-29 13:41:42Z volkmar $ rev = '$Rev: 30 $'; %#ok<NASGU> opwd = pwd; if ~isempty(char(job.outdir)) cd(char(job.outdir)); end out.files = {}; for k = 1:numel(job.dirs) files = dir(fullfile(job.dirs{k},'*.dcm')); if isempty(files) cd(opwd) error(['No DICOM files found in directory ''%s''. Check that the ' ... 'files are online and try again.'], job.dirs{k}); else fnames = cellfun(@(fn)fullfile(job.dirs{k},fn),{files.name},'UniformOutput',false); hdr = spm_dicom_headers(char(fnames)); atime = zeros(size(hdr)); for m = 1:numel(hdr) atime(m) = hdr{m}.AcquisitionTime; end [un aind] = sort(atime); if k == 1 out.files{1} = getfilelocation(hdr{aind(1)},job.root); end try [out.files{1}, status, errorstring] = read_dti_dicom(job.dirs{k}, ... files(aind), k > 1, out.files{1}, k); catch errorstring = 'DTI DICOM import failed.'; end if ~isequal(status,[1 1 1]) errorstring = 'The Dicom data does not privide all necessary information for the calculation of the tensors.\nThe reason for this might be that you don not work with Siemens Dicom.\n Please use the GUI instead (dti_tool) of the Batch Editor (see manual).\nAnother option would be that you read in your data into an mrstruct (see manual) and set up the batch using this as raw data.'; end if ~isempty(errorstring) fprintf(['Data in folder ''%s'' can not be converted. Please ' ... 'check whether this folder exists and make sure it ' ... 'contains only DTI DICOM data. The original error ' ... 'message was:\n %s\n'], job.dirs{k}, errorstring); end end end out.files{1} = [out.files{1} '_raw.bin']; cd(opwd); % The following code is copied from spm_dicom_convert (with modification % regarding ICE dims and format in filenames) %_______________________________________________________________________ %_______________________________________________________________________ function fname = getfilelocation(hdr,root_dir,prefix) if nargin < 3 prefix = 'f'; end; if strncmp(root_dir,'ice',3) % ICE dims sorting not supported root_dir = root_dir(4:end); end; if strcmp(root_dir, 'flat') % Standard SPM5 file conversion %------------------------------------------------------------------- if checkfields(hdr,'SeriesNumber','AcquisitionNumber') if checkfields(hdr,'EchoNumbers') fname = sprintf('%s%s-%.4d-%.5d-%.6d-%.2d', prefix, strip_unwanted(hdr.PatientID),... hdr.SeriesNumber, hdr.AcquisitionNumber, hdr.InstanceNumber,... hdr.EchoNumbers); else fname = sprintf('%s%s-%.4d-%.5d-%.6d', prefix, strip_unwanted(hdr.PatientID),... hdr.SeriesNumber, hdr.AcquisitionNumber, ... hdr.InstanceNumber); end; else fname = sprintf('%s%s-%.6d',prefix, ... strip_unwanted(hdr.PatientID),hdr.InstanceNumber); end; fname = fullfile(pwd,fname); return; end; % more fancy stuff - sort images into subdirectories if ~isfield(hdr,'ProtocolName') if isfield(hdr,'SequenceName') hdr.ProtocolName = hdr.SequenceName; else hdr.ProtocolName='unknown'; end; end; if ~isfield(hdr,'SeriesDescription') hdr.SeriesDescription = 'unknown'; end; if ~isfield(hdr,'EchoNumbers') hdr.EchoNumbers = 0; end; m = sprintf('%02d', floor(rem(hdr.StudyTime/60,60))); h = sprintf('%02d', floor(hdr.StudyTime/3600)); studydate = sprintf('%s_%s-%s', datestr(hdr.StudyDate,'yyyy-mm-dd'), ... h,m); switch root_dir case 'date_time', id = studydate; case {'patid', 'patid_date', 'patname'}, id = strip_unwanted(hdr.PatientID); end; serdes = strrep(strip_unwanted(hdr.SeriesDescription),... strip_unwanted(hdr.ProtocolName),''); protname = sprintf('%s%s_%.4d',strip_unwanted(hdr.ProtocolName), ... serdes, hdr.SeriesNumber); switch root_dir case 'date_time', dname = fullfile(pwd, id, protname); case 'patid', dname = fullfile(pwd, id, protname); case 'patid_date', dname = fullfile(pwd, id, studydate, protname); case 'patname', dname = fullfile(pwd, strip_unwanted(hdr.PatientsName), ... id, protname); otherwise error('unknown file root specification'); end; if ~exist(dname,'dir'), mkdir_rec(dname); end; % some non-product sequences on SIEMENS scanners seem to have problems % with image numbering in MOSAICs - doublettes, unreliable ordering % etc. To distinguish, always include Acquisition time in image name sa = sprintf('%02d', floor(rem(hdr.AcquisitionTime,60))); ma = sprintf('%02d', floor(rem(hdr.AcquisitionTime/60,60))); ha = sprintf('%02d', floor(hdr.AcquisitionTime/3600)); fname = sprintf('%s%s-%s%s%s-%.5d-%.5d-%d', prefix, id, ha, ma, sa, ... hdr.AcquisitionNumber,hdr.InstanceNumber, ... hdr.EchoNumbers); fname = fullfile(dname, fname); %_______________________________________________________________________ %_______________________________________________________________________ function suc = mkdir_rec(str) % works on full pathnames only opwd=pwd; if str(end) ~= filesep, str = [str filesep];end; pos = strfind(str,filesep); suc = zeros(1,length(pos)); for g=2:length(pos) if ~exist(str(1:pos(g)-1),'dir'), cd(str(1:pos(g-1)-1)); suc(g) = mkdir(str(pos(g-1)+1:pos(g)-1)); end; end; cd(opwd); return; %_______________________________________________________________________ %_______________________________________________________________________ function ok = checkfields(hdr,varargin) ok = 1; for i=1:(nargin-1), if ~isfield(hdr,varargin{i}), ok = 0; break; end; end; return; %_______________________________________________________________________ %_______________________________________________________________________ function clean = strip_unwanted(dirty) msk = (dirty>='a'&dirty<='z') | (dirty>='A'&dirty<='Z') |... (dirty>='0'&dirty<='9') | dirty=='_'; clean = dirty(msk); return;
github
philippboehmsturm/antx-master
spm_dpss.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/spectral/spm_dpss.m
4,266
utf_8
f38f5c5d111b9dd2c799242fc07d7e30
function [E] = spm_dpss (N,NW) % Compute discrete prolate spheroidal sequences % FORMAT [E] = spm_dpss (N,NW) % % N Length of taper % NW Product of N and W % % E [N x 2NW] matrix containing dpss sequences % The kth column contains the sequence which % comprises the length N signal that is kth most % concentrated in the frequency band |w|<=2*pi*W radians % % See Section 8.3 in % Percival, D.B. and Walden, A.T., "Spectral Analysis For Physical % Applications", Cambridge University Press, 1993. %__________________________________________________________________________ % Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging % Eric Breitenberger, 10/3/95 % Copyright 1988-2004 The MathWorks, Inc. % $Id: spm_dpss.m 3821 2010-04-15 14:26:34Z will $ W=NW/N; k = min(round(2*N*W),N); k = max(k,1); k = [1 k]; % Generate first and second diagonals d=((N-1-2*(0:N-1)').^2)*.25*cos(2*pi*W); ee=(1:N-1)'.*(N-1:-1:1)'/2; % Get the eigenvalues of B - see page 382 Percival and Walden v = tridieig(d,[0; ee],N-k(2)+1,N-k(1)+1); v = v(end:-1:1); Lv = length(v); % Compute the eigenvectors by inverse iteration with % starting vectors of roughly the right shape. E = zeros(N,k(2)-k(1)+1); t = (0:N-1)'/(N-1)*pi; for j = 1:Lv e = sin((j+k(1)-1)*t); e = tridisolve(ee,d-v(j),ee,e); e = tridisolve(ee,d-v(j),ee,e/norm(e)); e = tridisolve(ee,d-v(j),ee,e/norm(e)); E(:,j) = e/norm(e); end d=mean(E); for i=k(1):k(2) if rem(i,2) % i is odd % Polarize symmetric dpss if d(i-k(1)+1)<0, E(:,i-k(1)+1)=-E(:,i-k(1)+1); end else % i is even % Polarize anti-symmetric dpss if E(2,i-k(1)+1)<0, E(:,i-k(1)+1)=-E(:,i-k(1)+1); end end end function x = tridieig(c,b,m1,m2,eps1); %TRIDIEIG Find a few eigenvalues of a tridiagonal matrix. % LAMBDA = TRIDIEIG(D,E,M1,M2). D and E, two vectors of length N, % define a symmetric, tridiagonal matrix: % A = diag(E(2:N),-1) + diag(D,0) + diag(E(2:N),1) % E(1) is ignored. % TRIDIEIG(D,E,M1,M2) computes the eigenvalues of A with indices % M1 <= K <= M2. % TRIDIEIG(D,E,M1,M2,TOL) uses TOL as a tolerance. % % C. Moler % Copyright 1988-2002 The MathWorks, Inc. if nargin < 5, eps1 = 0; end n = length(c); b(1) = 0; beta = b.*b; xmin = min(c(n) - abs(b(n)),min(c(1:n-1) - abs(b(1:n-1)) - abs(b(2:n)))); xmax = max(c(n) + abs(b(n)),max(c(1:n-1) + abs(b(1:n-1)) + abs(b(2:n)))); eps2 = eps*max(xmax,-xmin); if eps1 <= 0, eps1 = eps2; end eps2 = 0.5*eps1 + 7*eps2; x0 = xmax; x = zeros(n,1); wu = zeros(n,1); x(m1:m2) = xmax(ones(m2-m1+1,1)); wu(m1:m2) = xmin(ones(m2-m1+1,1)); z = 0; for k = m2:-1:m1 xu = xmin; for i = k:-1:m1 if xu < wu(i) xu = wu(i); break end end if x0 > x(k), x0 = x(k); end while 1 x1 = (xu + x0)/2; if x0 - xu <= 2*eps*(abs(xu)+abs(x0)) + eps1 break end z = z + 1; a = 0; q = 1; for i = 1:n if q ~= 0 s = beta(i)/q; else s = abs(b(i))/eps; end q = c(i) - x1 - s; a = a + (q < 0); end if a < k if a < m1 xu = x1; wu(m1) = x1; else xu = x1; wu(a+1) = x1; if x(a) > x1, x(a) = x1; end end else x0 = x1; end end x(k) = (x0 + xu)/2; end x = x(m1:m2)'; function x = tridisolve(a,b,c,d) % TRIDISOLVE Solve tridiagonal system of equations. % x = TRIDISOLVE(a,b,c,d) solves the system of linear equations % b(1)*x(1) + c(1)*x(2) = d(1), % a(j-1)*x(j-1) + b(j)*x(j) + c(j)*x(j+1) = d(j), j = 2:n-1, % a(n-1)*x(n-1) + b(n)*x(n) = d(n). % % The algorithm does not use pivoting, so the results might % be inaccurate if abs(b) is much smaller than abs(a)+abs(c). % More robust, but slower, alternatives with pivoting are: % x = T\d where T = diag(a,-1) + diag(b,0) + diag(c,1) % x = S\d where S = spdiags([[a; 0] b [0; c]],[-1 0 1],n,n) x = d; n = length(x); for j = 1:n-1 mu = a(j)/b(j); b(j+1) = b(j+1) - mu*c(j); x(j+1) = x(j+1) - mu*x(j); end x(n) = x(n)/b(n); for j = n-1:-1:1 x(j) = (x(j)-c(j)*x(j+1))/b(j); end
github
philippboehmsturm/antx-master
tbx_cfg_vgtbx_Diffusion.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/tbx_cfg_vgtbx_Diffusion.m
155,387
utf_8
8dd9995d5b6c7f79aa25787c3f08fd63
function vgtbx_Diffusion = tbx_cfg_vgtbx_Diffusion % Diffusion toolbox %_______________________________________________________________________ % % This toolbox contains various functions related to post-processing of % diffusion weighted image series in SPM5. Topics include movement % correction for image time series, estimation of the diffusion tensor, % computation of anisotropy indices and tensor decomposition. Visualisation % of diffusion tensor data (quiver & red-green-blue plots of eigenvector % data) is not included in this toolbox, but there are separate plugins % for spm_orthviews available for download at the same place as the % source code of this toolbox. % % The algorithms applied in this toolbox are referenced within the PDF help % texts of the functions where they are implemented. % % This toolbox is free but copyright software, distributed under the % terms of the GNU General Public Licence as published by the Free % Software Foundation (either version 2, as given in file % spm_LICENCE.man, or at your option, any later version). Further details % on "copyleft" can be found at http://www.gnu.org/copyleft/. % The toolbox consists of the files listed in its Contents.m file. % % The source code of this toolbox is available at % % http://sourceforge.net/projects/spmtools % % Please use the SourceForge forum and tracker system for comments, % suggestions, bug reports etc. regarding this toolbox. %_______________________________________________________________________ % % @(#) $Id: vgtbx_config_Diffusion.m 543 2008-03-12 19:40:40Z glauche $ rev='$Revision: 543 $'; addpath(genpath(fullfile(spm('dir'),'toolbox','Diffusion'))); % see how we are called - if no output argument, then start spm_jobman UI if nargout == 0 spm_jobman('interactive'); return; end; % MATLABBATCH Configuration file for toolbox 'Diffusion toolbox' % This code has been automatically generated. % --------------------------------------------------------------------- % srcimgs Source Images % --------------------------------------------------------------------- srcimgs = cfg_files; srcimgs.tag = 'srcimgs'; srcimgs.name = 'Source Images'; srcimgs.help = {'The source images (one or more).'}; srcimgs.filter = 'image'; srcimgs.ufilter = '.*'; srcimgs.num = [1 Inf]; % --------------------------------------------------------------------- % b B values % --------------------------------------------------------------------- b = cfg_entry; b.tag = 'b'; b.name = 'B values'; b.help = {'A vector of b values (one number per image). The actual b value used in tensor computation will depend on this value, multiplied with the length of the corresponding gradient vector.'}; b.strtype = 'e'; b.num = [Inf 1]; % --------------------------------------------------------------------- % g Gradient direction values % --------------------------------------------------------------------- g = cfg_entry; g.tag = 'g'; g.name = 'Gradient direction values'; g.help = {'A #img-by-3 matrix of gradient directions. The length of each gradient vector will be used as a scaling factor to the b value. Therefore, you should make sure that your gradient vectors are of unit length if your b value already encodes for diffusion weighting strength.'}; g.strtype = 'e'; g.num = [Inf 3]; % --------------------------------------------------------------------- % M Reset orientation % --------------------------------------------------------------------- M = cfg_const; M.tag = 'M'; M.name = 'Reset orientation'; M.val{1} = double(1); M.help = {''}; % --------------------------------------------------------------------- % resetall (Re)set Gradient, b value and position % --------------------------------------------------------------------- resetall = cfg_branch; resetall.tag = 'resetall'; resetall.name = '(Re)set Gradient, b value and position'; resetall.val = {b g M }; resetall.help = {''}; % --------------------------------------------------------------------- % b B values % --------------------------------------------------------------------- b = cfg_entry; b.tag = 'b'; b.name = 'B values'; b.help = {'A vector of b values (one number per image). The actual b value used in tensor computation will depend on this value, multiplied with the length of the corresponding gradient vector.'}; b.strtype = 'e'; b.num = [Inf 1]; % --------------------------------------------------------------------- % g Gradient direction values % --------------------------------------------------------------------- g = cfg_entry; g.tag = 'g'; g.name = 'Gradient direction values'; g.help = {'A #img-by-3 matrix of gradient directions. The length of each gradient vector will be used as a scaling factor to the b value. Therefore, you should make sure that your gradient vectors are of unit length if your b value already encodes for diffusion weighting strength.'}; g.strtype = 'e'; g.num = [Inf 3]; % --------------------------------------------------------------------- % resetbg (Re)set Gradient and b value % --------------------------------------------------------------------- resetbg = cfg_branch; resetbg.tag = 'resetbg'; resetbg.name = '(Re)set Gradient and b value'; resetbg.val = {b g }; resetbg.help = {''}; % --------------------------------------------------------------------- % b B values % --------------------------------------------------------------------- b = cfg_entry; b.tag = 'b'; b.name = 'B values'; b.help = {'A vector of b values (one number per image). The actual b value used in tensor computation will depend on this value, multiplied with the length of the corresponding gradient vector.'}; b.strtype = 'e'; b.num = [Inf 1]; % --------------------------------------------------------------------- % resetb (Re)set b value % --------------------------------------------------------------------- resetb = cfg_branch; resetb.tag = 'resetb'; resetb.name = '(Re)set b value'; resetb.val = {b }; resetb.help = {''}; % --------------------------------------------------------------------- % g Gradient direction values % --------------------------------------------------------------------- g = cfg_entry; g.tag = 'g'; g.name = 'Gradient direction values'; g.help = {'A #img-by-3 matrix of gradient directions. The length of each gradient vector will be used as a scaling factor to the b value. Therefore, you should make sure that your gradient vectors are of unit length if your b value already encodes for diffusion weighting strength.'}; g.strtype = 'e'; g.num = [Inf 3]; % --------------------------------------------------------------------- % reset (Re)set Gradient % --------------------------------------------------------------------- reset = cfg_branch; reset.tag = 'reset'; reset.name = '(Re)set Gradient'; reset.val = {g }; reset.help = {''}; % --------------------------------------------------------------------- % M Reset orientation % --------------------------------------------------------------------- M = cfg_const; M.tag = 'M'; M.name = 'Reset orientation'; M.val{1} = double(1); M.help = {''}; % --------------------------------------------------------------------- % resetM (Re)set position % --------------------------------------------------------------------- resetM = cfg_branch; resetM.tag = 'resetM'; resetM.name = '(Re)set position'; resetM.val = {M }; resetM.help = {''}; % --------------------------------------------------------------------- % setM Add M matrix to existing DTI information % --------------------------------------------------------------------- setM = cfg_const; setM.tag = 'setM'; setM.name = 'Add M matrix to existing DTI information'; setM.val{1} = double(1); setM.help = {''}; % --------------------------------------------------------------------- % initopts (Re)Set what? % --------------------------------------------------------------------- initopts = cfg_choice; initopts.tag = 'initopts'; initopts.name = '(Re)Set what?'; initopts.help = {''}; initopts.values = {resetall resetbg resetb reset resetM setM }; % --------------------------------------------------------------------- % init_dtidata (Re)Set DTI information % --------------------------------------------------------------------- init_dtidata = cfg_exbranch; init_dtidata.tag = 'dti_init_dtidata'; init_dtidata.name = '(Re)Set DTI information'; init_dtidata.val = {srcimgs initopts }; init_dtidata.help = { 'Initialise userdata of diffusion weighted images' '' 'This routine allows to (re)set diffusion and orientation information for a series of diffusion weighted images (the orientation part can be used for other image series as well).' 'Diffusion information needs to be given for each individual image as a vector of b values and a number-of-images-by-3 matrix of diffusion gradient directions. This toolbox assumes that gradient directions are given in "world space". spm_input will read diffusion information from workspace variables if you type the variable name in the input field or even load it from a file. So, if you have to set diffusion information for a set of repeated measurements with diffusion information for one measurement stored in ''dti.txt'', you could use the syntax' 'repmat(load(''dti.txt''),nrep,1)' 'where dti.txt contains gradient information for all images within a repetition (one row with 3 columns per direction).' 'This routine is useful to initialise diffusion weighted images that have no diffusion information available in its DICOM header or to re-initialise images that have already been processed (e.g. to redo realignment).' '' 'Batch processing:' 'FORMAT dti_init_dtidata(bch)' '======' 'Input argument:' 'bch struct with fields' '/*\begin{description}*/' '/*\item[*/ .srcimgs/*]*/ cell array of file names' '/*\item[*/ .b/*]*/ numel(files)-by-1 vector of b values' '/*\item[*/ .g/*]*/ numel(files)-by-3 matrix of diffusion weighting directions' '/*\item[*/ .M/*]*/ 4x4 transformation matrix. If not set, and position should be reset, then the space will be reset to the saved information from DTI userdata. If this information is not available, the space of the first image is taken as reference.' '/*\end{description}*/' 'To add .M to DTI userdata, no additional input is necessary. In this case, the current .mat information (obtained from spm_get_space) will be saved if DTI userdata exists.' 'Note that re-setting .b or .g does not re-set the saved reference .mat. However, if no diffusion information was present before, also .mat will be created with the current space information. This occurs after a .M has been processed, so that redoing reorientation and setting diffusion information can be done in one step per image.' '' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id$' }'; init_dtidata.prog = @dti_init_dtidata; init_dtidata.vout = @vout_dti_init_dtidata; % --------------------------------------------------------------------- % srcimgs Source Images % --------------------------------------------------------------------- srcimgs = cfg_files; srcimgs.tag = 'srcimgs'; srcimgs.name = 'Source Images'; srcimgs.filter = 'image'; srcimgs.ufilter = '.*'; srcimgs.num = [2 Inf]; % --------------------------------------------------------------------- % infix Output Filename Infix % --------------------------------------------------------------------- infix = cfg_entry; infix.tag = 'infix'; infix.name = 'Output Filename Infix'; infix.val = {''}; infix.help = {['The output filename is constructed by prefixing ''m/s'' and this infix to ' ... 'the original filename.']}; infix.strtype = 's'; infix.num = [0 Inf]; % --------------------------------------------------------------------- % dw_wmean_variance Weighted Means and Variances % --------------------------------------------------------------------- dw_wmean_variance = cfg_exbranch; dw_wmean_variance.tag = 'dw_wmean_variance'; dw_wmean_variance.name = 'Weighted Means and Variances'; dw_wmean_variance.val = {srcimgs infix}; dw_wmean_variance.help = {'This tool calculates the weighted means and variances for a set of diffusion weighted images.'}; dw_wmean_variance.prog = @(job)dti_dw_wmean_variance('run',job); dw_wmean_variance.vout = @(job)dti_dw_wmean_variance('vout',job); % --------------------------------------------------------------------- % osrcimgs - Source Images % --------------------------------------------------------------------- osrcimgs = cfg_files; osrcimgs.tag = 'osrcimgs'; osrcimgs.name = 'Source Images'; osrcimgs.help = {'A list of images to be analysed. The computed selection indices will refer to this list of images.'}; osrcimgs.filter = 'image'; osrcimgs.ufilter = '.*'; osrcimgs.num = [1 Inf]; % --------------------------------------------------------------------- % msrcimgs - Source Images % --------------------------------------------------------------------- msrcimgs = cfg_files; msrcimgs.tag = 'msrcimgs'; msrcimgs.name = '(Weighted) Mean Images'; msrcimgs.help = {'A list of (weighted) mean images or a single mean image.'}; msrcimgs.filter = 'image'; msrcimgs.ufilter = '.*'; msrcimgs.num = [1 Inf]; % --------------------------------------------------------------------- % ssrcimgs - Source Images % --------------------------------------------------------------------- ssrcimgs = cfg_files; ssrcimgs.tag = 'ssrcimgs'; ssrcimgs.name = '(Weighted) Standard Deviation Images'; ssrcimgs.help = {'A list of (weighted) standard deviation images or a single standard deviation image.'}; ssrcimgs.filter = 'image'; ssrcimgs.ufilter = '.*'; ssrcimgs.num = [1 Inf]; % --------------------------------------------------------------------- % maskimg - Mask Image (optional) % --------------------------------------------------------------------- maskimg = cfg_files; maskimg.tag = 'maskimg'; maskimg.name = 'Mask Image (optional)'; maskimg.help = {'If supplied, each source image will be weighted by this mask image before clustering.' 'The mask image should have values between 0 (voxel does not belong to ROI) and 1 (voxel does belong to ROI). Fractional values are allowed.'}; maskimg.filter = 'image'; maskimg.ufilter = '.*'; maskimg.num = [0 1]; % --------------------------------------------------------------------- % th Intensity Threshold % --------------------------------------------------------------------- th = cfg_entry; th.tag = 'th'; th.name = 'Intensity Threshold'; th.help = {'The source images will be thresholded at this intensity. Those voxels which have a higher intensity than this threshold will be counted and clustered.'}; th.strtype = 'r'; th.num = [1 1]; % --------------------------------------------------------------------- % csize Minimum Cluster Size % --------------------------------------------------------------------- csize = cfg_entry; csize.tag = 'csize'; csize.name = 'Minimum Cluster Size'; csize.help = {'An image will be excluded from the selection list if at least one cluster at the specified intensity threshold exceed the minimum cluster size defined here.'}; csize.strtype = 'w'; csize.num = [1 1]; % --------------------------------------------------------------------- % thresh Threshold Specification % --------------------------------------------------------------------- thresh = cfg_branch; thresh.tag = 'thresh'; thresh.name = 'Threshold Specification'; thresh.val = {th csize }; % --------------------------------------------------------------------- % threshs Threshold Specifications % --------------------------------------------------------------------- threshs = cfg_repeat; threshs.tag = 'threshs'; threshs.name = 'Threshold Specifications'; threshs.help = {'One or more threshold specifications can be given. An image will be excluded from the final selection if it is excluded by one or more of the threshold criteria.'}; threshs.values = {thresh }; threshs.num = [1 Inf]; % --------------------------------------------------------------------- % dw_cluster_std_differences Cluster and Select Images % --------------------------------------------------------------------- dw_cluster_std_differences = cfg_exbranch; dw_cluster_std_differences.tag = 'dw_cluster_std_differences'; dw_cluster_std_differences.name = 'Cluster and Select Images'; dw_cluster_std_differences.val = {osrcimgs msrcimgs ssrcimgs maskimg threshs }; dw_cluster_std_differences.prog = @(job)dti_dw_cluster_std_differences('run',job); dw_cluster_std_differences.vout = @(job)dti_dw_cluster_std_differences('vout',job); dw_cluster_std_differences.check = @(job)dti_dw_cluster_std_differences('check','srcimgs',job); % --------------------------------------------------------------------- % osrcimgs Original Images % --------------------------------------------------------------------- osrcimgs = cfg_files; osrcimgs.tag = 'osrcimgs'; osrcimgs.name = 'Original Images'; osrcimgs.filter = 'image'; osrcimgs.ufilter = '.*'; osrcimgs.num = [2 Inf]; % --------------------------------------------------------------------- % msrcimgs Weighted Mean Images % --------------------------------------------------------------------- msrcimgs = cfg_files; msrcimgs.tag = 'msrcimgs'; msrcimgs.name = 'Weighted Mean Images'; msrcimgs.filter = 'image'; msrcimgs.ufilter = '.*'; msrcimgs.num = [2 Inf]; % --------------------------------------------------------------------- % ssrcimgs Weighted Mean Images % --------------------------------------------------------------------- ssrcimgs = cfg_files; ssrcimgs.tag = 'ssrcimgs'; ssrcimgs.name = 'Weighted Standard Deviation Images'; ssrcimgs.filter = 'image'; ssrcimgs.ufilter = '.*'; ssrcimgs.num = [2 Inf]; % --------------------------------------------------------------------- % summary Difference Summary % --------------------------------------------------------------------- summary = cfg_menu; summary.tag = 'summary'; summary.name = 'Difference Summary'; summary.labels = { 'Sum standard Differences' '#vox > Standard Difference Threshold'; 'Sum squared Differences' 'Sum percent Differences' '#vox > Percent Difference Threshold'; }; summary.values = {5; 4; 3; 2; 1}; summary.def = @(val)dti_dw_wmean_review('defaults','summaryopts.summary',val{:}); % --------------------------------------------------------------------- % mapping Intensity Mapping % --------------------------------------------------------------------- mapping = cfg_menu; mapping.tag = 'mapping'; mapping.name = 'Intensity Mapping'; mapping.labels = { 'Linear' 'Log' }; mapping.values = {2; 1}; mapping.def = @(val)dti_dw_wmean_review('defaults','summaryopts.mapping',val{:}); % --------------------------------------------------------------------- % grouping Image Grouping % --------------------------------------------------------------------- grouping = cfg_menu; grouping.tag = 'grouping'; grouping.name = 'Image Grouping'; grouping.labels = { 'All Data' 'Per b-Value' 'Per Image' }; grouping.values = {3; 2; 1}; grouping.def = @(val)dti_dw_wmean_review('defaults','summaryopts.grouping',val{:}); % --------------------------------------------------------------------- % summaryopts Summary Display Options % --------------------------------------------------------------------- summaryopts = cfg_branch; summaryopts.tag = 'summaryopts'; summaryopts.name = 'Summary Display Options'; summaryopts.val = {summary mapping grouping}; % --------------------------------------------------------------------- % pthresh Percent Difference Threshold % --------------------------------------------------------------------- pthresh = cfg_entry; pthresh.tag = 'pthresh'; pthresh.name = 'Percent Difference Threshold'; pthresh.strtype = 'r'; pthresh.num = [1 1]; pthresh.def = @(val)dti_dw_wmean_review('defaults','threshopts.pthresh',val{:}); % --------------------------------------------------------------------- % sdthresh Standard Difference Threshold % --------------------------------------------------------------------- sdthresh = cfg_entry; sdthresh.tag = 'sdthresh'; sdthresh.name = 'Standard Difference Threshold'; sdthresh.strtype = 'r'; sdthresh.num = [1 1]; sdthresh.def = @(val)dti_dw_wmean_review('defaults','threshopts.sdthresh',val{:}); % --------------------------------------------------------------------- % threshopts Threshold Options % --------------------------------------------------------------------- threshopts = cfg_branch; threshopts.tag = 'threshopts'; threshopts.name = 'Threshold Options'; threshopts.val = {pthresh sdthresh}; % --------------------------------------------------------------------- % dw_wmean_review Review Weighted Means and Variances % --------------------------------------------------------------------- dw_wmean_review = cfg_exbranch; dw_wmean_review.tag = 'dw_wmean_review'; dw_wmean_review.name = 'Review Weighted Means and Variances'; dw_wmean_review.val = {osrcimgs msrcimgs ssrcimgs summaryopts threshopts}; dw_wmean_review.help = {'Review Weighted Means and Variances.'}; dw_wmean_review.prog = @(job)dti_dw_wmean_review('run',job); % --------------------------------------------------------------------- % srcimgs Source Images % --------------------------------------------------------------------- srcimgs = cfg_files; srcimgs.tag = 'srcimgs'; srcimgs.name = 'Source Images'; srcimgs.help = {'The source images (one or more).'}; srcimgs.filter = 'image'; srcimgs.ufilter = '.*'; srcimgs.num = [1 Inf]; % --------------------------------------------------------------------- % b0corr Motion correction on b0 images % --------------------------------------------------------------------- b0corr = cfg_menu; b0corr.tag = 'b0corr'; b0corr.name = 'Motion correction on b0 images'; b0corr.help = {''}; b0corr.labels = { 'None' 'Stepwise' 'Linear interpolation (last stepwise)' 'Linear interpolation (last linear)' }'; b0corr.values = {0 1 2 3}; % --------------------------------------------------------------------- % b1corr Motion correction on all (b0+DW) images % --------------------------------------------------------------------- b1corr = cfg_menu; b1corr.tag = 'b1corr'; b1corr.name = 'Motion correction on all (b0+DW) images'; b1corr.help = {''}; b1corr.labels = { 'None' 'Realign xy' 'Realign per dw separately' 'Realign xy & Coregister to mean' 'Full Realign & Coregister (rigid body) to mean' 'Full Realign & Coregister (full affine) to mean' 'Realign (rigid body) to weighted means' 'Realign (full affine) to weighted means' }'; b1corr.values = {0 1 2 3 4 5 6 7}; % --------------------------------------------------------------------- % dti_realign Realign DW image time series % --------------------------------------------------------------------- realign = cfg_exbranch; realign.tag = 'dti_realign'; realign.name = 'Realign DW image time series'; realign.val = {srcimgs b0corr b1corr }; realign.help = { 'Determine realignment parameters for diffusion weighted images' '' 'Motion correction of diffusion weighted images can not be done by simply using SPMs realignment procedure, because images with different diffusion weighting show different contrast and signal/noise ratio. This would violate the assumptions on which the realignment code is based.' 'In a repeated measurement scenario, the solution could be separate realignment of images with different diffusion weighting. However, this does not work well for high b values, and it does not work at all without repeated measurements. Without repeated measurements, it is recommended to insert additional b0 scans into your acquisition every 6-10 diffusion weighting directions.' 'Motion correction can then be performed on the b0 images and the parameters applied to the corresponding diffusion weighted images. Three different options for motion correction based on b0 images are available:' '/*\begin{description}*/' '/*\item[*/ Stepwise correction/*]*/' 'Movement parameters for a b0 image will be applied unchanged to all following diffusion weighted images up to the next b0 image.' '/*\item[*/ Linear correction/*]*/' 'For all but the diffusion weighting images following the last b0 image, motion parameters will be determined by linear interpolation between the two sets of motion parameters of b0 images. There are two possibilities for images in the last series:' '/*\begin{description}*/' '/*\item[*/ last stepwise/*]*/ Do a stepwise correction for the last images' '/*\item[*/ last linear/*]*/ Extrapolate motion parameters from difference between last b0 images. This option might be useful if there is a linear scanner drift that is larger than voluntary head movement.' '/*\end{description}*//*\end{description}*/' 'In addition (or alternatively, if no time series of b0 images exists), motion correction can be performed on diffusion weighted images:' '/*\begin{description}*/' '/*\item[*/ Realign xy/*]*/' 'The b1 images are realigned within xy plane.' '/*\item[*/ Coregister to mean/*]*/' 'From the realigned diffusion images a mean image is created. The b1 images are then coregistered to this mean image.' '/*\end{description}*/' 'The images itself are not resliced during this step, only position information in NIFTI headers is updated. If necessary, images can be resliced to the space of the 1st image by choosing "Realign->Reslice only" from standard SPM and selecting all images of all series together in the correct order. This step can be skipped, if images will be normalised before tensor estimation. Gradient directions need to be adjusted prior to running tensor estimation using dti_reorient_gradients.' '' 'Batch processing:' 'FORMAT dti_realign(bch)' '====== Input argument:' 'bch struct with fields' '/*\begin{description}*/' '/*\item[*/ .files/*]*/ cell array of image filenames. Images are classified as b0 or b1 by inspection of the diffusion information in userdata using dti_extract_dirs. /*\item[*/ .b0corr/*]*/ Motion correction on b0 images' '/*\item[*/ .b1corr/*]*/ Motion correction on b1 images' '/*\end{description}*/' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id$' }'; realign.prog = @dti_realign; realign.vout = @vout_dti_realign; % --------------------------------------------------------------------- % srcimgs Source Images % --------------------------------------------------------------------- srcimgs = cfg_files; srcimgs.tag = 'srcimgs'; srcimgs.name = 'Source Images'; srcimgs.help = {'Diffusion information will be read from these images.'}; srcimgs.filter = 'image'; srcimgs.ufilter = '.*'; srcimgs.num = [1 Inf]; % --------------------------------------------------------------------- % tgtimgs Target images % --------------------------------------------------------------------- tgtimgs = cfg_files; tgtimgs.tag = 'tgtimgs'; tgtimgs.name = 'Target images'; tgtimgs.help = {'Diffusion information will be copied to this images, applying motion correction and (optional) normalisation information to gradient directions.'}; tgtimgs.filter = 'image'; tgtimgs.ufilter = '.*'; tgtimgs.num = [1 Inf]; % --------------------------------------------------------------------- % snparams Normalisation parameters (optional) % --------------------------------------------------------------------- snparams = cfg_files; snparams.tag = 'snparams'; snparams.name = 'Normalisation parameters (optional)'; snparams.val = {''}; snparams.help = {'A file containing spatial normalisation parameters. Spatial transformations from normalisation will be read from this file.'}; snparams.filter = 'mat'; snparams.ufilter = '.*sn.*'; snparams.num = [0 1]; % --------------------------------------------------------------------- % rot Rotation % --------------------------------------------------------------------- rot = cfg_menu; rot.tag = 'rot'; rot.name = 'Rotation'; rot.help = {''}; rot.labels = { 'Yes' 'No' }'; rot.values{1} = double(1); rot.values{2} = double(0); % --------------------------------------------------------------------- % zoom Zoom % --------------------------------------------------------------------- zoom = cfg_menu; zoom.tag = 'zoom'; zoom.name = 'Zoom'; zoom.help = {''}; zoom.labels = { 'Sign of zooms' 'Sign and magnitude' 'No' }'; zoom.values{1} = double(1); zoom.values{2} = double(2); zoom.values{3} = double(0); % --------------------------------------------------------------------- % shear Shear % --------------------------------------------------------------------- shear = cfg_menu; shear.tag = 'shear'; shear.name = 'Shear'; shear.help = {''}; shear.labels = { 'Yes' 'No' }'; shear.values{1} = double(1); shear.values{2} = double(0); % --------------------------------------------------------------------- % useaff Affine Components for Reorientation % --------------------------------------------------------------------- useaff = cfg_branch; useaff.tag = 'useaff'; useaff.name = 'Affine Components for Reorientation'; useaff.val = {rot zoom shear }; useaff.help = {'Select which parts of an affine transformation to consider for reorientation.'}; % --------------------------------------------------------------------- % dti_reorient_gradient Copy and Reorient diffusion information % --------------------------------------------------------------------- reorient_gradient = cfg_exbranch; reorient_gradient.tag = 'dti_reorient_gradient'; reorient_gradient.name = 'Copy and Reorient diffusion information'; reorient_gradient.val = {srcimgs tgtimgs snparams useaff }; reorient_gradient.help = { 'Apply image reorientation information to diffusion gradients' '' 'This function needs to be called once after all image realignment, coregistration or normalisation steps have been performed, i.e. after the images have been resliced or written normalised. Without calling this function immediately after reslicing or normalisation, all diffusion information is lost. /*\textbf{*/This is a major change to the functionality of the toolbox compared to SPM2!/*}*/' 'It applies the rotations performed during realignment, coregistration and affine normalisation to the gradient direction vectors. This is done by comparing the original orientation information (saved in the images userdata by dti_init_dtidata) with the current image orientation.' 'After applying this correction a reset of DTI information will not be able to recover the initial gradient or orientation values, since the original orientation matrix will be lost.' '' 'Batch processing:' 'FORMAT dti_reorient_gradient(bch)' '======' 'Input argument' 'bch struct with fields:' '/*\begin{description}*/' '/*\item[*/ .srcimgs/*]*/ cell array of file names (usually the un-resliced, un-normalised images)' '/*\item[*/ .tgtimgs/*]*/ target images (can be the same files as srcimgs, but usually the resliced or normalised images).' '/*\item[*/ .snparams/*]*/ optional normalisation parameters file used to write the images normalised.' '/*\end{description}*/' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id: dti_reorient_gradient.m 464 2006-10-04 14:00:44Z volkmar $' }'; reorient_gradient.prog = @dti_reorient_gradient; reorient_gradient.vout = @vout_dti_reorient_gradient; reorient_gradient.check = @check_dti_reorient_gradient; % --------------------------------------------------------------------- % file0 B0 image % --------------------------------------------------------------------- file0 = cfg_files; file0.tag = 'file0'; file0.name = 'B0 image'; file0.help = {'Select the b0 image for ADC computation.'}; file0.filter = 'image'; file0.ufilter = '.*'; file0.num = [1 1]; % --------------------------------------------------------------------- % files1 DW image(s) % --------------------------------------------------------------------- files1 = cfg_files; files1.tag = 'files1'; files1.name = 'DW image(s)'; files1.help = {'Diffusion weighted images - one ADC image per DW image will be produced.'}; files1.filter = 'image'; files1.ufilter = '.*'; files1.num = [1 Inf]; % --------------------------------------------------------------------- % minS Minimum Signal Threshold % --------------------------------------------------------------------- minS = cfg_entry; minS.tag = 'minS'; minS.name = 'Minimum Signal Threshold'; minS.val{1} = double(1); minS.help = {'Logarithm of values below 1 will produce negative ADC results. Very low intensities are probably due to noise and should be masked out.'}; minS.strtype = 'e'; minS.num = [1 1]; % --------------------------------------------------------------------- % prefix Output Filename Prefix % --------------------------------------------------------------------- prefix = cfg_entry; prefix.tag = 'prefix'; prefix.name = 'Output Filename Prefix'; prefix.val = {'adc_'}; prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'}; prefix.strtype = 's'; prefix.num = [1 Inf]; % --------------------------------------------------------------------- % interp Interpolation % --------------------------------------------------------------------- interp = cfg_menu; interp.tag = 'interp'; interp.name = 'Interpolation'; interp.help = {''}; interp.labels = { 'Nearest neighbour' 'Trilinear' '2nd Degree b-Spline' '3rd Degree b-Spline' '4th Degree b-Spline' '5th Degree b-Spline' '6th Degree b-Spline' '7th Degree b-Spline' '2nd Degree Sinc' '3rd Degree Sinc' '4th Degree Sinc' '5th Degree Sinc' '6th Degree Sinc' '7th Degree Sinc' }'; interp.values{1} = double(0); interp.values{2} = double(1); interp.values{3} = double(2); interp.values{4} = double(3); interp.values{5} = double(4); interp.values{6} = double(5); interp.values{7} = double(6); interp.values{8} = double(7); interp.values{9} = double(-2); interp.values{10} = double(-3); interp.values{11} = double(-4); interp.values{12} = double(-5); interp.values{13} = double(-6); interp.values{14} = double(-7); % --------------------------------------------------------------------- % dti_adc Compute ADC Images % --------------------------------------------------------------------- adc = cfg_exbranch; adc.tag = 'dti_adc'; adc.name = 'Compute ADC Images'; adc.val = {file0 files1 minS prefix interp }; adc.help = { 'ADC computation' '' 'Computes ADC maps from 2 b values (lower b value is assumed to be zero). More than one image can be entered for the high b value, in this case it is necessary to specify one b value per image. If available, this b value will be read from the userdata field of the image handle.' '' 'Output images are saved as adc_<FILENAME_OF_B1_IMAGE>.img .' '' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id$' }'; adc.prog = @dti_adc; adc.vout = @vout_dti_adc; % --------------------------------------------------------------------- % files ADC images % --------------------------------------------------------------------- files = cfg_files; files.tag = 'files'; files.name = 'ADC images'; files.help = {'The source images (one or more).'}; files.filter = 'image'; files.ufilter = '.*'; files.num = [6 6]; % --------------------------------------------------------------------- % interp Interpolation % --------------------------------------------------------------------- interp = cfg_menu; interp.tag = 'interp'; interp.name = 'Interpolation'; interp.help = {''}; interp.labels = { 'Nearest neighbour' 'Trilinear' '2nd Degree b-Spline' '3rd Degree b-Spline' '4th Degree b-Spline' '5th Degree b-Spline' '6th Degree b-Spline' '7th Degree b-Spline' '2nd Degree Sinc' '3rd Degree Sinc' '4th Degree Sinc' '5th Degree Sinc' '6th Degree Sinc' '7th Degree Sinc' }'; interp.values{1} = double(0); interp.values{2} = double(1); interp.values{3} = double(2); interp.values{4} = double(3); interp.values{5} = double(4); interp.values{6} = double(5); interp.values{7} = double(6); interp.values{8} = double(7); interp.values{9} = double(-2); interp.values{10} = double(-3); interp.values{11} = double(-4); interp.values{12} = double(-5); interp.values{13} = double(-6); interp.values{14} = double(-7); % --------------------------------------------------------------------- % dti_dt_adc Compute Tensor from 6 ADC Images % --------------------------------------------------------------------- dt_adc = cfg_exbranch; dt_adc.tag = 'dti_dt_adc'; dt_adc.name = 'Compute Tensor from 6 ADC Images'; dt_adc.val = {files interp }; dt_adc.help = { 'Compute diffusion tensor from 6 ADC images' '' 'This function computes diffusion tensors of order 2 from exactly 6 ADC images that have been acquired with different diffusion weightings. If your dataset consists of more diffusion weightings or repeated measurements with 6 diffusion weightings, use the regression method to compute the tensors from the original diffusion weighted images.' '' 'This routine tries to figure out gradient direction from userdata field of the ADC images. This may fail if' '/*\begin{itemize}*/' '/*\item*/ there is no userdata: in this case, the following direction scheme is assumed:' '/*\begin{tabular}{c|ccccccc}*/' '/*&*/ b0 /*&*/ im1 /*&*/ im2 /*&*/ im3 /*&*/ im4 /*&*/ im5 /*&*/ im6 /*\\*/' '/*\hline*/' 'x /*&*/ 0 /*&*/ 0 /*&*/ 0 /*&*/ 1 /*&*/ 1 /*&*/ 1 /*&*/ 1 /*\\*/' 'y /*&*/ 0 /*&*/ 1 /*&*/ 1 /*&*/ 0 /*&*/ 0 /*&*/ 1 /*&*/ -1 /*\\*/' 'z /*&*/ 0 /*&*/ 1 /*&*/ -1 /*&*/ 1 /*&*/ -1 /*&*/ 0 /*&*/ 0' '/*\end{tabular}*/' '/*\item*/ there are some identical directions in userdata: This happens with some SIEMENS standard sequences on Symphony/Sonata/Trio systems. In that case, a warning is issued and SIEMENS standard values are used.' '/*\end{itemize}*/' '/* The algorithm used in this routine is based on \cite{basser98}, */ /* although the direction scheme actually used depends on the applied */ /* diffusion imaging sequence.*/' '' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id$' }'; dt_adc.prog = @dti_dt_adc; dt_adc.vfiles = @vfiles_dti_dt_adc; % --------------------------------------------------------------------- % srcimgs DW images % --------------------------------------------------------------------- srcimgs = cfg_files; srcimgs.tag = 'srcimgs'; srcimgs.name = 'DW images'; srcimgs.help = {'Enter all diffusion weighted images (all replicated measurements, all diffusion weightings) and b0 images at once.'}; srcimgs.filter = 'image'; srcimgs.ufilter = '.*'; srcimgs.num = [8 Inf]; % --------------------------------------------------------------------- % srcscaling Data scaling % --------------------------------------------------------------------- srcscaling = cfg_menu; srcscaling.tag = 'srcscaling'; srcscaling.name = 'Data scaling'; srcscaling.labels = {'Raw DW data';'Ln(DW data)'}; srcscaling.values = {'raw';'log'}; srcscaling.val = {'raw'}; srcscaling.help = {'Specify whether input data are raw or log scaled.'}; % --------------------------------------------------------------------- % erriid Equal errors, equal variance % --------------------------------------------------------------------- erriid = cfg_const; erriid.tag = 'erriid'; erriid.name = 'Equal errors, equal variance'; erriid.val{1} = double(1); erriid.help = {''}; % --------------------------------------------------------------------- % ltol B value tolerance % --------------------------------------------------------------------- ltol = cfg_entry; ltol.tag = 'ltol'; ltol.name = 'B value tolerance'; ltol.help = {'B values will be divided by this tolerance value and then rounded. Any b values that are still different after rounding, will be treated as different.'}; ltol.strtype = 'e'; ltol.num = [1 1]; % --------------------------------------------------------------------- % dtol Gradient direction tolerance % --------------------------------------------------------------------- dtol = cfg_entry; dtol.tag = 'dtol'; dtol.name = 'Gradient direction tolerance'; dtol.help = { 'Determines which gradient vectors describe similar directions. Colinearity will be computed as the scalar product between two unit-length gradient vectors.' '' 'Two gradient vectors are treated as similar, if their scalar product is larger than the tolerance value. This means a tolerance value of -1 will treat all directions as similar, whereas a positive value between 0 and 1 will distinguish between different directions.' }'; dtol.strtype = 'e'; dtol.num = [1 1]; % --------------------------------------------------------------------- % sep Distinguish antiparallel gradient directions % --------------------------------------------------------------------- sep = cfg_menu; sep.tag = 'sep'; sep.name = 'Distinguish antiparallel gradient directions'; sep.help = { 'In theory, antiparallel gradient directions should be equivalent when measuring diffusion. However, due to possible scanner effects this might be not true.' '' 'If this entry is set to ''Yes'' then antiparallel gradient directions will be treated as different from each other.' }'; sep.labels = { 'Yes' 'No' }'; sep.values{1} = double(1); sep.values{2} = double(0); % --------------------------------------------------------------------- % errauto Auto-determined by b-values % --------------------------------------------------------------------- errauto = cfg_branch; errauto.tag = 'errauto'; errauto.name = 'Auto-determined by b-values'; errauto.val = {ltol dtol sep }; errauto.help = { 'Automatic determination of error variance components from diffusion weighting information. This is the recommended method.' '' 'To discriminate between b values, but not directions, set direction tolerance to 0 and do not distinguish between antiparallel directions.' }'; % --------------------------------------------------------------------- % inorder Input Order % --------------------------------------------------------------------- inorder = cfg_menu; inorder.tag = 'inorder'; inorder.name = 'Input Order'; inorder.help = {'The input order determines the way in which error covariance components are specified: the assumption is that error covariances are equal over similar diffusion weightings. If images are given replication by replication, the ordering of diffusion weighting should be the same for each replication.'}; inorder.labels = { 'repl1 all b | repl2 all b ... replX all b' 'b1 all repl | b2 all repl ... bX all repl' }'; inorder.values = { 'repl' 'bval' }'; % --------------------------------------------------------------------- % ndw # of different diffusion weightings % --------------------------------------------------------------------- ndw = cfg_entry; ndw.tag = 'ndw'; ndw.name = '# of different diffusion weightings'; ndw.help = {'Give the number of different diffusion weightings. The product of #dw and #rep must match the number of your images.'}; ndw.strtype = 'n'; ndw.num = [1 1]; % --------------------------------------------------------------------- % nrep # of repetitions % --------------------------------------------------------------------- nrep = cfg_entry; nrep.tag = 'nrep'; nrep.name = '# of repetitions'; nrep.help = {'Give the number of repeated measurements. The product of #dw and #rep must match the number of your images.'}; nrep.strtype = 'n'; nrep.num = [1 1]; % --------------------------------------------------------------------- % errspec User specified % --------------------------------------------------------------------- errspec = cfg_branch; errspec.tag = 'errspec'; errspec.name = 'User specified'; errspec.val = {inorder ndw nrep }; errspec.help = {'Specify error variance components for repeated measurements with similar diffusion weighting in each repetition.'}; % --------------------------------------------------------------------- % errorvar Error variance options % --------------------------------------------------------------------- errorvar = cfg_choice; errorvar.tag = 'errorvar'; errorvar.name = 'Error variance options'; errorvar.help = {'Diffusion weighted images may have different error variances depending on diffusion gradient strength and directions. To correct for this, one can model error variances based on diffusion information or measurement order.'}; errorvar.values = {erriid errauto errspec }; % --------------------------------------------------------------------- % dtorder Tensor order % --------------------------------------------------------------------- dtorder = cfg_entry; dtorder.tag = 'dtorder'; dtorder.name = 'Tensor order'; dtorder.help = {'Enter an even number (default 2). This determines the order of your diffusion tensors. Higher order tensors can be estimated only from data with many different diffusion weighting directions. See the referenced literature/*\cite{Orszalan2003}*/ for details.'}; dtorder.strtype = 'n'; dtorder.num = [1 1]; % --------------------------------------------------------------------- % maskimg Mask Image (optional) % --------------------------------------------------------------------- maskimg = cfg_files; maskimg.tag = 'maskimg'; maskimg.name = 'Mask Image (optional)'; maskimg.val = {{''}}; maskimg.help = { 'Specify an image for masking your data. Only voxels where this image has non-zero intensity will be processed.' '' 'This image is optional. If not specified, the whole volume will be analysed.' '' 'For a proper estimation of error covariances, non-brain voxels should be excluded by an explicit mask. This could be an mask based on an intensity threshold of your b0 images or a mask based on grey and white matter segments from SPM segmentation. Only voxels, with non-zero mask values will be included into analysis.' }'; maskimg.filter = 'image'; maskimg.ufilter = '.*'; maskimg.num = [0 1]; % --------------------------------------------------------------------- % swd Output directory % --------------------------------------------------------------------- swd = cfg_files; swd.tag = 'swd'; swd.name = 'Output directory'; swd.help = {'Files produced by this function will be written into this output directory'}; swd.filter = 'dir'; swd.ufilter = '.*'; swd.num = [1 1]; % --------------------------------------------------------------------- % spatsm Estimate spatial smoothness % --------------------------------------------------------------------- spatsm = cfg_menu; spatsm.tag = 'spatsm'; spatsm.name = 'Estimate spatial smoothness'; spatsm.help = {'Spatial smoothness estimates are not needed if one is only interested in the tensor values itself. Estimation can be speeded up by forcing SPM not to compute it.'}; spatsm.labels = { 'Yes' 'No' }'; spatsm.values{1} = double(1); spatsm.values{2} = double(0); % --------------------------------------------------------------------- % dti_dt_regress Compute Tensor (Multiple Regression) % --------------------------------------------------------------------- dt_regress = cfg_exbranch; dt_regress.tag = 'dti_dt_regress'; dt_regress.name = 'Compute Tensor (Multiple Regression)'; dt_regress.val = {srcimgs srcscaling errorvar dtorder maskimg swd spatsm }; dt_regress.help = { 'Tensor(regression)' '' 'Compute diffusion tensor components from at least 6 diffusion weighted images + 1 b0 image. Gradient directions and strength are read from the corresponding .mat files. The resulting B matrix is then given to spm_spm as design matrix for a multiple regression analysis.' '' 'If there are repeated measurements or one measurement, but different b value levels, then options for non-sphericity correction will be offered. The rationale behind this is the different amount of error variance contained in images with different diffusion weighting. If you want to take advantage of non-spericity correction, you should use an explicit mask to exclude any non-brain voxels from analysis, because the high noise level in non-brain-areas of diffusion weighted images will render the estimation of variance components invalid.' '' 'If there are more than 6 diffusion weighting directions in the data set, tensors of higher order can be estimated. This allows to model diffusivity profiles in voxels with e.g. fibre crossings more accurately than with order-2 tensors.' '' 'Output images are saved as D*_basename.img, where basename is derived from the original filenames. Directionality components are encoded by ''x'', ''y'', ''z'' letters in the filename.' '' '/* The algorithm used to determine the design matrix for SPM stats in this */ /* routine is based on \cite{basser94} and is developed for the general */ /* order-n tensors in \cite{Orszalan2003}, although the direction scheme */ /* actually used depends on the applied diffusion imaging sequence. */' '' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id$' }'; dt_regress.prog = @dti_dt_regress; dt_regress.vout = @vout_dti_dt_regress; % --------------------------------------------------------------------- % dtimg Diffusion Tensor Images % --------------------------------------------------------------------- dtimg = cfg_files; dtimg.tag = 'dtimg'; dtimg.name = 'Diffusion Tensor Images'; dtimg.help = {'Select images containing diffusion tensor data. If they are not computed using this toolbox, they need to be named according to the naming conventions of the toolbox or have at least an similar alphabetical order.'}; dtimg.filter = 'image'; dtimg.ufilter = '^D([x-z][x-z])*_.*'; dtimg.num = [6 Inf]; % --------------------------------------------------------------------- % snparams Normalisation parameters % --------------------------------------------------------------------- snparams = cfg_files; snparams.tag = 'snparams'; snparams.name = 'Normalisation parameters'; snparams.help = {'A file containing spatial normalisation parameters. Spatial transformations from normalisation will be read from this file.'}; snparams.filter = 'mat'; snparams.ufilter = '.*sn.*'; snparams.num = [1 1]; % --------------------------------------------------------------------- % dti_warp_tensors Warp tensors % --------------------------------------------------------------------- warp_tensors = cfg_exbranch; warp_tensors.tag = 'dti_warp_tensors'; warp_tensors.name = 'Warp tensors'; warp_tensors.val = {dtimg snparams }; warp_tensors.help = { 'Apply image reorientation information to diffusion gradients' '' 'Batch processing:' 'FORMAT dti_warp_tensors(bch)' '======' 'Input argument' 'bch struct with fields:' '/*\begin{description}*/' '/*\item[*/ .srcimgs/*]*/ cell array of file names (tensor images' 'computed from normalised images)' '/*\item[*/ .snparams/*]*/ optional normalisation parameters file used to write the images normalised.' '/*\end{description}*/' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id: dti_warp_tensors.m 464 2006-10-04 14:00:44Z volkmar $' }'; warp_tensors.prog = @dti_warp_tensors; % --------------------------------------------------------------------- % dtimg Diffusion Tensor Images % --------------------------------------------------------------------- dtimg = cfg_files; dtimg.tag = 'dtimg'; dtimg.name = 'Diffusion Tensor Images'; dtimg.help = {'Select images containing diffusion tensor data. If they are not computed using this toolbox, they need to be named according to the naming conventions of the toolbox or have at least an similar alphabetical order.'}; dtimg.filter = 'image'; dtimg.ufilter = '^D([x-z][x-z])*_.*'; dtimg.num = [6 Inf]; % --------------------------------------------------------------------- % dteigopts Decomposition output % --------------------------------------------------------------------- dteigopts = cfg_menu; dteigopts.tag = 'dteigopts'; dteigopts.name = 'Decomposition output'; dteigopts.help = {''}; dteigopts.labels = { 'Eigenvectors and Eigenvalues' 'Euler angles and Eigenvalues' 'Eigenvalues only' 'Euler angles only' 'All' }'; dteigopts.values = { 'vl' 'al' 'l' 'a' 'alv' }'; % --------------------------------------------------------------------- % dti_eig Tensor decomposition % --------------------------------------------------------------------- dtieig = cfg_exbranch; dtieig.tag = 'dti_eig'; dtieig.name = 'Tensor decomposition'; dtieig.val = {dtimg dteigopts }; dtieig.help = { 'Tensor decomposition' '' 'Computes eigenvector components, eigenvalues and euler angles (pitch, roll, yaw convention) from diffusion tensor data.' 'Output image naming convention' '/*\begin{itemize}*/' '/*\item*/ evec1[x,y,z]*IMAGE - components of 1st eigenvector' '/*\item*/ evec2[x,y,z]*IMAGE - components of 2nd eigenvector' '/*\item*/ evec3[x,y,z]*IMAGE - components of 3rd eigenvector' '/*\item*/ eval[1,2,3]*IMAGE - eigenvalues' '/*\item*/ euler[1,2,3]*IMAGE - euler angles' '/*\end{itemize}*/' 'Batch processing' 'FORMAT res = dti_eig(bch)' '======' '/*\begin{itemize}*/' '/*\item*/ Input argument:' 'bch struct with fields' '/*\begin{description}*/' '/*\item[*/ .dtimg/*]*/ cell array of filenames of tensor images /*\item[*/ .data/*]*/ real 6-by-Xdim-by-Ydim-by-Zdim-array of tensor elements' '/*\item[*/ .dteigopts/*]*/ results wanted, a string array containing a combination of /*\begin{description}*/' '/*\item[*/ v/*]*/ (eigenvectors)' '/*\item[*/ l/*]*/ (eigenvalues)' '/*\item[*/ a/*]*/ (euler angles)/*\end{description}*/' '/*\end{description}*/' 'Only one of ''dtimg'' or ''data'' need to be specified. If ''data'' is provided, no files will be read and outputs will be given as arrays in the returned ''res'' structure. Input order for the tensor elements is alphabetical.' '/*\item*/ Output argument (only defined if bch has a ''data'' field):' 'res struct with fields' '/*\begin{description}*/' '/*\item[*/ .evec/*]*/ eigenvectors' '/*\item[*/ .eval/*]*/ eigenvalues' '/*\item[*/ .euler/*]*/ euler angles' '/*\end{description}*/' 'The presence of each field depends on the option specified in the batch.' '/*\end{itemize}*/' '' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id$' }'; dtieig.prog = @dti_eig; dtieig.vout = @vout_dti_eig; % --------------------------------------------------------------------- % dtimg Diffusion Tensor Images % --------------------------------------------------------------------- dtimg = cfg_files; dtimg.tag = 'dtimg'; dtimg.name = 'Diffusion Tensor Images'; dtimg.help = {'Select images containing diffusion tensor data. If they are not computed using this toolbox, they need to be named according to the naming conventions of the toolbox or have at least an similar alphabetical order.'}; dtimg.filter = 'image'; dtimg.ufilter = '^D([x-z][x-z])*_.*'; dtimg.num = [6 Inf]; % --------------------------------------------------------------------- % option Compute indices % --------------------------------------------------------------------- option = cfg_menu; option.tag = 'option'; option.name = 'Compute indices'; option.help = {''}; option.labels = { 'Fractional Anisotropy' 'Variance Anisotropy' 'Average Diffusivity' 'Fractional+Variance Anisotropy' 'All' }'; option.values = { 'f' 'v' 'd' 'fv' 'fvd' }'; % --------------------------------------------------------------------- % dti_indices Tensor Indices % --------------------------------------------------------------------- indices = cfg_exbranch; indices.tag = 'dti_indices'; indices.name = 'Tensor Indices'; indices.val = {dtimg option }; indices.help = { 'Compute various invariants of diffusion tensor' '' 'Batch processing' 'FORMAT res = dti_indices(bch)' '======' '/*\begin{itemize}*/' '/*\item*/ Input argument:' 'bch struct containing fields' '/*\begin{description}*/' '/*\item[*/ .dtimg/*]*/ cell array of filenames of DT images' '/*\item[*/ .data/*]*/ Xdim-by-Ydim-by-Zdim-by-6 array of tensors' 'Only one of .files and .data need to be given.' '/*\item[*/ .option/*]*/ character array with a combination of' '/*\begin{description}*/' '/*\item[*/ f/*]*/ Fractional Anisotropy' '/*\item[*/ v/*]*/ Variance Anisotropy. In the literature, this is sometimes referred to as relative anisotropy, multiplication by a scaling factor of 1/sqrt(2) yields variance anisotropy.' '/*\item[*/ d/*]*/ Average Diffusivity' '/*\end{description}\end{description}*/' '/*\item*/ Output argument:' 'res struct containing fields (if requested)' '/*\begin{description}*/' '/*\item[*/ .fa/*]*/ FA output' '/*\item[*/ .va/*]*/ VA output' '/*\item[*/ .ad/*]*/ AD output' '/*\end{description}*/' 'where output is a filename if input is in files and a' 'Xdim-by-Ydim-by-Zdim array if input is a data array.' '/*\end{itemize}*/' '/* The algorithms used in this routine are based on \cite{basserNMR95}.*/' '' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id$' }'; indices.prog = @dti_indices; indices.vout = @vout_dti_indices; % --------------------------------------------------------------------- % limg Eigenvalue Images % --------------------------------------------------------------------- limg = cfg_files; limg.tag = 'limg'; limg.name = 'Eigenvalue Images'; limg.help = {''}; limg.filter = 'image'; limg.ufilter = '^(eva)?l[1-3].*'; limg.num = [3 3]; % --------------------------------------------------------------------- % dti_saliencies Salient Features % --------------------------------------------------------------------- saliencies = cfg_exbranch; saliencies.tag = 'dti_saliencies'; saliencies.name = 'Salient Features'; saliencies.val = {limg }; saliencies.help = { 'Salient features' '' 'Computes salient features (curve-ness, plane-ness and sphere-ness) from eigenvalue data:' '/*\begin{itemize}*/' '/*\item*/ sc*IMAGE curve-ness (l1-l2)/l1' '/*\item*/ sp*IMAGE plane-ness (l2-l3)/l1' '/*\item*/ ss*IMAGE sphere-ness l3/l1' '/*\end{itemize}*/' 'These salient features are described in computer vision literature/*\cite{medioni00}*/.' '' 'Batch processing' 'FORMAT res = dti_saliencies(bch)' '======' '/*\begin{itemize}*/' '/*\item*/ Input argument:' 'bch struct containing fields' '/*\begin{description}*/' '/*\item[*/ .limg/*]*/ cell array of image filenames of eigenvalue images' '/*\item[*/ .data/*]*/ alternatively, data as 3-by-xdim-by-ydim-by-zdim array.' '/*\end{description}*/' '/*\item*/ Output arguments:' 'res struct with fields .sc, .sp, .ss. These fields contain filenames, if input is from files, otherwise they contain the computed saliency maps.' '/*\end{itemize}*/' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id: dti_saliencies.m 435 2006-03-02 16:35:11Z glauche $' }'; saliencies.prog = @dti_saliencies; saliencies.vout = @vout_dti_saliencies; % --------------------------------------------------------------------- % srcimgs Source Images % --------------------------------------------------------------------- srcimgs = cfg_files; srcimgs.tag = 'srcimgs'; srcimgs.name = 'Source Images'; srcimgs.help = {'The source images (one or more).'}; srcimgs.filter = 'image'; srcimgs.ufilter = '.*'; srcimgs.num = [1 Inf]; % --------------------------------------------------------------------- % option Information to display % --------------------------------------------------------------------- option = cfg_menu; option.tag = 'option'; option.name = 'Information to display'; option.help = {''}; option.labels = { 'Gradient vectors' 'Direction distribution' 'Both' }'; option.values = { 'v' 'd' 'vd' }'; % --------------------------------------------------------------------- % axbgcol Axis background colour % --------------------------------------------------------------------- axbgcol = cfg_entry; axbgcol.tag = 'axbgcol'; axbgcol.name = 'Axis background colour'; axbgcol.help = {''}; axbgcol.strtype = 'e'; axbgcol.num = [1 3]; % --------------------------------------------------------------------- % fgbgcol Figure background colour % --------------------------------------------------------------------- fgbgcol = cfg_entry; fgbgcol.tag = 'fgbgcol'; fgbgcol.name = 'Figure background colour'; fgbgcol.help = {''}; fgbgcol.strtype = 'e'; fgbgcol.num = [1 3]; % --------------------------------------------------------------------- % res Sphere resolution % --------------------------------------------------------------------- res = cfg_entry; res.tag = 'res'; res.name = 'Sphere resolution'; res.help = {'Resolution of the unit grid on which the sphere will be created. This grid will have the resolution [-1:res:1] in x,y,z directions.'}; res.strtype = 'e'; res.num = [1 1]; % --------------------------------------------------------------------- % dti_disp_grad Display gradient directions % --------------------------------------------------------------------- disp_grad = cfg_exbranch; disp_grad.tag = 'dti_disp_grad'; disp_grad.name = 'Display gradient directions'; disp_grad.val = {srcimgs option axbgcol fgbgcol res }; disp_grad.help = { 'Visualise gradient direction vectors' '' 'Visualise a set of gradient direction vectors. This is useful to compare gradient directions between measurements which may differ due to changes in measurement protocols, motion correction etc.' '' 'Batch processing:' 'FORMAT res=dti_disp_grad(bch)' '======' '/*\begin{itemize}*/' '/*\item*/ Input argument:' 'bch struct with fields' '/*\begin{description}*/' '/*\item[*/ .srcimgs/*]*/ cell array of file names to get diffusion information' '/*\item[*/ .option/*]*/ one or both of /*\begin{description}*/' '/*\item[*/ v/*]*/ displays a vector for each direction, b value is encoded as vector length' '/*\item[*/ d/*]*/ displays direction density colour coded on a unit sphere' '/*\end{description}*/' '/*\item[*/ .axbgcol, .fgbgcol/*]*/ axis and figure background colours' '/*\item[*/ .res/*]*/ sphere resolution' '/*\end{description}*/' '/*\item*/ Output argument:' 'res struct with fields' '/*\begin{description}*/' '/*\item[*/ .vf/*]*/ figure handle for vector plot' '/*\item[*/ .vax/*]*/ axis handle for vector plot' '/*\item[*/ .l/*]*/ line handles' '/*\item[*/ .df/*]*/ figure handle for direction plot' '/*\item[*/ .dax/*]*/ axis handle for direction plot' '/*\item[*/ .s/*]*/ surface handle for sphere' '/*\item[*/ .cb/*]*/ handle for colorbar' '/*\end{description}\end{itemize}*/' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id: dti_disp_grad.m 435 2006-03-02 16:35:11Z glauche $' }'; disp_grad.prog = @dti_disp_grad; % --------------------------------------------------------------------- % srcimgs Source Images % --------------------------------------------------------------------- srcimgs = cfg_files; srcimgs.tag = 'srcimgs'; srcimgs.name = 'Source Images'; srcimgs.help = {'The source images (one or more).'}; srcimgs.filter = 'image'; srcimgs.ufilter = '.*'; srcimgs.num = [1 Inf]; % --------------------------------------------------------------------- % refimage Image % --------------------------------------------------------------------- refimage = cfg_const; refimage.tag = 'refimage'; refimage.name = 'Image'; refimage.val{1} = double(1); refimage.help = {''}; % --------------------------------------------------------------------- % refscanner Scanner % --------------------------------------------------------------------- refscanner = cfg_const; refscanner.tag = 'refscanner'; refscanner.name = 'Scanner'; refscanner.val{1} = double(1); refscanner.help = {''}; % --------------------------------------------------------------------- % snparams Normalised % --------------------------------------------------------------------- snparams = cfg_files; snparams.tag = 'snparams'; snparams.name = 'Normalised'; snparams.val = {''}; snparams.help = {'A file containing spatial normalisation parameters. Spatial transformations from normalisation will be read from this file.'}; snparams.filter = 'mat'; snparams.ufilter = '.*sn.*'; snparams.num = [1 1]; % --------------------------------------------------------------------- % ref Reference coordinate system % --------------------------------------------------------------------- ref = cfg_choice; ref.tag = 'ref'; ref.name = 'Reference coordinate system'; ref.help = {''}; ref.values = {refimage refscanner snparams }; % --------------------------------------------------------------------- % saveinf Save gradient information to .txt file % --------------------------------------------------------------------- saveinf = cfg_menu; saveinf.tag = 'saveinf'; saveinf.name = 'Save gradient information to .txt file'; saveinf.help = {''}; saveinf.labels = { 'Yes' 'No' }'; saveinf.values{1} = double(1); saveinf.values{2} = double(0); % --------------------------------------------------------------------- % sep Distinguish antiparallel gradient directions % --------------------------------------------------------------------- sep = cfg_menu; sep.tag = 'sep'; sep.name = 'Distinguish antiparallel gradient directions'; sep.help = { 'In theory, antiparallel gradient directions should be equivalent when measuring diffusion. However, due to possible scanner effects this might be not true.' '' 'If this entry is set to ''Yes'' then antiparallel gradient directions will be treated as different from each other.' }'; sep.labels = { 'Yes' 'No' }'; sep.values{1} = double(1); sep.values{2} = double(0); % --------------------------------------------------------------------- % ltol B value tolerance % --------------------------------------------------------------------- ltol = cfg_entry; ltol.tag = 'ltol'; ltol.name = 'B value tolerance'; ltol.help = {'B values will be divided by this tolerance value and then rounded. Any b values that are still different after rounding, will be treated as different.'}; ltol.strtype = 'e'; ltol.num = [1 1]; % --------------------------------------------------------------------- % dtol Gradient direction tolerance % --------------------------------------------------------------------- dtol = cfg_entry; dtol.tag = 'dtol'; dtol.name = 'Gradient direction tolerance'; dtol.help = { 'Determines which gradient vectors describe similar directions. Colinearity will be computed as the scalar product between two unit-length gradient vectors.' '' 'Two gradient vectors are treated as similar, if their scalar product is larger than the tolerance value. This means a tolerance value of -1 will treat all directions as similar, whereas a positive value between 0 and 1 will distinguish between different directions.' }'; dtol.strtype = 'e'; dtol.num = [1 1]; % --------------------------------------------------------------------- % dti_extract_dirs Extract DW information (gradients & dirs) % --------------------------------------------------------------------- extract_dirs = cfg_exbranch; extract_dirs.tag = 'dti_extract_dirs'; extract_dirs.name = 'Extract DW information (gradients & dirs)'; extract_dirs.val = {srcimgs ref saveinf sep ltol dtol }; extract_dirs.help = { 'Batch processing:' 'FORMAT res=dti_extract_dirs(bch)' '======' '/*\begin{itemize}*/' '/*\item*/ Input argument:' 'bch struct with fields' '/*\begin{description}*/' '/*\item[*/ .srcimgs/*]*/ cell array of file names' '/*\item[*/ .ref/*]*/ A struct with one field of ''image'', ''scanner'' or ''snparams''. Determines the reference system for extracted gradient information. The routine assumes that all images have the same orientation and applies the inverse rotation, zoom and shearing part of the affine transformation of the first image or the normalisation parameters to the gradient directions. If ''snparams'' is given, this needs to be a cellstring containing the name of the sn.mat file.' '/*\item[*/ .saveinf/*]*/ Save extracted b- and g-values to text files? (0 no, 1 yes)' '/*\item[*/ .sep/*]*/ separate antiparallel directions (0 no, 1 yes)' '/*\item[*/ .ltol/*]*/ b value tolerance to treat as identical - set this to the b value rounding error' '/*\item[*/ .dtol/*]*/ cosine between gradient vectors to treat directions as identical' '/*\end{description}*/' '/*\item*/ Output arguments:' 'res struct with fields' '/*\begin{description}*/' '/*\item[*/ .dirsel/*]*/ ndir-by-nscan logical array of flags that mark images with similar diffusion weighting - deprecated. One should use the result of unique([res.ubj, res.ugj],''rows'') instead.' '/*\item[*/ .b/*]*/ ndir-by-1 vector of distinct b values for bval/dir combinations /*\item[*/ .g/*]*/ ndir-by-3 array of distinct directions for bval/dir combinations' '/*\item[*/ .ub/*]*/ nb-by-1 vector of distinct b values over all directions' '/*\item[*/ .ug/*]*/ ndir-by-3 array of distinct directions over all bvals' '/*\item[*/ .allb/*]*/ nimg-by-1 vector of all b values' '/*\item[*/ .allg/*]*/ nimg-by-3 array of all directions' '/*\item[*/ .bfile/*]*/ name of text file with b-values' '/*\item[*/ .gfile/*]*/ name of text file with g-values' '/*\end{description}\end{itemize}*/' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id: dti_extract_dirs.m 437 2006-03-06 16:58:32Z glauche $' }'; extract_dirs.prog = @dti_extract_dirs; extract_dirs.vout = @vout_dti_extract_dirs; % --------------------------------------------------------------------- % dtimg Diffusion Tensor Images % --------------------------------------------------------------------- dtimg = cfg_files; dtimg.tag = 'dtimg'; dtimg.name = 'Diffusion Tensor Images'; dtimg.help = {'Select images containing diffusion tensor data. If they are not computed using this toolbox, they need to be named according to the naming conventions of the toolbox or have at least an similar alphabetical order.'}; dtimg.filter = 'image'; dtimg.ufilter = '^D([x-z][x-z])*_.*'; dtimg.num = [6 Inf]; % --------------------------------------------------------------------- % dtorder Tensor order % --------------------------------------------------------------------- dtorder = cfg_entry; dtorder.tag = 'dtorder'; dtorder.name = 'Tensor order'; dtorder.help = {'Enter an even number (default 2). This determines the order of your diffusion tensors. Higher order tensors can be estimated only from data with many different diffusion weighting directions. See the referenced literature/*\cite{Orszalan2003}*/ for details.'}; dtorder.strtype = 'n'; dtorder.num = [1 1]; % --------------------------------------------------------------------- % dti_hosvd Higher Order SVD % --------------------------------------------------------------------- dtihosvd = cfg_exbranch; dtihosvd.tag = 'dti_hosvd'; dtihosvd.name = 'Higher Order SVD'; dtihosvd.val = {dtimg dtorder }; dtihosvd.help = { 'Compute SVD for higher order tensors' '' 'Batch processing' 'FORMAT res = dti_hosvd(bch)' '======' '/*\begin{itemize}*/' '/*\item*/ Input argument:' 'bch struct with fields' '/*\begin{description}*/' '/*\item[*/ .data/*]*/ tensor elements in alphabetical index order (if data is given, then no files will be read or written)' '/*\item[*/ .dtimg/*]*/ cell array with file names of images' '/*\item[*/ .dtorder/*]*/ tensor order' '/*\end{description}*/' '/*\item*/ Output argument:' 'res struct with fields' '/*\begin{description}*/' '/*\item[*/ .S/*]*/ singular tensor (elements in alphabetical index order)' '/*\item[*/ .U/*]*/ cell array of singular matrices' '/*\end{description}\end{itemize}*/' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id: dti_hosvd.m 435 2006-03-02 16:35:11Z glauche $' }'; dtihosvd.prog = @dti_hosvd; dtihosvd.vout = @vout_dti_hosvd; % --------------------------------------------------------------------- % srcspm Source SPM.mat % --------------------------------------------------------------------- srcspm = cfg_files; srcspm.tag = 'srcspm'; srcspm.name = 'Source SPM.mat'; srcspm.help = {'Select SPM.mat from a previous analysis step.'}; srcspm.filter = 'mat'; srcspm.ufilter = '.*SPM.*\.mat'; srcspm.num = [1 1]; % --------------------------------------------------------------------- % prefix Output Filename Prefix % --------------------------------------------------------------------- prefix = cfg_entry; prefix.tag = 'prefix'; prefix.name = 'Output Filename Prefix'; prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'}; prefix.strtype = 's'; prefix.num = [1 Inf]; % --------------------------------------------------------------------- % dti_recalc Compute filtered/adjusted DW Images from Regression Model % --------------------------------------------------------------------- recalc = cfg_exbranch; recalc.tag = 'dti_recalc'; recalc.name = 'Compute filtered/adjusted DW Images from Regression Model'; recalc.val = {srcspm prefix }; recalc.help = { 'recalculate DTI input Data from given tensor and b-matrix data (i.e. adjusted data).' '' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id$' }'; recalc.prog = @dti_recalc; % --------------------------------------------------------------------- % data Coordinate points % --------------------------------------------------------------------- data = cfg_entry; data.tag = 'data'; data.name = 'Coordinate points'; data.help = {'A #lines-by-size(t,2) array of data points.'}; data.strtype = 'e'; data.num = [Inf Inf]; % --------------------------------------------------------------------- % a Line slope % --------------------------------------------------------------------- a = cfg_entry; a.tag = 'a'; a.name = 'Line slope'; a.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; a.strtype = 'e'; a.num = [Inf Inf]; % --------------------------------------------------------------------- % off Offset % --------------------------------------------------------------------- off = cfg_entry; off.tag = 'off'; off.name = 'Offset'; off.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; off.strtype = 'e'; off.num = [Inf Inf]; % --------------------------------------------------------------------- % linear Linear: f(t) = a*t + off % --------------------------------------------------------------------- linear = cfg_branch; linear.tag = 'linear'; linear.name = 'Linear: f(t) = a*t + off'; linear.val = {a off }; linear.help = {''}; % --------------------------------------------------------------------- % r Amplitude % --------------------------------------------------------------------- r = cfg_entry; r.tag = 'r'; r.name = 'Amplitude'; r.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; r.strtype = 'e'; r.num = [Inf Inf]; % --------------------------------------------------------------------- % f Frequency % --------------------------------------------------------------------- f = cfg_entry; f.tag = 'f'; f.name = 'Frequency'; f.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; f.strtype = 'e'; f.num = [Inf Inf]; % --------------------------------------------------------------------- % ph Phase % --------------------------------------------------------------------- ph = cfg_entry; ph.tag = 'ph'; ph.name = 'Phase'; ph.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; ph.strtype = 'e'; ph.num = [Inf Inf]; % --------------------------------------------------------------------- % off Offset % --------------------------------------------------------------------- off = cfg_entry; off.tag = 'off'; off.name = 'Offset'; off.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; off.strtype = 'e'; off.num = [Inf Inf]; % --------------------------------------------------------------------- % tanhp Tanh: f(t) = tanh(f*t + ph) + off % --------------------------------------------------------------------- tanhp = cfg_branch; tanhp.tag = 'tanhp'; tanhp.name = 'Tanh: f(t) = tanh(f*t + ph) + off'; tanhp.val = {r f ph off }; tanhp.help = {''}; % --------------------------------------------------------------------- % r Amplitude % --------------------------------------------------------------------- r = cfg_entry; r.tag = 'r'; r.name = 'Amplitude'; r.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; r.strtype = 'e'; r.num = [Inf Inf]; % --------------------------------------------------------------------- % f Frequency % --------------------------------------------------------------------- f = cfg_entry; f.tag = 'f'; f.name = 'Frequency'; f.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; f.strtype = 'e'; f.num = [Inf Inf]; % --------------------------------------------------------------------- % ph Phase % --------------------------------------------------------------------- ph = cfg_entry; ph.tag = 'ph'; ph.name = 'Phase'; ph.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; ph.strtype = 'e'; ph.num = [Inf Inf]; % --------------------------------------------------------------------- % off Offset % --------------------------------------------------------------------- off = cfg_entry; off.tag = 'off'; off.name = 'Offset'; off.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; off.strtype = 'e'; off.num = [Inf Inf]; % --------------------------------------------------------------------- % sinp Sin: f(t) = sin(f*t + ph) + off % --------------------------------------------------------------------- sinp = cfg_branch; sinp.tag = 'sinp'; sinp.name = 'Sin: f(t) = sin(f*t + ph) + off'; sinp.val = {r f ph off }; sinp.help = {''}; % --------------------------------------------------------------------- % fxfun Line function (X) % --------------------------------------------------------------------- fxfun = cfg_choice; fxfun.tag = 'fxfun'; fxfun.name = 'Line function (X)'; fxfun.help = {'Specification of fibers. Each fiber is parameterised by three functions x(t), y(t) and z(t). All combinations of x-, y- and z-line functions are computed.'}; fxfun.values = {data linear tanhp sinp }; % --------------------------------------------------------------------- % data Coordinate points % --------------------------------------------------------------------- data = cfg_entry; data.tag = 'data'; data.name = 'Coordinate points'; data.help = {'A #lines-by-size(t,2) array of data points.'}; data.strtype = 'e'; data.num = [Inf Inf]; % --------------------------------------------------------------------- % a Line slope % --------------------------------------------------------------------- a = cfg_entry; a.tag = 'a'; a.name = 'Line slope'; a.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; a.strtype = 'e'; a.num = [Inf Inf]; % --------------------------------------------------------------------- % off Offset % --------------------------------------------------------------------- off = cfg_entry; off.tag = 'off'; off.name = 'Offset'; off.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; off.strtype = 'e'; off.num = [Inf Inf]; % --------------------------------------------------------------------- % linear Linear: f(t) = a*t + off % --------------------------------------------------------------------- linear = cfg_branch; linear.tag = 'linear'; linear.name = 'Linear: f(t) = a*t + off'; linear.val = {a off }; linear.help = {''}; % --------------------------------------------------------------------- % r Amplitude % --------------------------------------------------------------------- r = cfg_entry; r.tag = 'r'; r.name = 'Amplitude'; r.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; r.strtype = 'e'; r.num = [Inf Inf]; % --------------------------------------------------------------------- % f Frequency % --------------------------------------------------------------------- f = cfg_entry; f.tag = 'f'; f.name = 'Frequency'; f.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; f.strtype = 'e'; f.num = [Inf Inf]; % --------------------------------------------------------------------- % ph Phase % --------------------------------------------------------------------- ph = cfg_entry; ph.tag = 'ph'; ph.name = 'Phase'; ph.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; ph.strtype = 'e'; ph.num = [Inf Inf]; % --------------------------------------------------------------------- % off Offset % --------------------------------------------------------------------- off = cfg_entry; off.tag = 'off'; off.name = 'Offset'; off.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; off.strtype = 'e'; off.num = [Inf Inf]; % --------------------------------------------------------------------- % tanhp Tanh: f(t) = tanh(f*t + ph) + off % --------------------------------------------------------------------- tanhp = cfg_branch; tanhp.tag = 'tanhp'; tanhp.name = 'Tanh: f(t) = tanh(f*t + ph) + off'; tanhp.val = {r f ph off }; tanhp.help = {''}; % --------------------------------------------------------------------- % r Amplitude % --------------------------------------------------------------------- r = cfg_entry; r.tag = 'r'; r.name = 'Amplitude'; r.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; r.strtype = 'e'; r.num = [Inf Inf]; % --------------------------------------------------------------------- % f Frequency % --------------------------------------------------------------------- f = cfg_entry; f.tag = 'f'; f.name = 'Frequency'; f.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; f.strtype = 'e'; f.num = [Inf Inf]; % --------------------------------------------------------------------- % ph Phase % --------------------------------------------------------------------- ph = cfg_entry; ph.tag = 'ph'; ph.name = 'Phase'; ph.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; ph.strtype = 'e'; ph.num = [Inf Inf]; % --------------------------------------------------------------------- % off Offset % --------------------------------------------------------------------- off = cfg_entry; off.tag = 'off'; off.name = 'Offset'; off.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; off.strtype = 'e'; off.num = [Inf Inf]; % --------------------------------------------------------------------- % sinp Sin: f(t) = sin(f*t + ph) + off % --------------------------------------------------------------------- sinp = cfg_branch; sinp.tag = 'sinp'; sinp.name = 'Sin: f(t) = sin(f*t + ph) + off'; sinp.val = {r f ph off }; sinp.help = {''}; % --------------------------------------------------------------------- % fyfun Line function (Y) % --------------------------------------------------------------------- fyfun = cfg_choice; fyfun.tag = 'fyfun'; fyfun.name = 'Line function (Y)'; fyfun.help = {'Specification of fibers. Each fiber is parameterised by three functions x(t), y(t) and z(t). All combinations of x-, y- and z-line functions are computed.'}; fyfun.values = {data linear tanhp sinp }; % --------------------------------------------------------------------- % data Coordinate points % --------------------------------------------------------------------- data = cfg_entry; data.tag = 'data'; data.name = 'Coordinate points'; data.help = {'A #lines-by-size(t,2) array of data points.'}; data.strtype = 'e'; data.num = [Inf Inf]; % --------------------------------------------------------------------- % a Line slope % --------------------------------------------------------------------- a = cfg_entry; a.tag = 'a'; a.name = 'Line slope'; a.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; a.strtype = 'e'; a.num = [Inf Inf]; % --------------------------------------------------------------------- % off Offset % --------------------------------------------------------------------- off = cfg_entry; off.tag = 'off'; off.name = 'Offset'; off.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; off.strtype = 'e'; off.num = [Inf Inf]; % --------------------------------------------------------------------- % linear Linear: f(t) = a*t + off % --------------------------------------------------------------------- linear = cfg_branch; linear.tag = 'linear'; linear.name = 'Linear: f(t) = a*t + off'; linear.val = {a off }; linear.help = {''}; % --------------------------------------------------------------------- % r Amplitude % --------------------------------------------------------------------- r = cfg_entry; r.tag = 'r'; r.name = 'Amplitude'; r.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; r.strtype = 'e'; r.num = [Inf Inf]; % --------------------------------------------------------------------- % f Frequency % --------------------------------------------------------------------- f = cfg_entry; f.tag = 'f'; f.name = 'Frequency'; f.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; f.strtype = 'e'; f.num = [Inf Inf]; % --------------------------------------------------------------------- % ph Phase % --------------------------------------------------------------------- ph = cfg_entry; ph.tag = 'ph'; ph.name = 'Phase'; ph.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; ph.strtype = 'e'; ph.num = [Inf Inf]; % --------------------------------------------------------------------- % off Offset % --------------------------------------------------------------------- off = cfg_entry; off.tag = 'off'; off.name = 'Offset'; off.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; off.strtype = 'e'; off.num = [Inf Inf]; % --------------------------------------------------------------------- % tanhp Tanh: f(t) = tanh(f*t + ph) + off % --------------------------------------------------------------------- tanhp = cfg_branch; tanhp.tag = 'tanhp'; tanhp.name = 'Tanh: f(t) = tanh(f*t + ph) + off'; tanhp.val = {r f ph off }; tanhp.help = {''}; % --------------------------------------------------------------------- % r Amplitude % --------------------------------------------------------------------- r = cfg_entry; r.tag = 'r'; r.name = 'Amplitude'; r.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; r.strtype = 'e'; r.num = [Inf Inf]; % --------------------------------------------------------------------- % f Frequency % --------------------------------------------------------------------- f = cfg_entry; f.tag = 'f'; f.name = 'Frequency'; f.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; f.strtype = 'e'; f.num = [Inf Inf]; % --------------------------------------------------------------------- % ph Phase % --------------------------------------------------------------------- ph = cfg_entry; ph.tag = 'ph'; ph.name = 'Phase'; ph.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; ph.strtype = 'e'; ph.num = [Inf Inf]; % --------------------------------------------------------------------- % off Offset % --------------------------------------------------------------------- off = cfg_entry; off.tag = 'off'; off.name = 'Offset'; off.help = { 'The interpretation of this parameter varies with its size. It can be' '1-by-1, 1-by-size(t,2): one line, with possibly changing parameter value over the line.' 'M-by-1, M-by-size(t,2): multiple lines with different settings of this parameter. All combinations of all parameters of the line function will be computed.' }'; off.strtype = 'e'; off.num = [Inf Inf]; % --------------------------------------------------------------------- % sinp Sin: f(t) = sin(f*t + ph) + off % --------------------------------------------------------------------- sinp = cfg_branch; sinp.tag = 'sinp'; sinp.name = 'Sin: f(t) = sin(f*t + ph) + off'; sinp.val = {r f ph off }; sinp.help = {''}; % --------------------------------------------------------------------- % fzfun Line function (Z) % --------------------------------------------------------------------- fzfun = cfg_choice; fzfun.tag = 'fzfun'; fzfun.name = 'Line function (Z)'; fzfun.help = {'Specification of fibers. Each fiber is parameterised by three functions x(t), y(t) and z(t). All combinations of x-, y- and z-line functions are computed.'}; fzfun.values = {data linear tanhp sinp }; % --------------------------------------------------------------------- % t Parametrisation points for line % --------------------------------------------------------------------- t = cfg_entry; t.tag = 't'; t.name = 'Parametrisation points for line'; t.help = {''}; t.strtype = 'e'; t.num = [1 Inf]; % --------------------------------------------------------------------- % iso Ratio of isotropic diffusion % --------------------------------------------------------------------- iso = cfg_entry; iso.tag = 'iso'; iso.name = 'Ratio of isotropic diffusion'; iso.help = {''}; iso.strtype = 'e'; iso.num = [1 1]; % --------------------------------------------------------------------- % fwhm Exponential decay of non-isotropic diffusion % --------------------------------------------------------------------- fwhm = cfg_entry; fwhm.tag = 'fwhm'; fwhm.name = 'Exponential decay of non-isotropic diffusion'; fwhm.help = {''}; fwhm.strtype = 'e'; fwhm.num = [1 1]; % --------------------------------------------------------------------- % D Diffusion coefficient % --------------------------------------------------------------------- D = cfg_entry; D.tag = 'D'; D.name = 'Diffusion coefficient'; D.help = {''}; D.strtype = 'e'; D.num = [1 1]; % --------------------------------------------------------------------- % lines Line specification % --------------------------------------------------------------------- lines = cfg_branch; lines.tag = 'lines'; lines.name = 'Line specification'; lines.val = {fxfun fyfun fzfun t iso fwhm D }; lines.help = {''}; % --------------------------------------------------------------------- % alllines Line specifications % --------------------------------------------------------------------- alllines = cfg_repeat; alllines.tag = 'alllines'; alllines.name = 'Line specifications'; alllines.help = {''}; alllines.values = {lines }; alllines.num = [1 Inf]; % --------------------------------------------------------------------- % prefix Output Filename Prefix % --------------------------------------------------------------------- prefix = cfg_entry; prefix.tag = 'prefix'; prefix.name = 'Output Filename Prefix'; prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'}; prefix.strtype = 's'; prefix.num = [1 Inf]; % --------------------------------------------------------------------- % swd Output directory % --------------------------------------------------------------------- swd = cfg_files; swd.tag = 'swd'; swd.name = 'Output directory'; swd.help = {'Files produced by this function will be written into this output directory'}; swd.filter = 'dir'; swd.ufilter = '.*'; swd.num = [1 1]; % --------------------------------------------------------------------- % dim Output image dimensions % --------------------------------------------------------------------- dim = cfg_entry; dim.tag = 'dim'; dim.name = 'Output image dimensions'; dim.help = {''}; dim.strtype = 'r'; dim.num = [2 3]; % --------------------------------------------------------------------- % res Sphere resolution % --------------------------------------------------------------------- res = cfg_entry; res.tag = 'res'; res.name = 'Sphere resolution'; res.help = {'Resolution of the unit grid on which the sphere will be created. This grid will have the resolution [-1:res:1] in x,y,z directions.'}; res.strtype = 'e'; res.num = [1 1]; % --------------------------------------------------------------------- % movprms Movement parameters % --------------------------------------------------------------------- movprms = cfg_entry; movprms.tag = 'movprms'; movprms.name = 'Movement parameters'; movprms.help = {'Enter a 1-by-6 or #directions-by-6 array of movement parameters to simulate phantom movement. Images will be simulated in transversal orientation, but the phantom may move in and out the initial bounding box.'}; movprms.strtype = 'e'; movprms.num = [Inf 6]; % --------------------------------------------------------------------- % b B value % --------------------------------------------------------------------- b = cfg_entry; b.tag = 'b'; b.name = 'B value'; b.help = {'A vector of b values (one number per image). The actual b value used in tensor computation will depend on this value, multiplied with the length of the corresponding gradient vector.'}; b.strtype = 'e'; b.num = [1 1]; % --------------------------------------------------------------------- % i0 B0 intensity % --------------------------------------------------------------------- i0 = cfg_entry; i0.tag = 'i0'; i0.name = 'B0 intensity'; i0.help = {''}; i0.strtype = 'e'; i0.num = [1 1]; % --------------------------------------------------------------------- % nr B0 noise ratio % --------------------------------------------------------------------- nr = cfg_entry; nr.tag = 'nr'; nr.name = 'B0 noise ratio'; nr.help = {''}; nr.strtype = 'e'; nr.num = [1 1]; % --------------------------------------------------------------------- % dti_dw_generate Generate diffusion weighted images % --------------------------------------------------------------------- dw_generate = cfg_exbranch; dw_generate.tag = 'dti_dw_generate'; dw_generate.name = 'Generate diffusion weighted images'; dw_generate.val = {alllines prefix swd dim res movprms b i0 nr }; dw_generate.help = { 'generate simulated diffusion weighted data' '' 'Batch processing:' 'FORMAT function dti_dw_generate(bch)' '======' 'Input argument:' 'bch struct with fields' '/*\begin{description}*/' '/*\item[*/ .dim/*]*/ [Inf Inf Inf] or [xdim ydim zdim] dimension of output images' '/*\item[*/ .res/*]*/ sphere resolution (determines number of evaluated diffusion directions)' '/*\item[*/ .b/*]*/ b Value' '/*\item[*/ .i0/*]*/ Intensity of b0 image' '/*\item[*/ .lines/*]*/ lines substructures' '/*\item[*/ .prefix/*]*/ filename stub' '/*\item[*/ .swd/*]*/ working directory' '/*\end{description}*/' 'lines substructure' '/*\begin{description}*/' '/*\item[*/ .t/*]*/ 1xN evaluation points for line functions, defaults to [1:10]' '/*\item[*/ .fxfun, .fyfun, .fzfun/*]*/ function specifications' '/*\item[*/ .iso/*]*/ ratio of isotropic diffusion (0 no isotropic diffusion, 1 no directional dependence)' '/*\item[*/ .fwhm/*]*/ exponential weight for non-isotropic diffusion (0 no weighting, +Inf only signal along line)' '/*\end{description}*/' 'This function generates fibres according to the specifications given in its input argument. Each specification describes a line in 3-D space, parameterised by lines.t.' '' 'fxfun, fyfun and fzfun can be the following functions that take as input a parameter t and an struct array with additional parameters:' '''linear''' 'ret=a*t + off;' '''tanhp''' 'ret=r*tanh(f*t+ph) + off;' '''sinp''' 'ret=r*sin(f*t+ph) + off;' '''cosp''' 'ret=r*cos(f*t+ph) + off;' '' 'fxfun, fyfun, fzfun can alternatively be specified directly as arrays fxfun(t), fyfun(t), fzfun(t) of size nlines-by-numel(t). In that case, no evaluation of fxprm, fyprm, fzprm takes place. It is checked, that the length of each array line matches the length of lines.t.' 'All parameters can be specified as 1x1, Mx1, 1xN, or MxN, where N must' 'match the number of evaluation points in t. A line will be derived for' 'each combination of parameters.' 'At each grid point (rounded x(t),y(t),z(t)) the 1st derivative of the line function (i.e. line direction) is computed. The diffusion gradient directions are assumed to lie on a sphere produced by Matlab''s isosurface command. The sphere is evaluated on a grid [-1:bch.res:1].' 'The diffusivity profile of each line is assumed to depend only on the angle between line direction and current diffusion gradient direction. When multiple lines are running through the same voxel, diffusivities will be averaged.' 'A set of diffusion weighted images will be written to disk consisting of a b0 image and one image for each diffusion gradient direction. These images can then be used as input to the tensor estimation routines. If finite dimensions for the images are given, lines will be clipped to fit into the image. Otherwise, the maximum dimensions are determined by the maximum line coordinates.' '' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id: dti_dw_generate.m 541 2007-12-31 06:58:36Z glauche $' }'; dw_generate.prog = @dti_dw_generate; dw_generate.vout = @vout_dti_dw_generate; % --------------------------------------------------------------------- % dtimg Diffusion Tensor Images % --------------------------------------------------------------------- dtimg = cfg_files; dtimg.tag = 'dtimg'; dtimg.name = 'Diffusion Tensor Images'; dtimg.help = {'Select images containing diffusion tensor data. If they are not computed using this toolbox, they need to be named according to the naming conventions of the toolbox or have at least an similar alphabetical order.'}; dtimg.filter = 'image'; dtimg.ufilter = '^D([x-z][x-z])*_.*'; dtimg.num = [6 Inf]; % --------------------------------------------------------------------- % dtorder Tensor order % --------------------------------------------------------------------- dtorder = cfg_entry; dtorder.tag = 'dtorder'; dtorder.name = 'Tensor order'; dtorder.help = {'Enter an even number (default 2). This determines the order of your diffusion tensors. Higher order tensors can be estimated only from data with many different diffusion weighting directions. See the referenced literature/*\cite{Orszalan2003}*/ for details.'}; dtorder.strtype = 'n'; dtorder.num = [1 1]; % --------------------------------------------------------------------- % maskimg Mask Image % --------------------------------------------------------------------- maskimg = cfg_files; maskimg.tag = 'maskimg'; maskimg.name = 'Mask Image'; maskimg.help = {'Specify an image for masking your data. Only voxels where this image has non-zero intensity will be processed.'}; maskimg.filter = 'image'; maskimg.ufilter = '.*'; maskimg.num = [1 1]; % --------------------------------------------------------------------- % sroi Starting ROI % --------------------------------------------------------------------- sroi = cfg_files; sroi.tag = 'sroi'; sroi.name = 'Starting ROI'; sroi.help = {'Specify starting region.'}; sroi.filter = 'image'; sroi.ufilter = '.*'; sroi.num = [1 1]; % --------------------------------------------------------------------- % eroi Target ROI (optional) % --------------------------------------------------------------------- eroi = cfg_files; eroi.tag = 'eroi'; eroi.name = 'Target ROI (optional)'; eroi.help = {'Specify target region (optional). Tracking will stop when all voxels within a target region have been reached or the specified fraction of all voxels has been visited.'}; eroi.filter = 'image'; eroi.ufilter = '.*'; eroi.num = [0 1]; % --------------------------------------------------------------------- % resfile Results filename generation % --------------------------------------------------------------------- resfile = cfg_menu; resfile.tag = 'resfile'; resfile.name = 'Results filename generation'; resfile.help = {''}; resfile.labels = { 'From Tensor' 'From Start ROI' 'From End ROI' }'; resfile.values = { 't' 's' 'e' }'; % --------------------------------------------------------------------- % swd Output directory % --------------------------------------------------------------------- swd = cfg_files; swd.tag = 'swd'; swd.name = 'Output directory'; swd.help = {'Files produced by this function will be written into this output directory'}; swd.filter = 'dir'; swd.ufilter = '.*'; swd.num = [1 1]; % --------------------------------------------------------------------- % frac Fraction of voxels to be visited % --------------------------------------------------------------------- frac = cfg_entry; frac.tag = 'frac'; frac.name = 'Fraction of voxels to be visited'; frac.help = {'Fraction of voxels to be visited before stopping.'}; frac.strtype = 'e'; frac.num = [1 1]; % --------------------------------------------------------------------- % nb Neighbourhood % --------------------------------------------------------------------- nb = cfg_menu; nb.tag = 'nb'; nb.name = 'Neighbourhood'; nb.help = {''}; nb.labels = { '6 Neighbours' '18 Neighbours' '26 Neighbours' }'; nb.values{1} = double(6); nb.values{2} = double(18); nb.values{3} = double(26); % --------------------------------------------------------------------- % exp Exponential for tensor % --------------------------------------------------------------------- exp = cfg_entry; exp.tag = 'exp'; exp.name = 'Exponential for tensor'; exp.help = {''}; exp.strtype = 'n'; exp.num = [1 1]; % --------------------------------------------------------------------- % dti_dt_time3 Tracking - Computation of Arrival time % --------------------------------------------------------------------- dt_time3 = cfg_exbranch; dt_time3.tag = 'dti_dt_time3'; dt_time3.name = 'Tracking - Computation of Arrival time'; dt_time3.val = {dtimg dtorder maskimg sroi eroi resfile swd frac nb exp }; dt_time3.help = { 'Compute time of arrival map for diffusion data' '' 'A level set algorithm is used to compute time of arrival maps. Starting with a start region, diffusion is simulated by evaluating the diffusivity profile at each voxel of a propagating front. The profile is computed efficiently from arbitrary order tensors.' '' 'References:' '[Set96] Sethian, James A. A Fast Marching Level Set Method for Monotonically Advancing Fronts. Proceedings of the National Academy of Sciences, USA, 93(4):1591 -- 1595, 1996.' '[?M03] ?rszalan, Evren and Thomas H Mareci. Generalized Diffusion Tensor Imaging and Analytical Relationships Between Diffusion Tensor Imaging and High Angular Resolution Diffusion Imaging. Magnetic Resonance in Medicine, 50:955--965, 2003.' '' 'Batch processing:' 'FORMAT dti_dt_time3(bch)' '======' 'Input argument:' 'bch - struct with batch descriptions, containing the following fields:' '.order - tensor order' '.files - cell array of tensor image filenames' '.mask - image mask' '.sroi - starting ROI' '.eroi - end ROI (optional)' '.frac - maximum fraction of voxels that should be visited (range 0-1)' '.resfile - results filename stub' '.nb - neighbourhood (one of 6, 18, 26)' '.exp - Exponential for tensor elements (should be an odd integer)' '' 'This function is part of the diffusion toolbox for SPM5. For general help about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' '_______________________________________________________________________' '' '@(#) $Id: dti_dt_time3.m 543 2008-03-12 19:40:40Z glauche $' }'; dt_time3.prog = @dti_dt_time3; dt_time3.vout = @vout_dti_dt_time3; % --------------------------------------------------------------------- % sroi Starting ROI % --------------------------------------------------------------------- sroi = cfg_files; sroi.tag = 'sroi'; sroi.name = 'Starting ROI'; sroi.help = {'Specify starting region.'}; sroi.filter = 'image'; sroi.ufilter = '.*'; sroi.num = [1 1]; % --------------------------------------------------------------------- % trace Trace Image % --------------------------------------------------------------------- trace = cfg_files; trace.tag = 'trace'; trace.name = 'Trace Image'; trace.help = {'Specify trace image.'}; trace.filter = 'image'; trace.ufilter = '.*'; trace.num = [1 1]; % --------------------------------------------------------------------- % prefix Output Filename Prefix % --------------------------------------------------------------------- prefix = cfg_entry; prefix.tag = 'prefix'; prefix.name = 'Output Filename Prefix'; prefix.val = {'p'}; prefix.help = {'The output filename is constructed by prefixing the original filename with this prefix.'}; prefix.strtype = 's'; prefix.num = [1 Inf]; % --------------------------------------------------------------------- % dti_tracepath Tracking - Backtracing Paths % --------------------------------------------------------------------- tracepath = cfg_exbranch; tracepath.tag = 'dti_tracepath'; tracepath.name = 'Tracking - Backtracing Paths'; tracepath.val = {sroi trace prefix }; tracepath.help = { 'Backtrace path to starting ROI' '' 'This routine computes a path from a region of interest back to the' 'source of tracking from dti_dt_time3. The region of interest may' 'contain multiple voxels, which need not be connected.' '' 'FORMAT [res bchdone]=dti_tracepath(bch)' '======' 'Input argument:' 'bch - struct array with batch descriptions, containing the following' 'fields:' '.sroi - starting ROI (image filename or 3D array)' '.trace - trace (image filename or 3D array)' '.prefix - output image prefix' 'Output arguments:' 'res - results structure' 'bchdone - filled batch structure' 'Output filename will be constructed by prefixing trace filename with a' 'customisable prefix. If trace is a 3D array, then sroi filename will be' 'tried instead. The filename will be returned in res.path. If both sroi' 'and trace are 3D arrays or bch.prefix is empty, res.path will be a 3D' 'array containing the traced paths.' '' 'This function is part of the diffusion toolbox for SPM5. For general help' 'about this toolbox, bug reports, licensing etc. type' 'spm_help vgtbx_config_Diffusion' 'in the matlab command window after the toolbox has been launched.' }'; tracepath.prog = @dti_tracepath; %tracepath.vout = @vout_dti_tracepath; % --------------------------------------------------------------------- % vgtbx_Diffusion Diffusion toolbox % --------------------------------------------------------------------- vgtbx_Diffusion = cfg_choice; vgtbx_Diffusion.tag = 'vgtbx_Diffusion'; vgtbx_Diffusion.name = 'Diffusion toolbox'; vgtbx_Diffusion.help = { 'Diffusion toolbox' '_______________________________________________________________________' '' 'This toolbox contains various functions related to post-processing of diffusion weighted image series in SPM. Topics include movement correction for image time series, estimation of the diffusion tensor, computation of anisotropy indices and tensor decomposition. Visualisation of diffusion tensor data (quiver & red-green-blue plots of eigenvector data) is not included in this toolbox, but there are separate plugins for spm_orthviews available for download at the same place as the source code of this toolbox.' '' 'The algorithms applied in this toolbox are referenced within the PDF help texts of the functions where they are implemented.' '' 'This toolbox is free but copyright software, distributed under the terms of the GNU General Public Licence as published by the Free Software Foundation (either version 2, as given in file spm_LICENCE.man, or at your option, any later version). Further details on "copyleft" can be found at http://www.gnu.org/copyleft/.' 'The toolbox consists of the files listed in its Contents.m file.' '' 'The source code of this toolbox is available at' '' 'http://sourceforge.net/projects/spmtools' '' 'Please use the SourceForge forum and tracker system for comments, suggestions, bug reports etc. regarding this toolbox.' '_______________________________________________________________________' '' '@(#) $Id: vgtbx_config_Diffusion.m 543 2008-03-12 19:40:40Z glauche $' }'; vgtbx_Diffusion.values = {init_dtidata dw_wmean_variance dw_cluster_std_differences dw_wmean_review ... realign reorient_gradient adc dt_adc dt_regress warp_tensors dtieig indices saliencies disp_grad extract_dirs dtihosvd recalc dw_generate dt_time3 tracepath tbxdti_cfg_favbs_norm}; % vfiles functions %======================================================================= % Note: if isfield(bch,'data') switches are currently not functional - % this would e.g. require a cfg_choice bch.input to work. function dep = vout_dti_init_dtidata(job) dep = cfg_dep; dep.sname = '(Re)Initialised DW Images'; dep.src_output = substruct('.','files'); dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); function dep = vout_dti_adc(job) dep = cfg_dep; dep.sname = 'ADC Images'; dep.src_output = substruct('.','adc'); dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); function dep = vfiles_dti_dt_adc(job) dep = cfg_dep; dep.sname = 'Tensor Images'; dep.src_output = substruct('.','dt'); dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); function dep = vout_dti_realign(job) dep = cfg_dep; dep.sname = 'Realigned DW Images'; dep.src_output = substruct('.','files'); dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); function dep = vout_dti_reorient_gradient(job) dep = cfg_dep; dep.sname = 'Images with Reoriented Gradients'; dep.src_output = substruct('.','tgtimgs'); dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); function dep = vout_dti_dt_regress(job) dep(1) = cfg_dep; dep(1).sname = 'Tensor Images'; dep(1).src_output = substruct('.','dt'); dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Ln(A0) Image'; dep(2).src_output = substruct('.','ln'); dep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(3) = cfg_dep; dep(3).sname = 'SPM.mat (Tensor estimation)'; dep(3).src_output = substruct('.','spmmat'); dep(3).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); function dep = vout_dti_eig(job) if ~ischar(job.dteigopts) || strcmpi(job.dteigopts,'<undefined>') dep = cfg_dep; dep = dep(false); else if isfield(job, 'data') tgt_spec = cfg_findspec({{'strtype','r'}}); else tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end; vdep = []; ldep = []; adep = []; if any (job.dteigopts=='v') vdep = cfg_dep; vdep.sname = 'Eigenvectors'; vdep.src_output = substruct('.','evec'); vdep.tgt_spec = tgt_spec; end; if any(job.dteigopts=='l') ldep = cfg_dep; ldep.sname = 'Eigenvalues'; ldep.src_output = substruct('.','eval'); ldep.tgt_spec = tgt_spec; end; if any(job.dteigopts=='a') adep = cfg_dep; adep.sname = 'Euler Angles'; adep.src_output = substruct('.','euler'); adep.tgt_spec = tgt_spec; end; dep = [vdep ldep adep]; end; function dep = vout_dti_indices(job) if ~ischar(job.option) || strcmpi(job.option,'<undefined>') dep = cfg_dep; dep = dep(false); else if isfield(job, 'data') tgt_spec = cfg_findspec({{'strtype','r'}}); else tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end; fdep = []; vdep = []; ddep = []; if any (job.option=='f') fdep = cfg_dep; fdep.sname = 'FA Data'; fdep.src_output = substruct('.','fa'); fdep.tgt_spec = tgt_spec; end; if any (job.option=='v') vdep = cfg_dep; vdep.sname = 'VA Data'; vdep.src_output = substruct('.','va'); vdep.tgt_spec = tgt_spec; end; if any (job.option=='d') ddep = cfg_dep; ddep.sname = 'AD Data'; ddep.src_output = substruct('.','ad'); ddep.tgt_spec = tgt_spec; end; dep = [fdep vdep ddep]; end; function dep = vout_dti_saliencies(job) if isfield(job, 'data') tgt_spec = cfg_findspec({{'strtype','r'}}); else tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end; dep(1) = cfg_dep; dep(1).sname = 'Curve-ness'; dep(1).src_output = substruct('.','sc'); dep(1).tgt_spec = tgt_spec; dep(2) = cfg_dep; dep(2).sname = 'Plane-ness'; dep(2).src_output = substruct('.','sp'); dep(2).tgt_spec = tgt_spec; dep(3) = cfg_dep; dep(3).sname = 'Sphere-ness'; dep(3).src_output = substruct('.','ss'); dep(3).tgt_spec = tgt_spec; function dep = vout_dti_hosvd(job) if isfield(job, 'data') dep = cfg_dep; dep.sname = 'SVD result'; dep.src_output = substruct('.','S'); dep.tgt_spec = cfg_findspec({{'strtype','r'}}); else dep(1) = cfg_dep; dep(1).sname = 'SVD(S) Images'; dep(1).src_output = substruct('.','S'); dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'SVD(U) Images'; dep(2).src_output = substruct('.','U'); dep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end; function dep = vout_dti_dt_time3(job) dep(1) = cfg_dep; dep(1).sname = 'Time of Arrival'; dep(1).src_output = substruct('.','ta'); dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Time of Arrival (Band)'; dep(2).src_output = substruct('.','tb'); dep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(3) = cfg_dep; dep(3).sname = 'Time of Arrival (Loc min)'; dep(3).src_output = substruct('.','tl'); dep(3).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(4) = cfg_dep; dep(4).sname = 'Distance'; dep(4).src_output = substruct('.','dst'); dep(4).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(5) = cfg_dep; dep(5).sname = 'Trace'; dep(5).src_output = substruct('.','trc'); dep(5).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(6) = cfg_dep; dep(6).sname = 'Velocity'; dep(6).src_output = substruct('.','vel'); dep(6).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); function str = check_dti_reorient_gradient(job) if numel(job.srcimgs) ~= numel(job.tgtimgs) str = '# source images must match # target images.'; else str = ''; end; return; function dep = vout_dti_dw_generate(job) dep = cfg_dep; dep.sname = 'DWI Simulation: Generated Volumes'; dep.src_output = substruct('.','files'); dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); function dep = vout_dti_extract_dirs(job) dep = cfg_dep; dep.sname = 'Extracted direction information'; dep.src_output = substruct('()',{1}); dep.tgt_spec = cfg_findspec({{'strtype','e'}});
github
philippboehmsturm/antx-master
vgtbx_config_Diffusion.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/vgtbx_config_Diffusion.m
42,826
utf_8
eb9604e7277e472a87001e6ff56b0f26
function varargout = vgtbx_config_Diffusion(varargin) % Diffusion toolbox %_______________________________________________________________________ % % This toolbox contains various functions related to post-processing of % diffusion weighted image series in SPM5. Topics include movement % correction for image time series, estimation of the diffusion tensor, % computation of anisotropy indices and tensor decomposition. Visualisation % of diffusion tensor data (quiver & red-green-blue plots of eigenvector % data) is not included in this toolbox, but there are separate plugins % for spm_orthviews available for download at the same place as the % source code of this toolbox. % % The algorithms applied in this toolbox are referenced within the PDF help % texts of the functions where they are implemented. % % This toolbox is free but copyright software, distributed under the % terms of the GNU General Public Licence as published by the Free % Software Foundation (either version 2, as given in file % spm_LICENCE.man, or at your option, any later version). Further details % on "copyleft" can be found at http://www.gnu.org/copyleft/. % The toolbox consists of the files listed in its Contents.m file. % % The source code of this toolbox is available at % % http://sourceforge.net/projects/spmtools % % Please use the SourceForge forum and tracker system for comments, % suggestions, bug reports etc. regarding this toolbox. %_______________________________________________________________________ % % @(#) $Id: vgtbx_config_Diffusion.m 543 2008-03-12 19:40:40Z glauche $ % This is the main config file for the SPM5 job management system. It % resides in fullfile(spm('dir'),'toolbox','Diffusion'). rev='$Revision: 543 $'; addpath(genpath(fullfile(spm('dir'),'toolbox','Diffusion'))); % see how we are called - if no output argument, then start spm_jobman UI if nargout == 0 spm_jobman('interactive','','jobs.tools.vgtbx_Diffusion'); return; end; % Some common input elements %======================================================================= interp.type = 'menu'; interp.name = 'Interpolation'; interp.tag = 'interp'; interp.labels = {'Nearest neighbour','Trilinear','2nd Degree b-Spline',... '3rd Degree b-Spline','4th Degree b-Spline','5th Degree b-Spline',... '6th Degree b-Spline','7th Degree b-Spline','2nd Degree Sinc',... '3rd Degree Sinc','4th Degree Sinc','5th Degree Sinc',... '6th Degree Sinc','7th Degree Sinc'}; interp.values = {0,1,2,3,4,5,6,7,-2,-3,-4,-5,-6,-7}; interp.def = 'tools.vgtbx_Diffusion.interp'; hold = interp; hold.tag = 'hold'; dtorder.type = 'entry'; dtorder.name = 'Tensor order'; dtorder.tag = 'dtorder'; dtorder.strtype = 'n'; dtorder.num = [1 1]; dtorder.help = {['Enter an even number (default 2). This determines the order of your ' ... 'diffusion tensors. Higher order tensors can be estimated ' ... 'only from data with many different diffusion weighting ' ... 'directions. See the referenced literature/*\cite{Orszalan2003}*/ for details.']}; res.type = 'entry'; res.strtype = 'e'; res.name = 'Sphere resolution'; res.tag = 'res'; res.num = [1 1]; res.help = {['Resolution of the unit grid on which the sphere will be ' ... 'created. This grid will have the resolution [-1:res:1] in ' ... 'x,y,z directions.']}; prefix.type = 'entry'; prefix.name = 'Output Filename Prefix'; prefix.tag = 'prefix'; prefix.strtype = 's'; prefix.num = [1 Inf]; prefix.help = {['The output filename is constructed by prefixing the original filename ' ... 'with this prefix.']}; sep.type = 'menu'; sep.name = 'Distinguish antiparallel gradient directions'; sep.tag = 'sep'; sep.labels = {'Yes','No'}; sep.values = {1,0}; sep.def = 'tools.vgtbx_Diffusion.extract_dirs.sep'; sep.help = {['In theory, antiparallel gradient directions should be ' ... 'equivalent when measuring diffusion. However, due to possible ' ... 'scanner effects this might be not true.'],'',... ['If this entry is set to ''Yes'' then antiparallel gradient ' ... 'directions will be treated as different from each other.']}; dtol.type = 'entry'; dtol.name = 'Gradient direction tolerance'; dtol.tag = 'dtol'; dtol.strtype = 'e'; dtol.num = [1 1]; dtol.def = 'tools.vgtbx_Diffusion.extract_dirs.dtol'; dtol.help = {['Determines which gradient vectors describe similar directions. ' ... 'Colinearity will be computed as the scalar product between ' ... 'two unit-length gradient vectors.'],'',... ['Two gradient vectors are treated as similar, if their ' ... 'scalar product is larger than the tolerance value. This ' ... 'means a tolerance value of -1 will treat all directions ' ... 'as similar, whereas a positive value between 0 and 1 ' ... 'will distinguish between different directions.']}; ltol.type = 'entry'; ltol.name = 'B value tolerance'; ltol.tag = 'ltol'; ltol.strtype = 'e'; ltol.num = [1 1]; ltol.def = 'tools.vgtbx_Diffusion.extract_dirs.ltol'; ltol.help = {['B values will be divided by this tolerance value and then ' ... 'rounded. Any b values that are still different after ' ... 'rounding, will be treated as different.']}; %-input and output files %----------------------------------------------------------------------- srcimgs.type = 'files'; srcimgs.name = 'Source Images'; srcimgs.tag = 'srcimgs'; srcimgs.filter = 'image'; srcimgs.num = [1 Inf]; srcimgs.help = {'The source images (one or more).'}; srcimg.type = 'files'; srcimg.name = 'Source Image'; srcimg.tag = 'srcimg'; srcimg.filter = 'image'; srcimg.num = [1 1]; srcimg.help = {'One source image.'}; snparams = srcimg; snparams.tag = 'snparams'; snparams.name = 'Normalisation parameters (optional)'; snparams.filter = 'mat'; snparams.ufilter = '.*sn.*'; snparams.num = [0 1]; snparams.val = {''}; snparams.help = {['A file containing spatial normalisation parameters. ' ... 'Spatial transformations from normalisation will be read from this file.']}; maskimg.type = 'files'; maskimg.name = 'Mask Image'; maskimg.tag = 'maskimg'; maskimg.filter = 'image'; maskimg.num = [1 1]; maskimg.help = {['Specify an image for masking your data. Only voxels where ' ... 'this image has non-zero intensity will be ' ... 'processed.']}; optmaskimg = maskimg; optmaskimg.name = 'Mask Image (optional)'; optmaskimg.num = [0 1]; optmaskimg.val = {''}; optmaskimg.help = {optmaskimg.help{:},'',['This image is optional. If not ' ... 'specified, the whole volume will be analysed.']}; dtimg.type = 'files'; dtimg.name = 'Diffusion Tensor Images'; dtimg.tag = 'dtimg'; dtimg.filter = 'image'; dtimg.ufilter = '^D([x-z][x-z])*_.*'; dtimg.num = [6 Inf]; dtimg.help = {['Select images containing diffusion tensor data. If they are ' ... 'not computed using this toolbox, they need to be named ' ... 'according to the naming conventions of the toolbox or have ' ... 'at least an similar alphabetical order.']}; faimg.type = 'files'; faimg.name = 'Fractional Anisotropy Image'; faimg.tag = 'faimg'; faimg.filter = 'image'; faimg.ufilter = '^fa.*'; faimg.num = [1 1]; e1img.type = 'files'; e1img.name = '1st Eigenvector Images'; e1img.tag = 'e1img'; e1img.filter = 'image'; e1img.ufilter = '^e(vec)?1.*'; e1img.num = [3 3]; e2img.type = 'files'; e2img.name = '2nd Eigenvector Images'; e2img.tag = 'e2img'; e2img.filter = 'image'; e2img.ufilter = '^e(vec)?2.*'; e2img.num = [3 3]; e3img.type = 'files'; e3img.name = '3rd Eigenvector Images'; e3img.tag = 'e3img'; e3img.filter = 'image'; e3img.ufilter = '^e(vec)?3.*'; e3img.num = [3 3]; limg.type = 'files'; limg.name = 'Eigenvalue Images'; limg.tag = 'limg'; limg.filter = 'image'; limg.ufilter = '^(eva)?l[1-3].*'; limg.num = [3 3]; swd.type = 'files'; swd.name = 'Output directory'; swd.tag = 'swd'; swd.filter = 'dir'; swd.num = [1 1]; swd.help = {['Files produced by this function will be written into this ' ... 'output directory']}; srcspm.type = 'files'; srcspm.name = 'Source SPM.mat'; srcspm.tag = 'srcspm'; srcspm.filter = 'mat'; srcspm.ufilter = '.*SPM.*\.mat'; srcspm.num = [1 1]; srcspm.help = {'Select SPM.mat from a previous analysis step.'}; % Comparisons %======================================================================= % Classify tensors %----------------------------------------------------------------------- fathresh.type = 'entry'; fathresh.name = 'FA threshold'; fathresh.tag = 'fathresh'; fathresh.strtype = 'e'; fathresh.num = [1 1]; fathresh.help = {['FA threshold - Voxels above will be treated as ' ... 'anisotropic, voxels below as isotropic.']}; clprefix = prefix; clprefix.val = {'cl'}; classify.type = 'branch'; classify.name = 'Classify Neighbouring Tensors'; classify.tag = 'dti_classify'; classify.val = {e1img faimg fathresh maskimg clprefix}; classify.prog = @dti_classify; classify.vfiles = @vfiles_dti_classify; classify.help = vgtbx_help2cell('dti_classify'); % Compare tensors %----------------------------------------------------------------------- refdtimg = dtimg; refdtimg.tag = 'refdtimg'; refdtimg.name = 'Reference Tensor'; cpprefix = prefix; cpprefix.val = {'cp'}; compare.type = 'branch'; compare.name = 'Voxel-by-Voxel Comparison of Tensors'; compare.tag = 'dti_compare'; compare.val = {dtimg, refdtimg, maskimg cpprefix}; compare.prog = @dti_compare; compare.vfiles = @vfiles_dti_compare; compare.help = vgtbx_help2cell('dti_compare'); % Rotate tensors %----------------------------------------------------------------------- refe1img = e1img; refe1img.tag = 'refe1img'; refe1img.name = 'Reference Eigenvector'; roprefix = prefix; roprefix.val = {'ro'}; evec_rot.type = 'branch'; evec_rot.name = 'Voxel-by-Voxel Rotation of Eigenvectors'; evec_rot.tag = 'dti_evec_rot'; evec_rot.val = {e1img, refe1img, maskimg roprefix}; evec_rot.prog = @dti_evec_rot; evec_rot.vfiles = @vfiles_dti_evec_rot; evec_rot.help = vgtbx_help2cell('dti_evec_rot'); % Tensor estimation %======================================================================= % ADC %----------------------------------------------------------------------- file0 = srcimg; file0.tag = 'file0'; file0.name = 'B0 image'; file0.help = {'Select the b0 image for ADC computation.'}; files1 = srcimgs; files1.tag = 'files1'; files1.name = 'DW image(s)'; files1.help = {['Diffusion weighted images - one ADC image per DW image ' ... 'will be produced.']}; minS.type = 'entry'; minS.name = 'Minimum Signal Threshold'; minS.tag = 'minS'; minS.strtype = 'e'; minS.num = [1 1]; minS.val = {1}; minS.help = {['Logarithm of values below 1 will produce negative ADC ' ... 'results. Very low intensities are probably due to noise ' ... 'and should be masked out.']}; adcprefix = prefix; adcprefix.val = {'adc_'}; adc.type = 'branch'; adc.name = 'Compute ADC Images'; adc.tag = 'dti_adc'; adc.val = {file0 files1 minS adcprefix interp}; adc.prog = @dti_adc; adc.vfiles = @vfiles_dti_adc; adc.help = vgtbx_help2cell('dti_adc'); % Tensor from 6 ADC images %----------------------------------------------------------------------- files = srcimgs; files.tag = 'files'; files.name = 'ADC images'; files.num = [6 6]; dt_adc.type = 'branch'; dt_adc.name = 'Compute Tensor from 6 ADC Images'; dt_adc.tag = 'dti_dt_adc'; dt_adc.val = {files, interp}; dt_adc.prog = @dti_dt_adc; dt_adc.vfiles = @vfiles_dti_dt_adc; dt_adc.help = vgtbx_help2cell('dti_dt_adc'); % Tensor from multiple directions/multiple measurements %----------------------------------------------------------------------- dwsrcimgs = srcimgs; dwsrcimgs.tag = 'srcimgs'; dwsrcimgs.name = 'DW images'; dwsrcimgs.num = [8 Inf]; dwsrcimgs.help = {['Enter all diffusion weighted images (all replicated ' ... 'measurements, all diffusion weightings) and b0 images ' ... 'at once.']}; inorder.type = 'menu'; inorder.name = 'Input Order'; inorder.tag = 'inorder'; inorder.labels = {'repl1 all b | repl2 all b ... replX all b', ... 'b1 all repl | b2 all repl ... bX all repl'}; inorder.values ={'repl','bval'}; inorder.help = {['The input order determines the way in which error ' ... 'covariance components are specified: the assumption is ' ... 'that error covariances are equal over similar diffusion '... 'weightings. If images are given replication by replication, '... 'the ordering of diffusion weighting should be the same ' ... 'for each replication.']}; ndw.type = 'entry'; ndw.name = '# of different diffusion weightings'; ndw.tag = 'ndw'; ndw.strtype = 'n'; ndw.num = [1 1]; ndw.help = {['Give the number of different diffusion weightings. The product ' ... 'of #dw and #rep must match the number of your images.']}; nrep.type = 'entry'; nrep.name = '# of repetitions'; nrep.tag = 'nrep'; nrep.strtype = 'n'; nrep.num = [1 1]; nrep.help = {['Give the number of repeated measurements. The product ' ... 'of #dw and #rep must match the number of your images.']}; erriid.type = 'const'; erriid.tag = 'erriid'; erriid.name = 'Equal errors, equal variance'; erriid.val = {1}; regltol = ltol; regdtol.def = 'tools.vgtbx_Diffusion.dti_dt_regress.ltol'; regdtol = dtol; regdtol.def = 'tools.vgtbx_Diffusion.dti_dt_regress.dtol'; regsep = sep; regsep.def = 'tools.vgtbx_Diffusion.dti_dt_regress.sep'; errauto.type = 'branch'; errauto.tag = 'errauto'; errauto.name = 'Auto-determined by b-values'; errauto.val = {regltol regdtol regsep}; errauto.help = {['Automatic determination of error variance components ' ... 'from diffusion weighting information. This is the ' ... 'recommended method.'],'',... ['To discriminate between b values, but not directions, ' ... 'set direction tolerance to 0 and do not distinguish ' ... 'between antiparallel directions.']}; errspec.type = 'branch'; errspec.tag = 'errspec'; errspec.name = 'User specified'; errspec.val = {inorder, ndw, nrep}; errspec.help = {['Specify error variance components for repeated measurements ' ... 'with similar diffusion weighting in each ' ... 'repetition.']}; errorvar.type = 'choice'; errorvar.name = 'Error variance options'; errorvar.tag = 'errorvar'; errorvar.values = {erriid, errauto, errspec}; errorvar.help = {['Diffusion weighted images may have different error ' ... 'variances depending on diffusion gradient strength and ' ... 'directions. To correct for this, one can model error ' ... 'variances based on diffusion information or measurement ' ... 'order.']}; dtoptmaskimg = optmaskimg; dtoptmaskimg.help = {dtoptmaskimg.help{:},'',... ['For a proper estimation of error covariances, non-brain ' ... 'voxels should be excluded by an explicit mask. This ' ... 'could be an mask based on an intensity threshold of ' ... 'your b0 images or a mask based on grey and white ' ... 'matter segments from SPM segmentation. Only voxels, ' ... 'with non-zero mask values will be included into analysis.']}; spatsm.type = 'menu'; spatsm.name = 'Estimate spatial smoothness'; spatsm.tag = 'spatsm'; spatsm.labels = {'Yes', 'No'}; spatsm.values = {1 0}; spatsm.help = {['Spatial smoothness estimates are not needed if one is ' ... 'only interested in the tensor values itself. Estimation ' ... 'can be speeded up by forcing SPM not to compute it.']}; spatsm.def = 'tools.vgtbx_Diffusion.dti_dt_regress.spatsm'; dt_regress.type = 'branch'; dt_regress.name = 'Compute Tensor (Multiple Regression)'; dt_regress.tag = 'dti_dt_regress'; dt_regress.val = {dwsrcimgs, errorvar,dtorder,dtoptmaskimg,swd,spatsm}; dt_regress.prog = @dti_dt_regress; dt_regress.vfiles = @vfiles_dti_dt_regress; dt_regress.help = vgtbx_help2cell('dti_dt_regress'); % Recover DW images from tensor fit %----------------------------------------------------------------------- recalc.type = 'branch'; recalc.name = 'Compute filtered/adjusted DW Images from Regression Model'; recalc.tag = 'dti_recalc'; recalc.val = {srcspm,prefix}; recalc.prog = @dti_recalc; recalc.vfiles = @vfiles_dti_recalc; recalc.help = vgtbx_help2cell('dti_recalc'); %-Tensor decomposition %======================================================================= % Eigenvectors/values/angles %----------------------------------------------------------------------- dteigopts.type = 'menu'; dteigopts.name = 'Decomposition output'; dteigopts.tag = 'dteigopts'; dteigopts.labels = {'Eigenvectors and Eigenvalues',... 'Euler angles and Eigenvalues',... 'Eigenvalues only',... 'Euler angles only',... 'All'}; dteigopts.values = {'vl','al','l','a','alv'}; dt_eig.type = 'branch'; dt_eig.name = 'Tensor decomposition'; dt_eig.tag = 'dti_eig'; dt_eig.val = {dtimg, dteigopts}; dt_eig.prog = @dti_eig; dt_eig.vfiles = @vfiles_dti_eig; dt_eig.help = vgtbx_help2cell('dti_eig'); % Tensor indices %----------------------------------------------------------------------- option.type = 'menu'; option.name = 'Compute indices'; option.tag = 'option'; option.labels = {'Fractional Anisotropy',... 'Variance Anisotropy',... 'Average Diffusivity',... 'Fractional+Variance Anisotropy',... 'All'}; option.values = {'f','v','d','fv','fvd'}; indices.type = 'branch'; indices.name = 'Tensor Indices'; indices.tag = 'dti_indices'; indices.val = {dtimg, option}; indices.prog = @dti_indices; indices.vfiles = @vfiles_dti_indices; indices.help = vgtbx_help2cell('dti_indices'); % Salient features %----------------------------------------------------------------------- saliencies.type = 'branch'; saliencies.name = 'Salient Features'; saliencies.tag = 'dti_saliencies'; saliencies.val = {limg}; saliencies.prog = @dti_saliencies; saliencies.vfiles = @vfiles_dti_saliencies; saliencies.help = vgtbx_help2cell('dti_saliencies'); %-Time of Arrival Tracking %======================================================================= % Full tensor tracking %----------------------------------------------------------------------- sroi = srcimg; sroi.name = 'Starting ROI'; sroi.tag = 'sroi'; sroi.help = {'Specify starting region.'}; eroi = srcimg; eroi.name = 'Target ROI (optional)'; eroi.tag = 'eroi'; eroi.num = [0 1]; eroi.help = {['Specify target region (optional). Tracking will stop when ' ... 'all voxels within a target region have been reached or the ' ... 'specified fraction of all voxels has been visited.']}; frac.type = 'entry'; frac.strtype = 'e'; frac.name = 'Fraction of voxels to be visited'; frac.tag = 'frac'; frac.num = [1 1]; frac.help = {['Fraction of voxels to be visited before stopping.']}; exp.type = 'entry'; exp.strtype = 'n'; exp.name = 'Exponential for tensor'; exp.tag = 'exp'; exp.num = [1 1]; resfile.type = 'menu'; resfile.name = 'Results filename generation'; resfile.tag = 'resfile'; resfile.labels = {'From Tensor','From Start ROI', 'From End ROI'}; resfile.values = {'t','s','e'}; nb.type = 'menu'; nb.name = 'Neighbourhood'; nb.tag = 'nb'; nb.labels = {'6 Neighbours','18 Neighbours', '26 Neighbours'}; nb.values = {6,18,26}; dt_time3.type = 'branch'; dt_time3.name = 'Tracking - Computation of Arrival time'; dt_time3.tag = 'dti_dt_time3'; dt_time3.val = {dtimg dtorder maskimg sroi eroi resfile swd frac nb exp}; dt_time3.prog = @dti_dt_time3; dt_time3.vfiles = @vfiles_dti_dt_time3; dt_time3.help = vgtbx_help2cell('dti_dt_time3'); % Backtracing paths %----------------------------------------------------------------------- trace = srcimg; trace.name = 'Trace Image'; trace.tag = 'trace'; trace.help = {'Specify trace image.'}; pathprefix = prefix; pathprefix.val = {'p'}; dt_tracepath.type = 'branch'; dt_tracepath.name = 'Tracking - Backtracing Paths'; dt_tracepath.tag = 'dti_tracepath'; dt_tracepath.val = {sroi trace pathprefix}; dt_tracepath.prog = @dti_tracepath; dt_tracepath.help = vgtbx_help2cell('dti_tracepath'); %-Higher Order Tensors %======================================================================= % Higher Order SVD %----------------------------------------------------------------------- hosvd.type = 'branch'; hosvd.name = 'Higher Order SVD'; hosvd.tag = 'dti_hosvd'; hosvd.val = {dtimg dtorder}; hosvd.prog = @dti_hosvd; hosvd.vfiles = @vfiles_dti_hosvd; hosvd.help = vgtbx_help2cell('dti_hosvd'); %-Preprocessing %======================================================================= % Init DTI data %----------------------------------------------------------------------- b.type = 'entry'; b.name = 'B values'; b.tag = 'b'; b.strtype = 'e'; b.num = [Inf 1]; b.help = {['A vector of b values (one number per image). The actual b value ' ... 'used in tensor computation will depend on this value, multiplied ' ... 'with the length of the corresponding gradient vector.']}; g.type = 'entry'; g.name = 'Gradient direction values'; g.tag = 'g'; g.strtype = 'e'; g.num = [Inf 3]; g.help = {['A #img-by-3 matrix of gradient directions. The length of each ' ... 'gradient vector will be used as a scaling factor to the b ' ... 'value. Therefore, you should make sure that your gradient ' ... 'vectors are of unit length if your b value already encodes ' ... 'for diffusion weighting strength.']}; M.type = 'const'; M.name = 'Reset orientation'; M.tag = 'M'; M.val = {1}; M.hidden = 1; resetall.type = 'branch'; resetall.name = '(Re)set Gradient, b value and position'; resetall.tag = 'resetall'; resetall.val = {b g M}; resetbg.type = 'branch'; resetbg.name = '(Re)set Gradient and b value'; resetbg.tag = 'resetbg'; resetbg.val = {b g}; resetb.type = 'branch'; resetb.name = '(Re)set b value'; resetb.tag = 'resetb'; resetb.val = {b}; resetg.type = 'branch'; resetg.name = '(Re)set Gradient'; resetg.tag = 'reset'; resetg.val = {g}; resetM.type = 'branch'; resetM.name = '(Re)set position'; resetM.tag = 'resetM'; resetM.val = {M}; setM.type = 'const'; setM.name = 'Add M matrix to existing DTI information'; setM.tag = 'setM'; setM.val = {1}; initopts.type = 'choice'; initopts.name = '(Re)Set what?'; initopts.tag = 'initopts'; initopts.values = {resetall, resetbg, resetb, resetg, resetM, setM}; init_dti_data.type = 'branch'; init_dti_data.name = '(Re)Set DTI information'; init_dti_data.tag = 'dti_init_dtidata'; init_dti_data.val = {srcimgs, initopts}; init_dti_data.prog = @dti_init_dtidata; init_dti_data.help = vgtbx_help2cell('dti_init_dtidata'); % Realign %----------------------------------------------------------------------- b0corr.type = 'menu'; b0corr.name = 'Motion correction on b0 images'; b0corr.tag = 'b0corr'; b0corr.labels = {'None', 'Stepwise', ... 'Linear interpolation (last stepwise)',... 'Linear interpolation (last linear)'}; b0corr.values = {0,1,2,3}; b1corr.type = 'menu'; b1corr.name = 'Motion correction on all (b0+DW) images'; b1corr.tag = 'b1corr'; b1corr.labels = {'None', 'Realign xy',... 'Realign per dw separately',... 'Realign xy & Coregister to mean',... 'Full Realign & Coregister (rigid body) to mean',... 'Full Realign & Coregister (full affine) to mean'}; b1corr.values = {0,1,2,3,4,5}; realign.type = 'branch'; realign.name = 'Realign DW image time series'; realign.tag = 'dti_realign'; realign.val = {srcimgs, b0corr, b1corr}; realign.prog = @dti_realign; realign.help = vgtbx_help2cell('dti_realign'); % Reorient gradients %----------------------------------------------------------------------- rsrcimgs = srcimgs; rsrcimgs.help = {['Diffusion information will be read from these ' ... 'images.']}; tgtimgs = srcimgs; tgtimgs.name = 'Target images'; tgtimgs.tag = 'tgtimgs'; tgtimgs.help = {['Diffusion information will be copied to this images, ' ... 'applying motion correction and (optional) normalisation ' ... 'information to gradient directions.']}; rot.type = 'menu'; rot.name = 'Rotation'; rot.tag = 'rot'; rot.labels = {'Yes', 'No'}; rot.values = {1, 0}; rot.def = 'tools.vgtbx_Diffusion.dti_reorient_gradient.useaff.rot'; zoom.type = 'menu'; zoom.name = 'Zoom'; zoom.tag = 'zoom'; zoom.labels = {'Sign of zooms', 'Sign and magnitude', 'No'}; zoom.values = {1, 2, 0}; zoom.def = 'tools.vgtbx_Diffusion.dti_reorient_gradient.useaff.zoom'; shear.type = 'menu'; shear.name = 'Shear'; shear.tag = 'shear'; shear.labels = {'Yes', 'No'}; shear.values = {1, 0}; shear.def = 'tools.vgtbx_Diffusion.dti_reorient_gradient.useaff.shear'; useaff.type = 'branch'; useaff.name = 'Affine Components for Reorientation'; useaff.tag = 'useaff'; useaff.val = {rot, zoom, shear}; useaff.help = {['Select which parts of an affine transformation to consider ' ... 'for reorientation.']}; reorient_gradient.type = 'branch'; reorient_gradient.name = 'Copy and Reorient diffusion information'; reorient_gradient.tag = 'dti_reorient_gradient'; reorient_gradient.val = {rsrcimgs tgtimgs snparams useaff}; reorient_gradient.prog = @dti_reorient_gradient; reorient_gradient.vfiles = @vfiles_dti_reorient_gradient; %reorient_gradient.check = @check_dti_reorient_gradient; reorient_gradient.help = vgtbx_help2cell('dti_reorient_gradient'); % Warp tensors %----------------------------------------------------------------------- rsnparams = rmfield(snparams,'val'); rsnparams.name = 'Normalisation parameters'; rsnparams.num = [1 1]; warp_tensors.type = 'branch'; warp_tensors.name = 'Warp tensors'; warp_tensors.tag = 'dti_warp_tensors'; warp_tensors.val = {dtimg rsnparams}; warp_tensors.prog = @dti_warp_tensors; warp_tensors.help = vgtbx_help2cell('dti_warp_tensors'); %-Visualisation %======================================================================= % Visualise gradient directions %----------------------------------------------------------------------- axbgcol.type = 'entry'; axbgcol.strtype = 'e'; axbgcol.name = 'Axis background colour'; axbgcol.tag = 'axbgcol'; axbgcol.num = [1 3]; axbgcol.def = 'tools.vgtbx_Diffusion.dti_disp_grad.axbgcol'; fgbgcol.type = 'entry'; fgbgcol.strtype = 'e'; fgbgcol.name = 'Figure background colour'; fgbgcol.tag = 'fgbgcol'; fgbgcol.num = [1 3]; fgbgcol.def = 'tools.vgtbx_Diffusion.dti_disp_grad.fgbgcol'; res.def = 'tools.vgtbx_Diffusion.dti_disp_grad.res'; option.type = 'menu'; option.name = 'Information to display'; option.tag = 'option'; option.labels = {'Gradient vectors',... 'Direction distribution',... 'Both'}; option.values = {'v','d','vd'}; disp_grad.type = 'branch'; disp_grad.name = 'Display gradient directions'; disp_grad.tag = 'dti_disp_grad'; disp_grad.val = {srcimgs option axbgcol fgbgcol res}; disp_grad.prog = @dti_disp_grad; disp_grad.help = vgtbx_help2cell('dti_disp_grad'); %-Helpers %======================================================================= refimage.type = 'const'; refimage.name = 'Image'; refimage.tag = 'refimage'; refimage.val = {1}; refscanner.type = 'const'; refscanner.name = 'Scanner'; refscanner.tag = 'refscanner'; refscanner.val = {1}; refsnparams = snparams; refsnparams.name = 'Normalised'; refsnparams.num = [1 1]; ref.type = 'choice'; ref.name = 'Reference coordinate system'; ref.tag = 'ref'; ref.values = {refimage, refscanner, refsnparams}; saveinf.type = 'menu'; saveinf.name = 'Save gradient information to .txt file'; saveinf.tag = 'saveinf'; saveinf.labels = {'Yes','No'}; saveinf.values = {1,0}; saveinf.def = 'tools.vgtbx_Diffusion.extract_dirs.saveinf'; extract_dirs.type = 'branch'; extract_dirs.name = 'Extract DW information (gradients & dirs)'; extract_dirs.tag = 'dti_extract_dirs'; extract_dirs.val = {srcimgs ref saveinf sep ltol dtol}; extract_dirs.prog = @dti_extract_dirs; extract_dirs.help = vgtbx_help2cell('dti_extract_dirs'); %-Simulations %======================================================================= % Simulate tensors %----------------------------------------------------------------------- lina.type = 'entry'; lina.name = 'Line slope'; lina.tag = 'a'; lina.strtype = 'e'; lina.num = [Inf Inf]; lina.def = 'tools.vgtbx_Diffusion.dti_dw_generate.a'; lina.help = {['The interpretation of this parameter varies with its ' ... 'size. It can be'], ... ['1-by-1, 1-by-size(t,2): one line, with possibly changing ' ... 'parameter value over the line.'], ... ['M-by-1, M-by-size(t,2): multiple lines with different ' ... 'settings of this parameter. All combinations of all ' ... 'parameters of the line function will be computed.']}; amp.type = 'entry'; amp.name = 'Amplitude'; amp.tag = 'r'; amp.strtype = 'e'; amp.num = [Inf Inf]; amp.def = 'tools.vgtbx_Diffusion.dti_dw_generate.r'; amp.help = {['The interpretation of this parameter varies with its ' ... 'size. It can be'], ... ['1-by-1, 1-by-size(t,2): one line, with possibly changing ' ... 'parameter value over the line.'], ... ['M-by-1, M-by-size(t,2): multiple lines with different ' ... 'settings of this parameter. All combinations of all ' ... 'parameters of the line function will be computed.']}; freq.type = 'entry'; freq.name = 'Frequency'; freq.tag = 'f'; freq.strtype = 'e'; freq.num = [Inf Inf]; freq.def = 'tools.vgtbx_Diffusion.dti_dw_generate.f'; freq.help = {['The interpretation of this parameter varies with its ' ... 'size. It can be'], ... ['1-by-1, 1-by-size(t,2): one line, with possibly changing ' ... 'parameter value over the line.'], ... ['M-by-1, M-by-size(t,2): multiple lines with different ' ... 'settings of this parameter. All combinations of all ' ... 'parameters of the line function will be computed.']}; phase.type = 'entry'; phase.name = 'Phase'; phase.tag = 'ph'; phase.strtype = 'e'; phase.num = [Inf Inf]; phase.def = 'tools.vgtbx_Diffusion.dti_dw_generate.ph'; phase.help = {['The interpretation of this parameter varies with its ' ... 'size. It can be'], ... ['1-by-1, 1-by-size(t,2): one line, with possibly changing ' ... 'parameter value over the line.'], ... ['M-by-1, M-by-size(t,2): multiple lines with different ' ... 'settings of this parameter. All combinations of all ' ... 'parameters of the line function will be computed.']}; offset.type = 'entry'; offset.name = 'Offset'; offset.tag = 'off'; offset.strtype = 'e'; offset.num = [Inf Inf]; offset.def = 'tools.vgtbx_Diffusion.dti_dw_generate.off'; offset.help = {['The interpretation of this parameter varies with its ' ... 'size. It can be'], ... ['1-by-1, 1-by-size(t,2): one line, with possibly changing ' ... 'parameter value over the line.'], ... ['M-by-1, M-by-size(t,2): multiple lines with different ' ... 'settings of this parameter. All combinations of all ' ... 'parameters of the line function will be computed.']}; linear.type = 'branch'; linear.tag = 'linear'; linear.name = 'Linear: f(t) = a*t + off'; linear. val = {lina,offset}; tanhp.type = 'branch'; tanhp.tag = 'tanhp'; tanhp.name = 'Tanh: f(t) = tanh(f*t + ph) + off'; tanhp. val = {amp, freq, phase, offset}; sinp.type = 'branch'; sinp.tag = 'sinp'; sinp.name = 'Sin: f(t) = sin(f*t + ph) + off'; sinp. val = {amp, freq, phase, offset}; data.type = 'entry'; data.name = 'Coordinate points'; data.tag = 'data'; data.strtype = 'e'; data.num = [Inf Inf]; data.help = {'A #lines-by-size(t,2) array of data points.'}; ffun.type = 'choice'; ffun.values = {data,linear,tanhp,sinp}; ffun.help = {['Specification of fibers. Each fiber is parameterised by ' ... 'three functions x(t), y(t) and z(t). All combinations of ' ... 'x-, y- and z-line functions are computed.']}; fxfun = ffun; fxfun.name = 'Line function (X)'; fxfun.tag = 'fxfun'; fyfun = ffun; fyfun.name = 'Line function (Y)'; fyfun.tag = 'fyfun'; fzfun = ffun; fzfun.name = 'Line function (Z)'; fzfun.tag = 'fzfun'; t.type = 'entry'; t.name = 'Parametrisation points for line'; t.tag = 't'; t.strtype = 'e'; t.num = [1 Inf]; t.def = 'tools.vgtbx_Diffusion.dti_dw_generate.t'; iso.type = 'entry'; iso.name = 'Ratio of isotropic diffusion'; iso.tag = 'iso'; iso.strtype = 'e'; iso.num = [1 1]; iso.def = 'tools.vgtbx_Diffusion.dti_dw_generate.iso'; fwhm.type = 'entry'; fwhm.name = 'Exponential decay of non-isotropic diffusion'; fwhm.tag = 'fwhm'; fwhm.strtype = 'e'; fwhm.num = [1 1]; fwhm.def = 'tools.vgtbx_Diffusion.dti_dw_generate.fwhm'; D.type = 'entry'; D.name = 'Diffusion coefficient'; D.tag = 'D'; D.strtype = 'e'; D.num = [1 1]; D.def = 'tools.vgtbx_Diffusion.dti_dw_generate.D'; lines.type = 'branch'; lines.name = 'Line specification'; lines.tag = 'lines'; lines.val = {fxfun fyfun fzfun t iso fwhm D}; alllines.type = 'repeat'; alllines.name = 'Line specifications'; alllines.tag = 'alllines'; alllines.num = [1 Inf]; alllines.values = {lines}; fname = prefix; dim.type = 'entry'; dim.name = 'Output image dimensions'; dim.tag = 'dim'; dim.strtype = 'n'; dim.num = [1 3]; dim.def = 'tools.vgtbx_Diffusion.dti_dw_generate.dim'; res.def = 'tools.vgtbx_Diffusion.dti_dw_generate.res'; movprms.type = 'entry'; movprms.name = 'Movement parameters'; movprms.tag = 'movprms'; movprms.strtype = 'e'; movprms.num = [Inf 6]; movprms.def = 'tools.vgtbx_Diffusion.dti_dw_generate.movprms'; movprms.help = {['Enter a 1-by-6 or #directions-by-6 array of movement ' ... 'parameters to simulate phantom movement. Images will '... 'be simulated in transversal orientation, but the ' ... 'phantom may move in and out the initial bounding ' ... 'box.']}; b.type = 'entry'; b.name = 'B value'; b.tag = 'b'; b.strtype = 'e'; b.num = [1 1]; b.def = 'tools.vgtbx_Diffusion.dti_dw_generate.b'; i0.type = 'entry'; i0.name = 'B0 intensity'; i0.tag = 'i0'; i0.strtype = 'e'; i0.num = [1 1]; i0.def = 'tools.vgtbx_Diffusion.dti_dw_generate.i0'; nr.type = 'entry'; nr.name = 'B0 noise ratio'; nr.tag = 'nr'; nr.strtype = 'e'; nr.num = [1 1]; nr.def = 'tools.vgtbx_Diffusion.dti_dw_generate.nr'; dw_generate.type = 'branch'; dw_generate.name = 'Generate diffusion weighted images'; dw_generate.tag = 'dti_dw_generate'; dw_generate.val = {alllines fname swd dim res movprms b i0 nr}; dw_generate.prog = @dti_dw_generate; dw_generate.vfiles = dti_dw_generate('vfiles'); dw_generate.help = vgtbx_help2cell('dti_dw_generate'); %-Main menu level %======================================================================= opt.type = 'repeat'; opt.name = 'Diffusion toolbox'; opt.tag = 'vgtbx_Diffusion'; opt.values = {init_dti_data realign reorient_gradient adc dt_adc dt_regress ... warp_tensors dt_eig indices saliencies disp_grad extract_dirs hosvd recalc ... dw_generate dt_time3 dt_tracepath}; opt.num = [0 Inf]; opt.help = vgtbx_help2cell(mfilename); %-Add defaults %======================================================================= global defaults; % Nearest Neighbour interpolation %----------------------------------------------------------------------- defaults.tools.vgtbx_Diffusion.interp = 0; defaults.tools.vgtbx_Diffusion.extract_dirs.saveinf = 0; defaults.tools.vgtbx_Diffusion.extract_dirs.sep = 1; defaults.tools.vgtbx_Diffusion.extract_dirs.ltol = 10; defaults.tools.vgtbx_Diffusion.extract_dirs.dtol = .95; defaults.tools.vgtbx_Diffusion.dti_dt_regress.sep = 0; defaults.tools.vgtbx_Diffusion.dti_dt_regress.ltol = 10; defaults.tools.vgtbx_Diffusion.dti_dt_regress.dtol = 0; defaults.tools.vgtbx_Diffusion.dti_dt_regress.spatsm = 0; defaults.tools.vgtbx_Diffusion.dti_disp_grad.axbgcol = [0 0 0]; defaults.tools.vgtbx_Diffusion.dti_disp_grad.fgbgcol = [.2 .2 .2]; defaults.tools.vgtbx_Diffusion.dti_disp_grad.res = 100; defaults.tools.vgtbx_Diffusion.dti_dw_generate.dim = [Inf Inf Inf]; defaults.tools.vgtbx_Diffusion.dti_dw_generate.res = .2; defaults.tools.vgtbx_Diffusion.dti_dw_generate.movprms = [0 0 0 0 0 0]; defaults.tools.vgtbx_Diffusion.dti_dw_generate.b = 750; defaults.tools.vgtbx_Diffusion.dti_dw_generate.i0 = 400; defaults.tools.vgtbx_Diffusion.dti_dw_generate.D = 4e-3; defaults.tools.vgtbx_Diffusion.dti_dw_generate.nr = .1; defaults.tools.vgtbx_Diffusion.dti_dw_generate.t = 1:10; defaults.tools.vgtbx_Diffusion.dti_dw_generate.iso = .1; defaults.tools.vgtbx_Diffusion.dti_dw_generate.fwhm= 3; defaults.tools.vgtbx_Diffusion.dti_dw_generate.a = 0; defaults.tools.vgtbx_Diffusion.dti_dw_generate.r = 1; defaults.tools.vgtbx_Diffusion.dti_dw_generate.f = 1; defaults.tools.vgtbx_Diffusion.dti_dw_generate.ph = 0; defaults.tools.vgtbx_Diffusion.dti_dw_generate.off = 0; defaults.tools.vgtbx_Diffusion.dti_reorient_gradient.useaff.rot = 1; defaults.tools.vgtbx_Diffusion.dti_reorient_gradient.useaff.zoom = 1; defaults.tools.vgtbx_Diffusion.dti_reorient_gradient.useaff.shear = 0; if nargout > 0 varargout{1}=opt; end; % vfiles functions %======================================================================= function vfiles = vfiles_dti_classify(job) vfiles={}; if ~isempty(job.e1img) [p n e v] = fileparts(job.e1img{1}); vfiles{1} = fullfile(p, [job.prefix n e v]); end; function vfiles = vfiles_dti_compare(job) vfiles={}; if ~isempty(job.dtimg) [p n e v] = fileparts(job.dtimg{1}); for k = 1:6 vfiles{k} = fullfile(p,[job.prefix sprintf('%02d_',k+3) n e v]); end; end; function vfiles = vfiles_dti_evec_rot(job) vfiles={}; for k = 1:numel(job.e1img) [p n e v] = fileparts(job.e1img{k}); vfiles{k} = fullfile(p, ['adc_' n e v]); end; function vfiles = vfiles_dti_adc(job) vfiles={}; for k = 1:numel(job.files1) [p n e v] = fileparts(job.files1{k}); vfiles{k} = fullfile(p, ['adc_' n e v]); end; function vfiles = vfiles_dti_dt_adc(job) vfiles={}; if ~isempty(job.files) [p n e v]=fileparts(job.files{1}); if n(1:4) == 'adc_' n=n(5:end); end; dirs={'xx','xy','xz','yy','yz','zz'}; for k=1:6 vfiles{k} = fullfile(p, sprintf('D%s_%s%s%s',dirs{k}, n, e, v)); end; end; function vfiles = vfiles_dti_reorient_gradient(job) vfiles = job.tgtimgs; function vfiles = vfiles_dti_dt_regress(job) persistent dtorder Hind mult fdirs vfiles=cell(1,(job.dtorder+1)*(job.dtorder+2)/2+1); cswd = spm_select('cpath',job.swd{1}); vfiles{end}=fullfile(cswd,'SPM.mat'); % get beta filename stub [p betafname e v] = fileparts(job.srcimgs{1}); if isempty(dtorder) || (dtorder ~= job.dtorder) dirs = 'xyz'; [Hind mult] = dti_dt_order(job.dtorder); dtorder = job.dtorder; for j=1:(job.dtorder+1)*(job.dtorder+2)/2 fdirs{j}=dirs(Hind(:,j)); end; end; for j=1:(job.dtorder+1)*(job.dtorder+2)/2 vfiles{j}=fullfile(cswd,... sprintf('D%s_%s.img,1',... fdirs{j},betafname)); end; % mean regressor included by spm_config_factorial design.m vfiles{end+1} = fullfile(cswd,sprintf('lnA0_%s.img,1', betafname)); function vfiles = vfiles_dti_eig(job) vfiles={}; [p n e v]=fileparts(job.dtimg{1}); if ~isempty(regexp(n,'^((dt[1-6])|(D[x-z][x-z]))_.*')) n = n(5:end); end; cdir=['x','y','z']; if any (job.dteigopts=='v') for j=1:3 for k=1:3 vfiles{end+1} = ... fullfile(p, ... [sprintf('evec%d%s_',k,cdir(j)) n e v]); end; end; end; if any(job.dteigopts=='l') for j=1:3 vfiles{end+1} = fullfile(p,[sprintf('eval%d_',j) n e v]); end; end; if any(job.dteigopts=='a') for j=1:3 vfiles{end+1} = fullfile(p,[sprintf('euler%d_',j) n e v]); end; end; function vfiles = vfiles_dti_indices(job) vfiles={}; [p n e v]=fileparts(job.dtimg{1}); if ~isempty(regexp(n,'^((dt[1-6])|(D[x-z][x-z]))_.*')) n = n(5:end); end; if any (job.option=='f') vfiles{end+1} = fullfile(p,['fa_' n e v]); end; if any (job.option=='v') vfiles{end+1} = fullfile(p,['va_' n e v]); end; if any (job.option=='d') vfiles{end+1} = fullfile(p,['ad_' n e v]); end; function vfiles = vfiles_dti_saliencies(job) [p n e v]=fileparts(job.limg{1}); if length(n)>6 & n(1:4) == 'eval' n=n(7:end); end; vfiles{1} = fullfile(p,['sc_' n e v]); vfiles{2} = fullfile(p,['sp_' n e v]); vfiles{3} = fullfile(p,['ss_' n e v]); function vfiles = vfiles_dti_hosvd(job) vfiles = {}; for k=1:numel(job.dtimg) [p n e v] = fileparts(job.dtimg{k}); if n(1)=='D' n(1)='S'; else n = ['S' n]; end; vfiles{end+1} = fullfile(p, [n e v]); end; [p n e v] = fileparts(job.dtimg{1}); if ~isempty(regexp(n, sprintf('^D%s_.*', repmat('[x-z]',1,job.dtorder)))) n = n(job.dtorder+2:end); end; for k=1:3 for l=1:3 vfiles{end+1} = fullfile(p, [sprintf('U%d%s_%s',l,dirs(k),n) e v]); end; end; function vfiles = vfiles_dti_dt_time3(job) vfiles = {}; return; % Currently unused function str = check_dti_reorient_gradient(job) if numel(job.srcimgs) ~= numel(job.tgtimgs) str = '# source images must match # target images.'; else str = ''; end; return;
github
philippboehmsturm/antx-master
dti_warp_tensors.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Preprocessing/dti_warp_tensors.m
16,258
utf_8
a6a5a358bf12126d9b28e14f63b80ff1
function varargout=dti_warp_tensors(bch) % Apply image reorientation information to diffusion gradients % % Batch processing: % FORMAT dti_warp_tensors(bch) % ====== % Input argument % bch struct with fields: %/*\begin{description}*/ %/*\item[*/ .srcimgs/*]*/ cell array of file names (tensor images % computed from normalised images) %/*\item[*/ .snparams/*]*/ optional normalisation parameters file used to % write the images normalised. %/*\end{description}*/ % This function is part of the diffusion toolbox for SPM5. For general % help about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id: dti_warp_tensors.m 712 2010-06-30 14:20:19Z glauche $ rev = '$Revision: 712 $'; funcname = 'Warp tensors'; % function preliminaries Finter=spm_figure('GetWin','Interactive'); spm_input('!DeleteInputObj'); Finter=spm('FigName',funcname,Finter); SPMid = spm('FnBanner',mfilename,rev); % function code starts here V = spm_vol(char(dti_fileorder(bch.dtimg))); dti_write_sn(V,bch.snparams{1}); function VO = dti_write_sn(V,prm,flags,extras) % Write Out Warped Images. % FORMAT VO = dti_write_sn(V,prm,flags,msk) % V - Images to transform (filenames or volume structure). % matname - 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. This field is present for % compatibility with spm_write_sn, but will be % ignored. % 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 = dti_write_sn(V,prm,flags,'mask') % V - Images to transform (filenames or volume structure). % matname - 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. %_______________________________________________________________________ % Copyright (C) 2005 Wellcome Department of Imaging Neuroscience % John Ashburner % $Id: dti_warp_tensors.m 712 2010-06-30 14:20:19Z glauche $ if isempty(V), return; end; if ischar(prm), prm = load(prm); end; if ischar(V), V = spm_vol(V); end; def_flags = struct('interp',1,'vox',NaN,'bb',NaN,'wrap',[0 0 0],'preserve',0); [def_flags.bb, def_flags.vox] = bbvox_from_V(prm.VG(1)); 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; % Voxel size and bounding box from images flags.vox = sqrt(sum(V(1).mat(1:3,1:3).^2)); bbtmp = V(1).mat*[1 1 1 1; V(1).dim(1:3) 1]'; flags.bb = bbtmp(1:3,:)'; [x,y,z,mat] = get_xyzmat(prm,flags.bb,flags.vox); msk = []; % unused 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) VO = []; warning('Please use copy/reorient diffusion information for this task.'); return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = nonlin_transform(V,prm,x,y,z,mat,flags,msk) 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); % need jacobian matrix for local transformations 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'); spm_progress_bar('Init',V(1).dim(3),'Resampling','planes completed'); for i=1:numel(V), VO(i) = make_hdr_struct(V(i),x,y,z,mat); if nargout>0, %Dat= zeros(VO.dim(1:3)); Dat{i} = single(0); Dat{i}(VO.dim(1),VO.dim(2),VO.dim(3)) = 0; else VO(i) = spm_create_vol(VO(i)); end; end % matrices used in loop %---------------------------------------------------------------------------- J = zeros([V(1).dim(1:2),3,3]); isj = zeros([V(1).dim(1:2),6]); D = zeros([V(1).dim(1:2),6]); R11 = zeros(V(1).dim(1:2)); R12 = zeros(V(1).dim(1:2)); R13 = zeros(V(1).dim(1:2)); R21 = zeros(V(1).dim(1:2)); R22 = zeros(V(1).dim(1:2)); R23 = zeros(V(1).dim(1:2)); DR = zeros(V(1).dim(1:2)); 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; % as opposed to the original code, we need the inverse rotation to % compensate normalisation. This is equal to rotation with M' % (M'*D*M) instead of M (M*D*M') and needs indexing of j. Therefore % we use an indexed m-by-n-by-3,3 array instead of 9 individual variables J(:,:,1,1) = DX*tx*BY' + 1; J(:,:,1,2) = BX*tx*DY'; J(:,:,1,3) = BX*get_2Dtrans(Tr(:,:,:,1),DZ,j)*BY'; J(:,:,2,1) = DX*ty*BY'; J(:,:,2,2) = BX*ty*DY' + 1; J(:,:,2,3) = BX*get_2Dtrans(Tr(:,:,:,2),DZ,j)*BY'; J(:,:,3,1) = DX*tz*BY'; J(:,:,3,2) = BX*tz*DY'; J(:,:,3,3) = BX*get_2Dtrans(Tr(:,:,:,3),DZ,j)*BY' + 1; % brute force method to compute finite strain rotation matrix and % rotated tensors %---------------------------------------------------------------------------- % M = inv(sqrtm(J*J'))*J; % J*J'; jjt11=J(:,:,1,1).^2 +J(:,:,1,2).^2 +J(:,:,1,3).^2; jjt21=J(:,:,2,1).*J(:,:,1,1)+J(:,:,2,2).*J(:,:,1,2)+J(:,:,2,3).*J(:,:,1,3); jjt22=J(:,:,2,1).^2 +J(:,:,2,2).^2 +J(:,:,2,3).^2; jjt31=J(:,:,3,1).*J(:,:,1,1)+J(:,:,3,2).*J(:,:,1,2)+J(:,:,3,3).*J(:,:,1,3); jjt32=J(:,:,3,1).*J(:,:,2,1)+J(:,:,3,2).*J(:,:,2,2)+J(:,:,3,3).*J(:,:,2,3); jjt33=J(:,:,3,1).^2+J(:,:,3,2).^2+J(:,:,3,3).^2; % inv(sqrtm) for k=1:V(1).dim(1) for l=1:V(1).dim(2) tmp = inv(sqrtm([jjt11(k,l) jjt21(k,l) jjt31(k,l); ... jjt21(k,l) jjt22(k,l) jjt32(k,l); ... jjt31(k,l) jjt32(k,l) jjt33(k,l)])); isj(k,l,1)=tmp(1,1); isj(k,l,2)=tmp(2,1); isj(k,l,4)=tmp(2,2); isj(k,l,3)=tmp(3,1); isj(k,l,5)=tmp(3,2); isj(k,l,6)=tmp(3,3); end; end; % read tensors into matrix %---------------------------------------------------------------------------- B = inv(spm_matrix([0 0 -j 0 0 0 1 1 1])); for k=1:6 D(:,:,k)=spm_slice_vol(V(k),B,V(1).dim(1:2),0); end; % rotate tensors %---------------------------------------------------------------------------- % if there is an parameterisation for M that allows to estimate % rotations without inversion and sqrtm, then an vectorised scheme % for rotation could be used: % DR_{ij} = vec(M_{i.} x M'_{j.}) * [D_xx; Dxy; D_xz; ... D_zz] % % where the vec(M) lines can be stacked to yield DR_xx...DR_zz and % the entire process can be reordered into sparse matrix form for rotation of an % entire plane like this % [DR_{xx1}; ... DR_{xxN}; DR_{xy1}; DR_{xyN};...] = % [spdiags(M_{xx}.^2) spdiags(M_{xx}.*M_{yy}+M_{xy}.*M_{yx}...)] % *[D_{xx1};...D_{xxN}; D_{xy1}...D_{xyN}] % % This is for rotation in the J direction % % R = [isj(:,1).*j11+isj(:,2).*j21+isj(:,3).*j31 isj(:,1).*j12+isj(:,2).*j22+isj(:,3).*j32 isj(:,1).*j13+isj(:,2).*j23+isj(:,3).*j33 % % isj(:,2).*j11+isj(:,4).*j21+isj(:,5).*j31 isj(:,2).*j12+isj(:,4).*j22+isj(:,5).*j32 isj(:,2).*j13+isj(:,4).*j23+isj(:,5).*j33 % % isj(:,3).*j11+isj(:,5).*j21+isj(:,6).*j31 isj(:,3).*j12+isj(:,5).*j22+isj(:,6).*j32 isj(:,3).*j13+isj(:,5).*j23+isj(:,6).*j33] % % % M.. = [R.1*R.1 R.1*R.2+R.2*R.1 R.1*R.3+R.3*R.1 R.2*R.2 R.2*R.3+R.3*R.2 R.3*R.3] % % wobei M21 = M12, M31=M13, M32=M23 wegen Tensorsymmetrie % ri = [1 2 3 1 2 3; ... % xx % 1 2 3 2 4 5; ... % xy % 1 2 3 3 5 6; ... % xz % 2 4 5 2 4 5; ... % yy % 2 4 5 3 5 6; ... % yz % 3 5 6 3 5 6]; % zz % inverse rotation means rotation with R' % R = [isj(:,1).*j11+isj(:,2).*j21+isj(:,3).*j31 isj(:,2).*j11+isj(:,4).*j21+isj(:,5).*j31 isj(:,3).*j11+isj(:,5).*j12+isj(:,6).*j13 % isj(:,1).*j12+isj(:,2).*j22+isj(:,3).*j32 isj(:,2).*j12+isj(:,4).*j22+isj(:,5).*j32 isj(:,3).*j12+isj(:,5).*j22+isj(:,6).*j33 % isj(:,1).*j13+isj(:,2).*j23+isj(:,3).*j33 isj(:,2).*j13+isj(:,4).*j23+isj(:,5).*j33 isj(:,3).*j13+isj(:,5).*j23+isj(:,6).*j33] rj = [1 1;... 1 2;... 1 3;... 2 2;... 2 3;... 3 3]; for k=1:6 % % rotation about R % R11 = isj(:,:,ri(k,1)).*j11+isj(:,:,ri(k,2)).*j21+isj(:,:,ri(k,3)).*j31; % R12 = isj(:,:,ri(k,1)).*j12+isj(:,:,ri(k,2)).*j22+isj(:,:,ri(k,3)).*j32; % R13 = isj(:,:,ri(k,1)).*j13+isj(:,:,ri(k,2)).*j23+isj(:,:,ri(k,3)).*j33; % R21 = isj(:,:,ri(k,4)).*j11+isj(:,:,ri(k,5)).*j21+isj(:,:,ri(k,6)).*j31; % R22 = isj(:,:,ri(k,4)).*j12+isj(:,:,ri(k,5)).*j22+isj(:,:,ri(k,6)).*j32; % R23 = isj(:,:,ri(k,4)).*j13+isj(:,:,ri(k,5)).*j23+isj(:,:,ri(k,6)).*j33; % rotation about R' R11 = isj(:,:,1).*J(:,:,1,rj(k,1))+isj(:,:,2).*J(:,:,2,rj(k,1))+isj(:,:,3).*J(:,:,3,rj(k,1)); R12 = isj(:,:,2).*J(:,:,1,rj(k,1))+isj(:,:,4).*J(:,:,2,rj(k,1))+isj(:,:,5).*J(:,:,3,rj(k,1)); R13 = isj(:,:,3).*J(:,:,1,rj(k,1))+isj(:,:,5).*J(:,:,2,rj(k,1))+isj(:,:,6).*J(:,:,3,rj(k,1)); R21 = isj(:,:,1).*J(:,:,1,rj(k,2))+isj(:,:,2).*J(:,:,2,rj(k,2))+isj(:,:,3).*J(:,:,3,rj(k,2)); R22 = isj(:,:,2).*J(:,:,1,rj(k,2))+isj(:,:,4).*J(:,:,2,rj(k,2))+isj(:,:,5).*J(:,:,3,rj(k,2)); R23 = isj(:,:,3).*J(:,:,1,rj(k,2))+isj(:,:,5).*J(:,:,2,rj(k,2))+isj(:,:,6).*J(:,:,3,rj(k,2)); DR = R11 .* R21 .* D(:,:,1) + ... (R11 .* R22 + R12 .* R21) .* D(:,:,2) + ... (R11 .* R23 + R13 .* R21) .* D(:,:,3) + ... R12 .* R22 .* D(:,:,4) + ... (R12 .* R23 + R13 .* R22) .* D(:,:,5) + ... R13 .* R23 .* D(:,:,6); VO(k) = spm_write_plane(VO(k), DR, j); end; spm_progress_bar('Set',j); end; spm_progress_bar('Clear'); return; %_______________________________________________________________________ %_______________________________________________________________________ function VO = make_hdr_struct(V,x,y,z,mat) VO = V; VO.fname = prepend(V.fname,'W2'); VO.mat = mat; VO.dim(1:3) = [length(x) length(y) length(z)]; VO.pinfo(3,1) = 0; 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,[nm(1:3) pre nm(4:end) xt vr]); 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 [bb,vx] = bbvox_from_V(V) vx = sqrt(sum(V.mat(1:3,1:3).^2)); if det(V.mat(1:3,1:3))<0, vx(1) = -vx(1); end; o = V.mat\[0 0 0 1]'; o = o(1:3)'; bb = [-vx.*(o-1) ; vx.*(V.dim(1:3)-o)]; return; %_______________________________________________________________________ %_______________________________________________________________________ function [x,y,z,mat] = get_xyzmat(prm,bb,vox) % 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); 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. I chose not to change it because % it would lead to being bombarded by questions about spatially % normalised images not having the same dimensions. 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/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;
github
philippboehmsturm/antx-master
spm_coreg_FAVBS.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/FAVBS/spm_coreg_FAVBS.m
4,853
utf_8
89628eae19d61819bd45464fb3e8db4c
function spm_coreg_FAVBS(PF,FA_on,opt) % modified version of spm_coreg_ui.m % Volkmar Glauche and Siawoosh Mohammadi 10/01/09 %%% begin modification %%% spm_defaults global defaults % if nargin==2 | strcmp(lower(opt),'ui'), % run_ui(PF,FA_on,defaults.coreg); % elseif nargin>0 & strcmp(lower(opt),'defaults'), % defaults.coreg = get_defs(defaults.coreg); % end; % return; % % function run_ui(PF,FA_on,flags) SPMid = spm('FnBanner',mfilename,'2.10'); [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Coregister'); spm_help('!ContextHelp',mfilename); %%% end modification %%% %%% begin modification %%% % % get number of subjects % nsubjects = spm_input('number of subjects',1, 'e', 1); % if nsubjects < 1, % spm_figure('Clear','Interactive'); % return; % end; %%setting defaults %12 params defaults.coreg.estimate.params = [0 0 0 0 0 0 1 1 1 0 0 0]; defaults.coreg.estimate.tol = [0.02 0.02 0.02 0.001 0.001 0.001 0.01 0.01 0.01 0.001 0.001 0.001]; % %9 params: % defaults.coreg.estimate.params = [0 0 0 0 0 0 1 1 1] % defaults.coreg.estimate.tol = [0.02 0.02 0.02 0.001 0.001 0.001 0.01 0.01 0.01]; % %6-paras: % defaults.coreg.estimate.params = [0 0 0 0 0 0]; % defaults.coreg.estimate.tol = [0.02 0.02 0.02 0.001 0.001 0.001]; defaults.coreg.estimate.cost_fun = 'nmi'; defaults.coreg.estimate.sep = [4 2]; defaults.coreg.estimate.fwhm = [7 7]; p = 3; % p = spm_input('Which option?',2,'m',... % 'Coregister only|Reslice Only|Coregister & Reslice', [1 2 3],3); if p == 1 || p == 3, % for i = 1:nsubjects, mireg = struct('VG',[],'VF',[],'PO',''); % select target(s) % PG = spm_get(1,'IMAGE', ['Target image']); PG = spm_get('Files','C:\Programme\MATLAB71\spm2\templates',['EPI.mnc']); mireg.VG = spm_vol(PG); % select source(s) % PF = spm_get(Inf,'IMAGE', ['Source images']); mireg.VF = spm_vol(PF); mireg.PO = PF; % PO = spm_get(Inf,'IMAGE', ['Other images, subj ' num2str(i)]); % if isempty(PO), % mireg(i).PO = PF; % else, % mireg(i).PO = strvcat(PF,PO); % end; % end; end; sz=size(PF,1); % if p==2, % for i = 1:nsubjects, % mireg(i) = struct('VG',[],'VF',[],'PO',[]); % % % select target space % PG = spm_get(1,'IMAGE', ['Space defining image, subj ' num2str(i)]); % mireg(i).VG = spm_vol(PG); % % PO = spm_get(Inf,'IMAGE', ['Images to reslice, subj ' num2str(i)]); % mireg(i).PO = PO; % end; % end; % For each subject, call the program to perform the registration. %----------------------------------------------------------------------- spm('Pointer','Watch') for i=1:sz, if p == 1 || p == 3, spm('FigName',['Coregister subj ' num2str(i)],Finter,CmdLine); x = spm_coreg(mireg.VG, mireg.VF(i),defaults.coreg.estimate); M = inv(SM_matrix(x)); MM = zeros(4,4,size(mireg.PO,1)); for j=i:i, MM(:,:,j) = spm_get_space(deblank(mireg.PO(j,:))); end; for j=i:i, spm_get_space(deblank(mireg.PO(j,:)), M*MM(:,:,j)); end; end; if p == 2 || p == 3, spm('FigName',['Reslice subj ' num2str(i)],Finter,CmdLine); fprintf('Reslicing Subject %d\n', i); P = char(mireg.VG.fname,mireg.PO(i,:)); flg = defaults.coreg.write; flg.mean = 0; flg.which = 1; flg.mean = 0; spm_reslice(P,flg); end; end; %%% end modification %%% spm('FigName','Coregister: done',Finter,CmdLine); spm('Pointer'); return; function defs = get_defs(defs) fun = defs.estimate.cost_fun; funs={'mi','ecc','nmi','ncc'}; sel = 1; for i=1:length(funs), if strcmpi(funs{i},fun), sel = i; break; end; end; defs.estimate.cost_fun = spm_input('Cost Function?','+1','m',[... 'Mutual Information|Entropy Correlation Coefficient|'... 'Normalised Mutual Information|Normalised Cross Correlation'],... funs,sel); defs.estimate.cost_fun = defs.estimate.cost_fun{1}; tmp2 = [0 1 2 3 4 5 6 7 Inf]; tmp = find(defs.write.interp == tmp2); if ~isfinite(defs.write.interp), tmp = 9; end; if isempty(tmp), tmp = 2; end; defs.write.interp = spm_input('Reslice interpolation method?','+1','m',... ['Nearest Neighbour|Trilinear|2nd Degree B-Spline|'... '3rd Degree B-Spline|4th Degree B-Spline|5th Degree B-Spline|'... '6th Degree B-Spline|7th Degree B-Spline|Fourier Interpolation'],... tmp2,tmp); wraps = [0 0 0 ; 1 0 0; 0 1 0; 1 1 0; 0 0 1; 1 0 1; 0 1 1; 1 1 1]; t = find(all(repmat(defs.write.wrap(:)',8,1) == wraps, 2)); if isempty(t), t = 1; end; p = spm_input('Way to wrap images?','+1','m',... ['No wrap|Wrap X|Wrap Y|Wrap X & Y|Wrap Z|Wrap X & Z|Wrap Y & Z|Wrap X, Y & Z'],... [1 2 3 4 5 6 7 8], t); defs.write.wrap = wraps(p,:); defs.estimate.wrap = defs.write.wrap; tmp = 2; if defs.write.mask == 1, tmp = 1; end; defs.write.mask = spm_input(['Mask images?'], '+1', 'm',... ' Mask images|Dont mask images', [1 0], tmp); return;
github
philippboehmsturm/antx-master
FAVBS_do_the_job.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/FAVBS/FAVBS_do_the_job.m
11,909
utf_8
dd46a423955940aab3381a7642dc51b5
function out = FAVBS_do_the_job(rVb0, rVFA, rVmean, FA_on, iter, VGstemp) % function out = FAVBS_do_the_job(rVb0, rVFA, rVmean, FA_on, iter, stemp) % function out = FAVBS_do_the_job(rVb0, rVFA, rVmean, FA_on, iter, VG) % Begin VARIABLES % rVb0 = b0 images % rVFA = FA images % rVmean = average of all DW images % FA_on = dummy for normalization contrast % iter = iteration (used for normalisation parameter selection) % stemp = dummy for template symmetrization % VG = template (in this case, no template is created) % End VARIABLES %%%%%%%%%%%%%%%%%%%%%% % TODOs: % Schnittstellen zu aufgerufenen Funktionen anpassen % rP -> rVXX % rPmean -> rVmean % (File names durch spm_vol structs ersetzen) % Wenn File names als Liste, dann als cellstr '{','}' % spm_get durch cfg_getfile('FPlist',...) ersetzen %%%%%%%%%%%%%%%%%%%%%% % step zero: creating first subject-averaged meanDW image, FA image and b0 % image if isnumeric(VGstemp) doloop=false; % false: run iterative template generation dotemplate = true; stemp = VGstemp; else doloop = true; dotemplate = false; VG = VGstemp; end if dotemplate if(FA_on==0) [p,n,e] = spm_fileparts(rVb0(1).fname); pname = fullfile(p, ['template-' num2str(0) '_b0' e]); % ->KANN NACHHER WEG? VTemplate(1) = rVb0(1); VTemplate(1).fname = pname; VTemplate(1) = spm_imcalc(rVb0, VTemplate(1), 'mean(X)', {1}); else [p,n,e] = spm_fileparts(rVmean(1).fname); mname = fullfile(p, ['Average_rmeanDWI' e]); %->KANN NACHHER WEG? VGmean = rmfield(rVmean(1),'private'); VGmean.fname = mname; VGmean = spm_imcalc(rVmean, VGmean, 'mean(X)', {1}); [p,n,e] = spm_fileparts(rVFA(1).fname); % begin: creation of brain- (FA_on==1) or left-brain mask (FA_on==2 and FA_on==3) if(FA_on==1) % VG: BMSK_average output of find_mask_meanDWI VBMSK_average = find_mask_meanDWI(VGmean); % ->HIER FEHLER!!! pname = fullfile(p, ['template-' num2str(0) '_FA' e]); % ->KANN NACHHER WEG? VTemplate(1) = rVFA(1); VTemplate(1).fname = pname; VTemplate(1) = spm_imcalc([rVFA(:); VBMSK_average], VTemplate(1), 'mean(X(1:end-1,:)).*X(end,:)', {1}); else [VrL_MSK,VrfL_MSK]= main_creat_LBMSK_iii(VGmean); % ->KANN NACHHER WEG? Lpname = fullfile(p, ['Ltemplate-' num2str(0) '_LFA' e]); % ->KANN NACHHER WEG? VLTemplate(1) = rVFA(1); VLTemplate(1).fname = Lpname; VLTemplate(1) = spm_imcalc([rVFA(:); VrL_MSK], VLTemplate(1), 'mean(X(1:end-1,:)).*X(end,:)', {1}); fLpname = fullfile(p, ['fLtemplate-' num2str(0) '_LFA' e]); % ->KANN NACHHER WEG? VfLTemplate(1) = rVFA(1); VfLTemplate(1).fname = fLpname; VfLTemplate(1) = spm_imcalc([rVFA(:); VrfL_MSK], VfLTemplate(1), 'mean(X(1:end-1,:)).*X(end,:)', {1}); end end % begin: symmetrization if(FA_on==0 || FA_on==1) if (stemp==1) [p,n,e] = spm_fileparts(VTemplate(1).fname); VfTemplate = VTemplate(1); VfTemplate.mat = diag([-1 1 1 1])*VTemplate(1).mat; Average_wP = fullfile(p, [n '_sym' e]); VsTemplate(1) = VTemplate(1); VsTemplate(1).fname = Average_wP; VsTemplate(1) = spm_imcalc([VTemplate(1) VfTemplate], VsTemplate(1), '(i1+i2)/2'); VG = VsTemplate(1); clear p n e; else % no symmetrization of template VG = VTemplate(1); end else [p,n,e] = spm_fileparts(VLTemplate(1).fname); VsTemplate(1) = VLTemplate(1); Average_wP = fullfile(p, [n '_sym' e]); VsTemplate(1).fname = Average_wP; VsTemplate(1) = spm_imcalc([VLTemplate(1) VfLTemplate(1)], VsTemplate(1), '(i1+i2)/2'); VG = VsTemplate(1); clear p n e; end % end: symmetrization %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end % begin loop: k=1; % iter kann als eingabeparmeter verwendet werden. if ~exist('iter','var') iter=1; end procent_diff = 100; ddiff = 100; while(procent_diff>2 && ddiff>2), if dotemplate disp('Template generation, step:') disp(k) if(k==1) tmp_VG = VG; tmp_diff = 100; end end % normalisation switch FA_on case 0 matnames = norm_spm_FAVBS(VG,rVb0,'',FA_on,iter); case 1 matnames = norm_spm_FAVBS(VG,rVFA,rVmean,FA_on,iter); case 2 [matnames, fmatnames] = norm_spm_FAVBS(VG,rVFA,rVmean,FA_on,iter); end % begin: creating average k %%%%%%begin: write normalisation%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%5 switch FA_on case 0 [wrVb0 wrVFA wrVmean] = write_norm(rVb0,rVFA,rVmean,FA_on); case 1 [wrVFA wrVb0 wrVmean] = write_norm(rVFA,rVb0,rVmean,FA_on) ; % es wir rVb0 auch weggeschrieben!!! case 2 % keyboard [wrVFA wfrVFA] = write_norm(rVFA,'','',FA_on) ; end if dotemplate switch FA_on case 0 % b0 template [p,n,e] = spm_fileparts(rVb0(1).fname); % get the path wpname = fullfile(p, ['template-' num2str(k) '_b0' e]); VTemplate(k+1) = wrVb0(1); VTemplate(k+1).fname = wpname; VTemplate(k+1) = spm_imcalc(wrVb0, VTemplate(k+1), 'mean(X)', {1}); case 1 [p,n,e] = spm_fileparts(rVFA(1).fname); % get the path wpname = fullfile(p, ['template-' num2str(k) '_FA' e]); VTemplate(k+1) = wrVFA(1); VTemplate(k+1).fname = wpname; % weighted mean of normalised FA images VTemplate(k+1) = spm_imcalc([wrVFA(:); VBMSK_average], VTemplate(k+1), 'mean(X(1:end-1,:)).*X(end,:)', {1}); case 2 [p,n,e] = spm_fileparts(rVFA(1).fname); % get the path LMFApname = fullfile(p, ['Ltemplate-' num2str(k) '_LFA' e]); VLTemplate(k+1) = wrVFA(1); VLTemplate(k+1).fname = LMFApname; VLTemplate(k+1) = spm_imcalc([wrVFA(:); VrL_MSK], VLTemplate(k+1), 'mean(X(1:end-1,:)).*X(end,:)', {1}); fLMFApname = fullfile(p, ['fLtemplate-' num2str(k) '_LFA' e]); VfLTemplate(k+1) = wrVFA(1); VfLTemplate(k+1).fname = fLMFApname; VfLTemplate(k+1) = spm_imcalc([wfrVFA(:); VrfL_MSK], VfLTemplate(k+1), 'mean(X(1:end-1,:)).*X(end,:)', {1}); end %%%%%%%%%%%%%%%%%%%%%%end: write normalize%%%%%%%%%%%%%%%%%%%%%%%%%%%5 % begin: symmetrization if(FA_on==0 || FA_on==1) if(stemp==1) [p,n,e] = spm_fileparts(VTemplate(k+1).fname); VfTemplate = VTemplate(k+1); VfTemplate.mat = diag([-1 1 1 1])*VTemplate(k+1).mat; Average_wP = fullfile(p, [n '_sym' e]); VsTemplate(k+1) = VTemplate(k+1); VsTemplate(k+1).fname = Average_wP; VsTemplate(k+1) = spm_imcalc([VTemplate(k+1) VfTemplate], VsTemplate(k+1), '(i1+i2)/2'); VG = VsTemplate(k+1); clear p n e; else % no symmetrization of template VG = VTemplate(k+1); end else [p,n,e] = spm_fileparts(VLTemplate(k+1).fname); VsTemplate(k+1) = VLTemplate(k+1); Average_wP = fullfile(p, [n '_sym' e]); VsTemplate(k+1).fname = Average_wP; VsTemplate(k+1) = spm_imcalc([VLTemplate(k+1) VfLTemplate(k+1)], VsTemplate(k+1), '(i1+i2)/2'); VG = VsTemplate(k+1); clear p n e; end % end: symmetrization end if doloop % end while loop break; else % check the amount of difference between Average_wP and Average_rP % HIER FEHLT: DIE DATEN VORHER GLAETTEN A_tVG = spm_read_vols(tmp_VG); A_wVG = spm_read_vols(VG); msk = isfinite(A_wVG(:)) & isfinite(A_tVG(:)); procent_diff = sum((A_wVG(msk)-A_tVG(msk)).^2)/sum(A_wVG(msk).^2)*100; ddiff = tmp_diff-procent_diff; disp(procent_diff); disp(ddiff); tmp_diff = procent_diff; tmp_VG = VG; k=k+1; end clear wP wLP wfLP; end % Outputs switch FA_on case 0 out.matnames = matnames; out.wrb0names = {wrVb0.fname}; out.wrFAnames = {wrVFA.fname}; out.wrPmeans = {wrVmean.fname}; if dotemplate out.templates = {VTemplate.fname}; if(stemp==1) out.stemplates = {VsTemplate.fname}; end end case 1 out.matnames = matnames; out.wrb0names = {wrVb0.fname}; out.wrFAnames = {wrVFA.fname}; out.wrPmeans = {wrVmean.fname}; if dotemplate out.templates = {VTemplate.fname}; if(stemp==1) out.stemplates = {VsTemplate.fname}; end end case 2 out.matnames = matnames; out.fmatnames = fmatnames; out.wrFAnames = {wrVFA.fname}; out.wfrFAnames = {wfrVFA.fname}; if dotemplate out.Ltemplates = {VLTemplate.fname}; out.fLtemplates = {VfLTemplate.fname}; out.stemplates = {VsTemplate.fname}; end end % function varargout = write_norm(Vsource,Vother1,Vother2,FA_on) % Outputs: volume handles for % FA_on == 0 - wVsource (b0), wVFA, wVmean % FA_on == 1 - wVsource (FA), wVb0, wVmean % FA_on == 2 - wV, wfV % copied from write_norm.m defaults_n.write.preserve = 0; defaults_n.write.vox = [NaN NaN NaN]; defaults_n.write.bb = ones(2,3)*NaN; defaults_n.write.interp = 7; defaults_n.write.wrap = [0 0 0]; fdefaults_n = defaults_n; fdefaults_n.write.prefix = 'wf'; n=size(Vsource,1); for i=1:n, [pth,fname,ext] = fileparts(Vsource(i).fname); if(FA_on==0 || FA_on==1) matname = char(cfg_getfile('FPList',pth,['^' fname '_sn.mat'])); % get output struct from spm_write_sn % explicitly write the data to disk % remove data field from struct Vo = spm_write_sn(Vsource(i),matname,defaults_n.write); Vo = spm_write_vol(Vo, Vo.dat); varargout{1}(i) = rmfield(Vo,'dat'); Vo = spm_write_sn(Vother1(i),matname,defaults_n.write); Vo = spm_write_vol(Vo, Vo.dat); varargout{2}(i) = rmfield(Vo,'dat'); Vo = spm_write_sn(Vother2(i),matname,defaults_n.write); Vo = spm_write_vol(Vo, Vo.dat); varargout{3}(i) = rmfield(Vo,'dat'); end if(FA_on==2) matname = char(cfg_getfile('FPList',pth,['^LM-' fname '_sn.mat'])); fmatname = prepend(matname, 'f'); fV = Vsource(i); fV.mat = diag([-1 1 1 1])*Vsource(i).mat; Vo = spm_write_sn(Vsource(i),matname,defaults_n.write); Vo = spm_write_vol(Vo, Vo.dat); varargout{1}(i) = rmfield(Vo,'dat'); Vo = spm_write_sn(fV,fmatname,fdefaults_n.write); Vo = spm_write_vol(Vo, Vo.dat); varargout{2}(i) = rmfield(Vo,'dat'); end end %_______________________________________________________________________ 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
cfg_run_favbs_create_template.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/FAVBS/cfg_run_favbs_create_template.m
12,282
utf_8
1cff5a75eb5463c0b49ed9bf8d634812
function varargout = cfg_run_favbs_create_template(cmd, varargin) % Template function to implement callbacks for an cfg_exbranch. The calling % syntax is % varargout = cfg_run_favbs_create_template(cmd, varargin) % where cmd is one of % 'run' - out = cfg_run_favbs_create_template('run', job) % Run a job, and return its output argument % 'vout' - dep = cfg_run_favbs_create_template('vout', job) % Examine a job structure with all leafs present and return an % array of cfg_dep objects. % 'check' - str = cfg_run_favbs_create_template('check', subcmd, subjob) % Examine a part of a fully filled job structure. Return an empty % string if everything is ok, or a string describing the check % error. subcmd should be a string that identifies the part of % the configuration to be checked. % 'defaults' - defval = cfg_run_favbs_create_template('defaults', key) % Retrieve defaults value. key must be a sequence of dot % delimited field names into the internal def struct which is % kept in function local_def. An error is returned if no % matching field is found. % cfg_run_favbs_create_template('defaults', key, newval) % Set the specified field in the internal def struct to a new % value. % Application specific code needs to be inserted at the following places: % 'run' - main switch statement: code to compute the results, based on % a filled job % 'vout' - main switch statement: code to compute cfg_dep array, based % on a job structure that has all leafs, but not necessarily % any values filled in % 'check' - create and populate switch subcmd switchyard % 'defaults' - modify initialisation of defaults in subfunction local_defs % Callbacks can be constructed using anonymous function handles like this: % 'run' - @(job)cfg_run_favbs_create_template('run', job) % 'vout' - @(job)cfg_run_favbs_create_template('vout', job) % 'check' - @(job)cfg_run_favbs_create_template('check', 'subcmd', job) % 'defaults' - @(val)cfg_run_favbs_create_template('defaults', 'defstr', val{:}) % Note the list expansion val{:} - this is used to emulate a % varargin call in this function handle. % % This code is part of a batch job configuration system for MATLAB. See % help matlabbatch % for a general overview. %_______________________________________________________________________ % Copyright (C) 2007 Freiburg Brain Imaging % Volkmar Glauche % $Id: cfg_run_favbs_create_template.m 689 2009-11-12 10:58:57Z glauche $ rev = '$Rev: 689 $'; %#ok if ischar(cmd) switch lower(cmd) case 'run' job = local_getjob(varargin{1}); % do computation subcmd = lower(varargin{2}); rVFA = spm_vol(char(job.PFA)); % keyboard switch subcmd case 'b0' FA_on = 0; rVb0 = spm_vol(char(job.Pb0)); Vmean = spm_vol(char(job.Pmean)); case 'fa' FA_on = 1; rVb0 = spm_vol(char(job.Pb0)); Vmean = spm_vol(char(job.Pmean)); case 'lfa' rVb0 = spm_vol(''); Vmean = spm_vol(char(job.Pmean)); FA_on = 2; end % Begin: do the job if(numel(fieldnames(job))>4) if(job.citer==1) iter=1; else iter=2; end else iter=1; end if(strcmp('CT',fieldnames(job.norm.templ))) % Customized Template (CT) Generation if(strcmp('SCT',fieldnames(job.norm.templ.CT))) % Symmetrisized CT out = FAVBS_do_the_job(rVb0, rVFA, Vmean, FA_on,iter,1); elseif(strcmp('NCT',fieldnames(job.norm.templ.CT))) % Normal CT out = FAVBS_do_the_job(rVb0, rVFA, Vmean, FA_on,iter,0); end elseif(strcmp('ET',fieldnames(job.norm.templ))) % External Template (ET) if(strcmp('SC',fieldnames(job.norm.templ.ET))) % Single-Contrast (EC) VG = spm_vol(char(job.norm.templ.ET.SC.(char(fieldnames(job.norm.templ.ET.SC))))); elseif(strcmp('MC',fieldnames(job.norm.templ.ET))) % Multi-Contrast (MC) if(FA_on==0) VG = spm_vol(char(job.norm.templ.ET.MC.PGb0)); elseif(FA_on==1) VG = spm_vol(char(job.norm.templ.ET.MC.PGFA)); elseif(FA_on==2) VG = spm_vol(char(job.norm.templ.ET.MC.PGLFA)); end end out = FAVBS_do_the_job(rVb0, rVFA, Vmean, FA_on, iter, VG); end % End: do the job % return results in variable out if nargout > 0 varargout{1} = out; end case 'vout' job = local_getjob(varargin{1}); % initialise empty cfg_dep array subcmd = varargin{2}; switch lower(subcmd) case 'b0' dep(1) = cfg_dep; dep(1).sname = 'Normalisation parameters'; dep(1).src_output = substruct('.','matnames'); dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Normalised b0 images'; dep(2).src_output = substruct('.','wrb0names'); dep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(3) = cfg_dep; dep(3).sname = 'Normalised FA images'; dep(3).src_output = substruct('.','wrFAnames'); dep(3).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(4) = cfg_dep; dep(4).sname = 'Template image(s)'; dep(4).src_output = substruct('.','templates'); dep(4).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(5) = cfg_dep; dep(5).sname = 'Symmetric template image(s)'; dep(5).src_output = substruct('.','stemplates'); dep(5).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); case 'fa' dep(1) = cfg_dep; dep(1).sname = 'Normalisation parameters'; dep(1).src_output = substruct('.','matnames'); dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Normalised FA images'; dep(2).src_output = substruct('.','wrFAnames'); dep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(3) = cfg_dep; dep(3).sname = 'Template image(s)'; dep(3).src_output = substruct('.','templates'); dep(3).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(4) = cfg_dep; dep(4).sname = 'Symmetric template image(s)'; dep(4).src_output = substruct('.','stemplates'); dep(4).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); case 'lfa' dep(1) = cfg_dep; dep(1).sname = 'Normalisation parameters'; dep(1).src_output = substruct('.','matnames'); dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Normalisation parameters (flipped)'; dep(2).src_output = substruct('.','fmatnames'); dep(2).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); dep(3) = cfg_dep; dep(3).sname = 'Normalised FA images'; dep(3).src_output = substruct('.','wrFAnames'); dep(3).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(4) = cfg_dep; dep(4).sname = 'Normalised FA images (flipped)'; dep(4).src_output = substruct('.','wfrFAnames'); dep(4).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(5) = cfg_dep; dep(5).sname = 'Template image(s)'; dep(5).src_output = substruct('.','Ltemplates'); dep(5).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(6) = cfg_dep; dep(6).sname = 'Template image(s) (flipped)'; dep(6).src_output = substruct('.','fLtemplates'); dep(6).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(7) = cfg_dep; dep(7).sname = 'Symmetric template image(s)'; dep(7).src_output = substruct('.','stemplates'); dep(7).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end % determine outputs, return cfg_dep array in variable dep varargout{1} = dep; case 'check' if ischar(varargin{1}) subcmd = lower(varargin{1}); subjob = varargin{2}; str = ''; switch subcmd case 'numfiles' % subjob is a struct with file name lists. All of % them should have the same number of files. filefields = fieldnames(subjob); nfiles = numel(subjob.(filefields{1})); for k = 2:numel(filefields) if numel(subjob.(filefields{k})) ~= nfiles str = 'The number of files have to be the same for all inputs.'; break; end end % implement checks, return status string in variable str otherwise cfg_message('unknown:check', ... 'Unknown check subcmd ''%s''.', subcmd); end varargout{1} = str; else cfg_message('ischar:check', 'Subcmd must be a string.'); end case 'defaults' if nargin == 2 varargout{1} = local_defs(varargin{1}); else local_defs(varargin{1:2}); end otherwise cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd); end else cfg_message('ischar:cmd', 'Cmd must be a string.'); end function varargout = local_defs(defstr, defval) persistent defs; if isempty(defs) % initialise defaults end if ischar(defstr) % construct subscript reference struct from dot delimited tag string tags = textscan(defstr,'%s', 'delimiter','.'); subs = struct('type','.','subs',tags{1}'); try cdefval = subsref(local_def, subs); catch cdefval = []; cfg_message('defaults:noval', ... 'No matching defaults value ''%s'' found.', defstr); end if nargin == 1 varargout{1} = cdefval; else defs = subsasgn(defs, subs, defval); end else cfg_message('ischar:defstr', 'Defaults key must be a string.'); end function job = local_getjob(job) if ~isstruct(job) cfg_message('isstruct:job', 'Job must be a struct.'); end
github
philippboehmsturm/antx-master
norm_spm_FAVBS.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/FAVBS/norm_spm_FAVBS.m
6,098
utf_8
b1fd5e5b601f815b6ad0cf4b592c5322
function varargout = norm_spm_FAVBS(VG,V,rVmean,FA_on,iter) % modified version of spm_normalise.m % Output: % cell array(s) of normalisation parameter filenames % ---- % V = resliced images (FA or b0); rVmean = resliced mean % DWIs % ---- % Volkmar Glauche and Siawoosh Mohammadi 10/01/09 %spm_defaults defaults_n.estimate.smosrc = 8; defaults_n.estimate.smoref = 0; defaults_n.estimate.regtype = 'mni'; defaults_n.estimate.weight = ''; defaults_n.estimate.cutoff = 25; defaults_n.estimate.nits = 16; defaults_n.estimate.reg = 1; defaults_n.estimate.wtsrc = 0; % no mask image is used for registration n=numel(V); matname = cell(size(V)); if FA_on == 2 fmatname = cell(size(V)); end for i=1:n, if(FA_on==0) matname{i} = [spm_str_manip(V(i).fname,'sd') '_sn.mat']; if(iter==1) % %%%defaults 'rough b0' defaults_n.estimate.smosrc = 8; defaults_n.estimate.smoref = 8; defaults_n.estimate.cutoff = 25; defaults_n.estimate.nits = 16; defaults_n.estimate.reg = 1; end if(iter==2) % %%%defaults 'precise b0' defaults_n.estimate.smosrc = 6; defaults_n.estimate.smoref = 6; defaults_n.estimate.cutoff = 20; defaults_n.estimate.nits = 16; defaults_n.estimate.reg = 0.7; end spm_normalise(VG,V(i),matname{i},'','',defaults_n.estimate); end if(FA_on==1) % keyboard % HIER!!! matname{i} = [spm_str_manip(V(i).fname,'sd') '_sn.mat']; % begin: construction of brain mask [pth, fname, ext] = spm_fileparts(rVmean(i).fname); BMSK = cfg_getfile('FPlist',pth,['BMSK' '-' fname ext]); %get whole-brain mask %changed if(isempty(char(BMSK))) find_mask_meanDWI(rVmean(i)); % finds brain mask BMSK = cfg_getfile('FPlist',pth,['BMSK' '-' fname ext]); %get whole-brain mask %changed end % end: construction of brain mask VM = spm_vol(char(BMSK)); %-> VOLKMAR? % name of resliced FA images 'rFA' [p,n,e] = fileparts(V(i).fname); % construction of brain masked rFA images BMSKrFA_name = fullfile(p, ['BMSK-' n e]); VBMSKrFA_name = V(i); VBMSKrFA_name.fname = BMSKrFA_name; % Atmp = spm_read_vols(V(i)); % if(max(Atmp(:))>500) % VBMSKrFA_name = spm_imcalc([V(i) VM],VBMSKrFA_name,'i1.*i2'); % else % VBMSKrFA_name = spm_imcalc([V(i) VM],VBMSKrFA_name,'i1.*i2*1000'); % end % clear Atmp; VBMSKrFA_name = spm_imcalc([V(i) VM],VBMSKrFA_name,'i1.*i2'); if(iter==1) % %%%defaults 'rough FA' defaults_n.estimate.smosrc = 8; defaults_n.estimate.smoref = 8; defaults_n.estimate.cutoff = 25; % 20 defaults_n.estimate.nits = 16; defaults_n.estimate.reg = 1; % 1 end if(iter==2) % %%%defaults 'precise FA' defaults_n.estimate.smosrc = 6; defaults_n.estimate.smoref = 6; defaults_n.estimate.cutoff = 20; defaults_n.estimate.nits = 16; defaults_n.estimate.reg = 0.7; end spm_normalise(VG,VBMSKrFA_name,matname{i},'','',defaults_n.estimate); end if(FA_on==2) [pth, fname, ext] = spm_fileparts(rVmean(i).fname); rLBMSK = cfg_getfile('FPlist',pth,['rL_MSK-' fname(1:length(fname)-3) ext]); %->VOLKMAR? rfLBMSK = cfg_getfile('FPlist',pth,['rfL_MSK-' fname(1:length(fname)-3) ext]); if(isempty(char(rLBMSK)) || isempty(char(rfLBMSK))) [VrLBMSK,VrfLBMSK] = main_creat_LBMSK_iii(rVmean(i)); else VrLBMSK = spm_vol(char(rLBMSK)); %-> VOLKMAR? VrfLBMSK = spm_vol(char(rfLBMSK)); %-> VOLKMAR? end clear pth fname ext; [pth, fname, ext] = spm_fileparts(V(i).fname); % begin: masking rFA images LP = fullfile(pth, [filesep 'LM-' fname ext]); VLP = VrLBMSK; VLP.fname = LP; VLP = spm_imcalc([V(i) VrLBMSK],VLP,'i1.*i2'); fLP = fullfile(pth, [filesep 'fLM-' fname ext]); VfLP = VrLBMSK; VfLP.fname = fLP; fV = V(i); %fV.fname = prepend(V(i).fname,'f'); fV.mat = diag([-1 1 1 1])*V(i).mat; VfLP = spm_imcalc([fV VrfLBMSK],VfLP,'i2.*i1'); % -> VOLKMAR? % end: masking rFA images %normalise matname{i} = [spm_str_manip(VLP.fname,'sd') '_sn.mat']; fmatname{i} = [spm_str_manip(VfLP.fname,'sd') '_sn.mat']; if(iter==1) % %%%defaults 'rough FA' defaults_n.estimate.smosrc = 8; defaults_n.estimate.smoref = 8; defaults_n.estimate.cutoff = 25; defaults_n.estimate.nits = 16; defaults_n.estimate.reg = 1; end if(iter==2) % %%%defaults 'precise FA' defaults_n.estimate.smosrc = 6; defaults_n.estimate.smoref = 6; defaults_n.estimate.cutoff = 20; defaults_n.estimate.nits = 16; defaults_n.estimate.reg = 0.7; end spm_normalise(VG,VLP,matname{i},'','',defaults_n.estimate); spm_normalise(VG,VfLP,fmatname{i},'','',defaults_n.estimate); end end varargout{1} = matname; if FA_on == 2 varargout{2} = fmatname; end %_______________________________________________________________________ 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
tbxdti_run_favbs_norm.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/FAVBS/tbxdti_run_favbs_norm.m
12,793
utf_8
943dfad17a02784a50ae1894bdb09547
function varargout = tbxdti_run_favbs_norm(cmd, varargin) % Run a sequence of normalisations on DWI/FA data % varargout = tbxdti_run_favbs_norm(cmd, varargin) % where cmd is one of % 'run' - out = tbxdti_run_favbs_norm('run', job) % Run a job, and return its output argument % 'vout' - dep = tbxdti_run_favbs_norm('vout', job) % Examine a job structure with all leafs present and return an % array of cfg_dep objects. % 'check' - str = tbxdti_run_favbs_norm('check', subcmd, subjob) % Examine a part of a fully filled job structure. Return an empty % string if everything is ok, or a string describing the check % error. subcmd should be a string that identifies the part of % the configuration to be checked. % 'defaults' - defval = tbxdti_run_favbs_norm('defaults', key) % Retrieve defaults value. key must be a sequence of dot % delimited field names into the internal def struct which is % kept in function local_def. An error is returned if no % matching field is found. % tbxdti_run_favbs_norm('defaults', key, newval) % Set the specified field in the internal def struct to a new % value. % Application specific code needs to be inserted at the following places: % 'run' - main switch statement: code to compute the results, based on % a filled job % 'vout' - main switch statement: code to compute cfg_dep array, based % on a job structure that has all leafs, but not necessarily % any values filled in % 'check' - create and populate switch subcmd switchyard % 'defaults' - modify initialisation of defaults in subfunction local_defs % Callbacks can be constructed using anonymous function handles like this: % 'run' - @(job)tbxdti_run_favbs_norm('run', job) % 'vout' - @(job)tbxdti_run_favbs_norm('vout', job) % 'check' - @(job)tbxdti_run_favbs_norm('check', 'subcmd', job) % 'defaults' - @(val)tbxdti_run_favbs_norm('defaults', 'defstr', val{:}) % Note the list expansion val{:} - this is used to emulate a % varargin call in this function handle. % % This code is part of a batch job configuration system for MATLAB. See % help matlabbatch % for a general overview. %_______________________________________________________________________ % Copyright (C) 2007 Freiburg Brain Imaging % Volkmar Glauche % $Id: tbxdti_run_favbs_norm.m 712 2010-06-30 14:20:19Z glauche $ %_______________________________________________________________________ % specifity of tbxdti_favbs: % structure of running number, e.g., in 'job{isteps+1+(citer-1)*numel(job{1}.norm.steps)}': % - isteps = number that assigns whole-brain registration % (multi-contrast elements) - goes from 1 to "number of elements of whole-brain registration" - 1. % - citer = iteration step number - goes from 1 to number of % iterations or until tolerance criteria is acchieved (the latter point has to be done). % - iComb = number of deformationfields that have been generated. %______________________________________________________________________ % Volkmar Glauche / Siawoosh Mohammadi % 2009 rev = '$Rev: 712 $'; %#ok if ischar(cmd) switch lower(cmd) case 'run' job{1} = local_getjob(varargin{1}); % do computation, return results in variable out citer = 1; while(citer<=job{1}.norm.niter) fprintf('Iteration: %d\n', citer) for isteps=1:numel(job{1}.norm.steps), fprintf('Step %d: Running %s-Normalisation', isteps, char(fieldnames(job{1}.norm.steps{isteps}))); % define new iteration variable iter_all=isteps+(citer-1)*numel(job{1}.norm.steps); out{iter_all} = cfg_run_favbs_create_template('run',job{iter_all},char(fieldnames(job{1}.norm.steps{isteps}))); if(iter_all==1) for k = 1:numel(out{1}.matnames) job{2}.Pmean{k} = out{1}.wrPmeans{k}; job{2}.PFA{k} = out{1}.wrFAnames{k}; job{2}.Pb0{k} = out{1}.wrb0names{k}; end job{2}.norm = job{1}.norm; job{2}.citer = 1; else if(iter_all==2) for k = 1:numel(out{1}.matnames) [p n e v] = spm_fileparts(out{1}.matnames{k}); % alternative: anstatt inputs((k-1)*4+1) inputs(1,k-1) % (1:length(out{citer}.matnames{k})-2) inputs{(k-1)*4 + 1} = {out{2}.matnames{k}}; % 2. sn_mat-file inputs{(k-1)*4 + 2} = {out{1}.matnames{k}}; % 1. sn_mat-file inputs{(k-1)*4 + 3} = n; inputs{(k-1)*4 + 4} = [deblank(job{1}.PFA(k)) deblank(job{1}.Pmean(k)) deblank(job{1}.Pb0(k))]; jobComb{k} = 'batch_combine_snMATs.m'; end else % if iter_all > 2 for k = 1:numel(out{iter_all}.matnames) [p n e v] = spm_fileparts(out{ijobComb}.matnames{k}); % alternative: anstatt inputs((k-1)*4+1) inputs(1,k-1) % (1:length(out{citer}.matnames{k})-2) inputs{(k-1)*4 + 1} = {char(outjobComb{ijobComb}{k}.def)}; % def-feld von der letzten iteration inputs{(k-1)*4 + 2} = {out{iter_all}.matnames{k}}; % neues sn_mat-files inputs{(k-1)*4 + 3} = n; inputs{(k-1)*4 + 4} = [deblank(job{1}.PFA(k)) deblank(job{1}.Pmean(k)) deblank(job{1}.Pb0(k))]; jobComb{k} = 'batch_combine_deffield_snMAT.m'; end end ijobComb=iter_all-1; % output "jobComb" unterscheidet sich vom output % "cfg_run_favbs_create_template", daher ist eine % neue variable "outjobComb" notwendig. outjobComb{ijobComb} = spm_jobman('serial',jobComb, '',inputs{:}); clear inputs p n e v; % hier wird neue variable "outjobComb" verwendet, % um die neuen inputs zu definieren. for k = 1:numel(outjobComb{ijobComb}) job{iter_all+1}.Pmean{k} = outjobComb{ijobComb}{k}.warped{2}; job{iter_all+1}.PFA{k} = outjobComb{ijobComb}{k}.warped{1}; job{iter_all+1}.Pb0{k} = outjobComb{ijobComb}{k}.warped{3}; end job{iter_all+1}.norm = job{1}.norm; end end % end isteps citer=citer+1; if(iter_all >1) job{iter_all+1}.citer = citer; end end %Finale LFA-Registration: if(isfield(job{1}.norm.templ,'CT'))% case 1: Customized Template is symmetrical if(isfield(job{1}.norm.templ.CT,'SCT')) if(job{1}.norm.templ.CT.SCT==1) if(exist('iter_all')) out{iter_all+1} = cfg_run_favbs_create_template('run',job{iter_all+1},'LFA'); else out{1} = cfg_run_favbs_create_template('run',job{1},'LFA'); end end end else % case 2: External LFA Template is not empty (Multi-Contrast) if(isfield(job{1}.norm.templ.ET,'SC')) if(~isempty(char(job{1}.norm.templ.ET.SC.PGLFA))) if(exist('iter_all')) out{iter_all+1} = cfg_run_favbs_create_template('run',job{iter_all+1},'LFA'); else out{1} = cfg_run_favbs_create_template('run',job{1},'LFA'); end end end if(isfield(job{1}.norm.templ.ET,'MC')) if(~isempty(char(job{1}.norm.templ.ET.MC.PGLFA))) if(exist('iter_all')) out{iter_all+1} = cfg_run_favbs_create_template('run',job{iter_all+1},'LFA'); else out{1} = cfg_run_favbs_create_template('run',job{1},'LFA'); end end end end if nargout > 0 varargout{1} = out; end case 'vout' job = local_getjob(varargin{1}); % initialise empty cfg_dep array dep = cfg_dep; dep = dep(false); % determine outputs, return cfg_dep array in variable dep varargout{1} = dep; case 'check' if ischar(varargin{1}) subcmd = lower(varargin{1}); subjob = varargin{2}; str = ''; switch subcmd % implement checks, return status string in variable str case 'files' % keyboard % check that files are present which are needed for % selected normalisation steps needb0 = false; needdw = false; for k = 1:numel(subjob.norm.steps) needb0 = needb0||strcmp(char(fieldnames(subjob.norm.steps{k})),'b0'); needdw = needdw||strcmp(char(fieldnames(subjob.norm.steps{k})),'FA'); end needdw = needdw||any(strcmp(fieldnames(subjob.norm.templ.(char(fieldnames(subjob.norm.templ))).(char(fieldnames(subjob.norm.templ.(char(fieldnames(subjob.norm.templ))))))),'PGLFA')); %hier anpassen: fstep existiert nicht mehr! if needb0 && numel(subjob.PFA) ~= numel(subjob.Pb0) str = 'Both FA and b0 images are required.'; return; end if needdw && numel(subjob.PFA) ~= numel(subjob.Pmean) str = 'Both FA and MeanDW images are required.'; return; end otherwise cfg_message('unknown:check', ... 'Unknown check subcmd ''%s''.', subcmd); end varargout{1} = str; else cfg_message('ischar:check', 'Subcmd must be a string.'); end case 'defaults' if nargin == 2 varargout{1} = local_defs(varargin{1}); else local_defs(varargin{1:2}); end otherwise cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd); end else cfg_message('ischar:cmd', 'Cmd must be a string.'); end function varargout = local_defs(defstr, defval) persistent defs; if isempty(defs) % initialise defaults end if ischar(defstr) % construct subscript reference struct from dot delimited tag string tags = textscan(defstr,'%s', 'delimiter','.'); subs = struct('type','.','subs',tags{1}'); try cdefval = subsref(local_def, subs); catch cdefval = []; cfg_message('defaults:noval', ... 'No matching defaults value ''%s'' found.', defstr); end if nargin == 1 varargout{1} = cdefval; else defs = subsasgn(defs, subs, defval); end else cfg_message('ischar:defstr', 'Defaults key must be a string.'); end %_______________________________________________________________________ function job = local_getjob(job) if ~isstruct(job) cfg_message('isstruct:job', 'Job must be a struct.'); end %_______________________________________________________________________ %_______________________________________________________________________ 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
dti_sphere_nb.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Helpers/dti_sphere_nb.m
3,720
utf_8
d0720724fc721f2295c3f7d70f36350e
function varargout = dti_sphere_nb(varargin) % Proximity of points on a unit sphere to a 6-, 18-, 26-neighbourhood % % Batch processing: % FORMAT bchdefaults = dti_sphere_nb('defaults') % ====== % returns the default batch structure as described below. This structure % can be used as a skeleton to fill in necessary values for batch processing. % % FORMAT [res bchdone]=dti_sphere_nb(bch) % ====== % Input argument: % bch - struct array with fields % .res - sphere resolution on a grid [-1:bch.res:1] % .nb - one of 6,18, 26: neighbourhood size and shape % .dim - optional: size of 3D-array to base linear index on % Output arguments: % res - struct array with fields % .nbhood - neighbourhood definition (NOT normalised to unit length) % .nbind - if input has .dim set, return index offsets for linear % indexing % .F, .V - faces and vertices of isosurface as produced by MATLABs % isosurface function % .ind - nearest neighbour direction for each vertex (minimum % euklidean distance between .V and normalised .nbhood) % .Vd - cell array of vertices, belonging to each neighbourhood % direction (this is merely a copy of V, but for % performance reasons in dti_dt_time3 we want this precomputed) % bchdone - filled input struct % % This function is part of the diffusion toolbox for SPM5. For general % help about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id: dti_sphere_nb.m 712 2010-06-30 14:20:19Z glauche $ rev = '$Revision: 712 $'; % defaults mydefaults = struct('res',.05, 'nb',26); if nargin==1 && ischar(varargin{1}) && strcmpi(varargin{1},'defaults') varargout{1} = mydefaults; return; end; % Check input arguments if (nargin==1) && isstruct(varargin{1}) bch = fillstruct(mydefaults,varargin{1}); else bch = mydefaults; end; for ns = 1:numel(bch) [x y z] = ndgrid(-1:bch(ns).res:1); [res(ns).F res(ns).V]=isosurface(x,y,z,x.^2+y.^2+z.^2,1); switch(bch(ns).nb) case 6, nbhood = kron(eye(3),[1; -1]); case 18, for j = 1:3 for k = 1:3 for l = 1:3 nbhood(sub2ind([3 3 3],j,k,l),1:3)=[j-2 k-2 l-2]; end, end; end; nbhood = nbhood(sum(abs(nbhood),2)~=0&~all(nbhood,2),:); case 26, for j = 1:3 for k = 1:3 for l = 1:3 nbhood(sub2ind([3 3 3],j,k,l),1:3)=[j-2 k-2 l-2]; end, end; end; nbhood = nbhood(sum(abs(nbhood),2)~=0,:); otherwise, error('unknown neighbourhood'); end; res(ns).nbhood = nbhood; res(ns).num = 1:bch(ns).nb; res(ns).ones= ones(bch(ns).nb,1); nbhood = nbhood./(sqrt(sum(nbhood.^2,2))*ones(1,3)); for k=1:size(nbhood,1) dist(k,:) = sqrt(sum((res(ns).V -... ones(size(res(ns).V,1),1)*nbhood(k,:)).^2, ... 2))'; res(ns).inum(k) = find(all(nbhood==-res(ns).ones*nbhood(k,:),2)); end; [tmp res(ns).ind] = min(dist); for k=1:size(nbhood,1) res(ns).Vd{k} = res(ns).V(res(ns).ind==k,:); end; end; varargout{1}=res; varargout{2}=bch; function visualise(res) col=abs(res.nbhood); figure; for k=1:size(res.nbhood,1) V1=res.V; V1(res.ind~=k,:)=NaN; h(k)=patch('Faces',res.F, 'Vertices',V1, 'FaceColor',col(k,:), ... 'EdgeColor','none'); hold on; end view(3); daspect([1 1 1]);
github
philippboehmsturm/antx-master
tensor_gop.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Computations/tensor_gop.m
1,596
utf_8
58878f4452e9c3192c95c027a88b66c6
function t = tensor_gop(varargin) % generalised outer product % FORMAT t = tensor_gop(u1,u2,...uN) % ====== % Input arguments % - u1,..,uN - generating vectors % or % - U - udim-by-N matrix of generating vectors U(:,1) ... U(:,N) % Output argument % - t - generated tensor % % Computes t(i1,i2,...,iN) = u1(i1)*u2(i2)*...*uN(iN), thus creating a % rank-1 tensor of order n with dimensionality [length(u1), length(u2), % ... length(uN)]. % % This function is part of the diffusion toolbox for SPM5. For general % help about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id: tensor_gop.m 677 2009-09-02 08:07:46Z glauche $ rev = '$Revision: 677 $'; if nargin > 1 szt = zeros(1,nargin); for k=1:nargin szt(k) = numel(varargin{k}); end; t = varargin{1}; for k=2:nargin t = kron(varargin{k},t); end; else szt = repmat(size(varargin{1},1),[1,size(varargin{1},2)]); t = varargin{1}(:,1); for k=2:size(varargin{1},2) t = kron(varargin{1}(:,k),t); end; end; t=reshape(t,szt); function obsolete t1=t; t=zeros(szt); ind=zeros(nargin,1); indstr = sprintf('ind(%d),',1:nargin); sub2indstr = sprintf('[%s] = ind2sub(szt,k);',indstr(1:end-1)); vaindstr = sprintf('varargin{%d}(ind(%d))*',kron(1:nargin,[1,1])); prodstr = sprintf('t(%s) = %s;', indstr(1:end-1), vaindstr(1:end-1)); for k = 1:numel(t) eval(sub2indstr); eval(prodstr); end; keyboard
github
philippboehmsturm/antx-master
dti_eig.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Computations/dti_eig.m
9,841
utf_8
c5451b9b2d2579b6d08b9776b0ad1917
function varargout=dti_eig(bch) % Tensor decomposition % % Computes eigenvector components, eigenvalues and euler angles (pitch, % roll, yaw convention) from diffusion tensor data. % Output image naming convention %/*\begin{itemize}*/ %/*\item*/ evec1[x,y,z]*IMAGE - components of 1st eigenvector %/*\item*/ evec2[x,y,z]*IMAGE - components of 2nd eigenvector %/*\item*/ evec3[x,y,z]*IMAGE - components of 3rd eigenvector %/*\item*/ eval[1,2,3]*IMAGE - eigenvalues %/*\item*/ euler[1,2,3]*IMAGE - euler angles %/*\end{itemize}*/ % Batch processing % FORMAT res = dti_eig(bch) % ====== %/*\begin{itemize}*/ %/*\item*/ Input argument: % bch struct with fields %/*\begin{description}*/ %/*\item[*/ .dtimg/*]*/ cell array of filenames of tensor images %/*\item[*/ .data/*]*/ real 6-by-Xdim-by-Ydim-by-Zdim-array of tensor elements %/*\item[*/ .dteigopts/*]*/ results wanted, a string array containing a % combination of /*\begin{description}*/ %/*\item[*/ v/*]*/ (eigenvectors) %/*\item[*/ l/*]*/ (eigenvalues) %/*\item[*/ a/*]*/ (euler angles)/*\end{description}*/ %/*\end{description}*/ % Only one of 'dtimg' or 'data' need to be specified. If 'data' is % provided, no files will be read and outputs will be given as % arrays in the returned 'res' structure. Input order for the % tensor elements is alphabetical. %/*\item*/ Output argument (only defined if bch has a 'data' field): % res struct with fields %/*\begin{description}*/ %/*\item[*/ .evec/*]*/ eigenvectors %/*\item[*/ .eval/*]*/ eigenvalues %/*\item[*/ .euler/*]*/ euler angles %/*\end{description}*/ % The presence of each field depends on the option specified in % the batch. %/*\end{itemize}*/ % % This function is part of the diffusion toolbox for SPM5. For general % help about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id$ rev = '$Revision$'; funcname = 'Tensor decomposition'; % function preliminaries Finter=spm_figure('GetWin','Interactive'); Finter=spm('FigName',funcname,Finter); SPMid = spm('FnBanner',mfilename,rev); % function code starts here if isfield(bch,'data') tmp=size(bch.data); if length(tmp)>4||tmp(1)~=6 error('wrong DTI dimensions'); end; DTIdim=[1 1 1]; DTIdim(1:length(tmp)-1)=tmp(2:end); if any(bch.dteigopts=='v') res.evec = zeros([3,3,DTIdim]); end; if any(bch.dteigopts=='l') res.eval = zeros([3,DTIdim]); end; if any(bch.dteigopts=='a') res.euler = zeros([3,DTIdim]); end; for p = 1:DTIdim(3) if any(bch.dteigopts=='a') [evec eval euler] = ... dti_eig_decompose(bch.data(:,:,:,p)); else [evec eval] = ... dti_eig_decompose(bch.data(:,:,:,p)); end; if any(bch.dteigopts=='v') res.evec(:,:,:,:,p) = evec; end; if any(bch.dteigopts=='l') res.eval(:,:,:,p) = eval; end; if any(bch.dteigopts=='a') res.euler(:,:,:,p) = euler; end; end; else IDTI = spm_vol(char(bch.dtimg)); DTIdim=IDTI(1).dim(1:2); [p n e]=spm_fileparts(IDTI(1).fname); if ~isempty(regexp(n,'^((dt[1-6])|(D[x-z][x-z]))_.*', 'once')) n = n(5:end); end; cdir=['x','y','z']; if any (bch.dteigopts=='v') for j=1:3 for k=1:3 res.evec{(j-1)*3+k} = ... fullfile(p,... [sprintf('evec%d%s_',... k,cdir(j)) n e]); vdescrip{(j-1)*3+k} = ... sprintf('Eigenvector %d, %s component',... k, cdir(j)); end; end; Vevec = spm_create_vol(struct('fname',res.evec, ... 'descrip',vdescrip, ... 'dim',IDTI(1).dim(1:3), ... 'dt',[spm_type('float32') spm_platform('bigend')], ... 'mat',IDTI(1).mat,... 'pinfo',[1 0 0]')); end; if any(bch.dteigopts=='l') ldescrip = cell(1,3); for j=1:3 res.eval{j} = ... fullfile(p,[sprintf('eval%d_',j) n e]); ldescrip{j} = sprintf('Eigenvalue %d',j); end; Veval = spm_create_vol(struct('fname',res.eval, ... 'descrip',ldescrip, ... 'dim',IDTI(1).dim(1:3), ... 'dt',[spm_type('float32') spm_platform('bigend')], ... 'mat',IDTI(1).mat,... 'pinfo',[1 0 0]')); end; if any(bch.dteigopts=='a') adescrip = cell(1,3); for j=1:3 res.euler{j} = ... fullfile(p,[sprintf('euler%d_',j) n e]); adescrip{j} = sprintf('Euler angle %d',j); end; Veuler = spm_create_vol(struct('fname',res.euler, ... 'descrip',adescrip, ... 'dim',IDTI(1).dim(1:3),... 'dt',[spm_type('float32') spm_platform('bigend')], ... 'mat',IDTI(1).mat,... 'pinfo',[1 0 0]')); end; %-Start progress plot %----------------------------------------------------------------------- spm_progress_bar('Init', IDTI(1).dim(3),... 'Tensor decomposition', 'planes completed'); %-Loop over planes computing result Y %----------------------------------------------------------------------- for p = 1:IDTI(1).dim(3), B = inv(spm_matrix([0 0 -p 0 0 0 1 1 1])); X=zeros(6,DTIdim(1),DTIdim(2)); for k = 1:6 X(k,:,:) = spm_slice_vol(IDTI(k),B,DTIdim,0); % hold 0 end; if any(bch.dteigopts=='a') [evec evals euler]=dti_eig_decompose(X); else [evec evals]=dti_eig_decompose(X); end; %-Write output image %---------------------------------------------------------------- for n1=1:3 if any(bch.dteigopts == 'v') for n2=1:3 Vevec((n1-1)*3+n2)=... spm_write_plane(Vevec((n1-1)*3+n2), ... squeeze(evec(n1,n2,:,:)),p); end; end; if any(bch.dteigopts == 'l') Veval(n1)=spm_write_plane(Veval(n1),... squeeze(evals(n1,:,:)),p); end; if any(bch.dteigopts == 'a') Veuler(n1)=spm_write_plane(Veuler(n1), ... squeeze(euler(n1,:,:)),p); end; end; spm_progress_bar('Set',p); end; spm_progress_bar('Clear') end; if nargout > 0 if isfield(bch,'dtimg') ud = dti_get_dtidata(bch.dtimg{1}); if any (bch.dteigopts=='v') for k = 1:numel(res.evec) dti_get_dtidata(res.evec{k}, ud); end end if any (bch.dteigopts=='a') for k = 1:numel(res.euler) dti_get_dtidata(res.euler{k}, ud); end end end varargout{1} = res; else if isfield(bch,'data') assignin('base', 'res', res); end; end; function varargout=dti_eig_decompose(X) % input formats: % - 6-by-N[-by-M] % % output formats: % - evec 3-by-3-by-N[-by-M] % - eval 3-by-N[-by-M] % - euler 3-by-N[-by-M] szx=size(X); ndx=ndims(X); if (szx(1) ~= 6) || ~any(ndx==1:3) error([mfilename ': Wrong number of elements in tensor']); end; DTIdim = [1 1]; if ndx > 1 DTIdim(1) = szx(2); end; if ndx > 2 DTIdim(2) = szx(3); end; evec = zeros(3,3,DTIdim(1),DTIdim(2)); evals = zeros(3,DTIdim(1),DTIdim(2)); msk = squeeze(any(isnan(X))|any(isinf(X))|all(X==0)); if DTIdim(2)==1 msk=msk'; end; for k=1:DTIdim(1) for l=1:DTIdim(2) if msk(k,l) % find(isnan(X(:,k,l))|isinf(X(:,k,l)))|all(all(X(:,k,l)==0)) e = NaN*ones(3,3); v = NaN*ones(1,3); else [re rv] = eig([X(1,k,l) X(2,k,l) X(3,k,l);... X(2,k,l) X(4,k,l) X(5,k,l);... X(3,k,l) X(5,k,l) X(6,k,l)]); % sort eigenvalues and -vectors tmp=diag(rv); [v ind]=sort(-abs(tmp)); v=tmp(ind); e=re(:,ind); [mx ind] = max(abs(e)); if sign(det(e))==-1 % make coordinate system right-handed if sign(e(ind(1),1))==-1 e(:,1) = -e(:,1); elseif sign(e(ind(2),2))==-1 e(:,2) = -e(:,2); else e(:,3) = -e(:,3); end; else % right-handed, check for 2 negative "main vector" elements ne = double(sign([e(ind(1),1) e(ind(2),2) e(ind(3),3)])==-1); if sum(ne) == 2 ne=ones(3,1)*ne; ne(ne==1)=-1; ne(ne==0)=1; e = e.*ne; end; end; end evec(:,:,k,l)=e; evals(:,k,l)=v; % nur v end; end; if nargout > 0 varargout(1) = {evec}; end; if nargout > 1 varargout(2) = {evals}; end; if nargout > 2 euler=zeros(3,DTIdim(1),DTIdim(2)); euler(2,:,:) = squeeze(asin(evec(1,3,:,:))); sel=(abs(euler(2,:,:))-pi/2).^2 < 1e-9; euler(1,sel) = 0; euler(3,sel) = atan2(-squeeze(evec(2,1,sel)), ... squeeze(-evec(3,1,sel)./evec(1,3,sel))); c = cos(euler(2,~sel))'; euler(1,~sel) = atan2(squeeze(evec(2,3,~sel))./c, squeeze(evec(3,3,~sel))./c); euler(3,~sel) = atan2(squeeze(evec(1,2,~sel))./c, squeeze(evec(1,1,~sel))./c); %euler(euler<0) = euler(euler<0)+pi; varargout(3) = {euler}; end;
github
philippboehmsturm/antx-master
dti_dt_time3.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/TimeOfArrival/dti_dt_time3.m
13,277
utf_8
834fc3ef1b12e2b89986d9c2835347e5
function varargout=dti_dt_time3(bch) % Compute time of arrival map for diffusion data % % A level set algorithm is used to compute time of arrival maps. Starting % with a start region, diffusion is simulated by evaluating the % diffusivity profile at each voxel of a propagating front. The profile % is computed efficiently from arbitrary order tensors. % % References: % [Set96] Sethian, James A. A Fast Marching Level Set Method for % Monotonically Advancing Fronts. Proceedings of the % National Academy of Sciences, USA, 93(4):1591 -- 1595, 1996. % [?M03] ?rszalan, Evren and Thomas H Mareci. Generalized Diffusion % Tensor Imaging and Analytical Relationships Between % Diffusion Tensor Imaging and High Angular Resolution % Diffusion Imaging. Magnetic Resonance in Medicine, % 50:955--965, 2003. % % Batch processing: % FORMAT dti_dt_time3(bch) % ====== % Input argument: % bch - struct with batch descriptions, containing the following % fields: % .order - tensor order % .files - cell array of tensor image filenames % .mask - image mask % .sroi - starting ROI % .eroi - end ROI (optional) % .frac - maximum fraction of voxels that should be visited % (range 0-1) % .resfile - results filename stub % .nb - neighbourhood (one of 6, 18, 26) % .exp - Exponential for tensor elements (should be an odd integer) % % This function is part of the diffusion toolbox for SPM5. For general help % about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id: dti_dt_time3.m 543 2008-03-12 19:40:40Z glauche $ rev = '$Revision: 543 $'; funcname = 'Time of arrival (DT)'; % function preliminaries Finter=spm_figure('GetWin','Interactive'); Finter=spm('FigName',funcname,Finter); SPMid = spm('FnBanner',mfilename,rev); % function code starts here % DEBUG debug = true; if debug dTV = spm_vol(spm_select(1,'image','Tloc image')); dTind = find(spm_read_vols(dTV)); end; % ~DEBUG DH = spm_vol(char(bch.dtimg)); % get vox and mm coordinates of DH voxels [x y z]=ndgrid(1:DH(1).dim(1),1:DH(1).dim(2),1:DH(1).dim(3)); Dxyzvx = [x(:)';y(:)';z(:)'; ones(1,numel(x))]; xyzmm=DH(1).mat*Dxyzvx; % resample Mask and ROI(s) in DH space MaskH=spm_vol(bch.maskimg{1}); Mxyzvx=inv(MaskH.mat)*xyzmm; MaskDt=reshape(spm_sample_vol(MaskH,Mxyzvx(1,:),Mxyzvx(2,:),Mxyzvx(3,:),0),... DH(1).dim(1:3)); MaskDt(~isfinite(MaskDt))=0; MaskDt = logical(MaskDt); SRoiH=spm_vol(bch.sroi{1}); Sxyzvx=inv(SRoiH.mat)*xyzmm; alive=MaskDt&logical(reshape(spm_sample_vol(SRoiH, Sxyzvx(1,:), Sxyzvx(2,:),... Sxyzvx(3,:),0),... DH(1).dim(1:3))); if isempty(bch.eroi{1}) EndDt = []; else EndH=spm_vol(bch.eroi{1}); Exyzvx=inv(EndH.mat)*xyzmm; EndDt=MaskDt&logical(reshape(spm_sample_vol(EndH, Exyzvx(1,:), Exyzvx(2,:),... Exyzvx(3,:),0),... DH(1).dim(1:3))); if ~any(EndDt(:)) EndDt = []; end; end; clear Mxyzvx Sxyzvx Exyzvx % we need voxel size later on VOX = sqrt(sum(DH(1).mat(1:3,1:3).^2)); sumu=floor(bch.frac*sum(MaskDt(:)==true)); bandx=false(DH(1).dim(1:3)); bandy=false(DH(1).dim(1:3)); bandz=false(DH(1).dim(1:3)); bandx(2:end,:,:)=alive(1:end-1,:,:); bandx(1:end-1,:,:)=bandx(1:end-1,:,:)|alive(2:end,:,:); bandx=bandx&~alive&MaskDt; bandy(:,2:end,:)=alive(:,1:end-1,:); bandy(:,1:end-1,:)=bandy(:,1:end-1,:)|alive(:,2:end,:); bandy=bandy&~alive&MaskDt; bandz(:,:,2:end)=alive(:,:,1:end-1); bandz(:,:,1:end-1)=bandz(:,:,1:end-1)|alive(:,:,2:end); bandz=bandz&~alive&MaskDt; band=bandx|bandy|bandz; clear bandx bandy bandz; T=inf(DH(1).dim(1:3)); D=inf(DH(1).dim(1:3)); P=inf(DH(1).dim(1:3)); Tloc=zeros(DH(1).dim(1:3)); Tnumb=zeros(DH(1).dim(1:3)); T(alive)=0; D(alive)=1; P(alive)=0; D(band)=1; [Hind mult] = dti_dt_order(bch.dtorder); global nbhood; nbhood=dti_sphere_nb(struct('nb',bch.nb)); nbhood.nbdist=sqrt(sum(abs(nbhood.nbhood).*... repmat(VOX.^2,bch.nb,1),2))'; % pre-compute HM for cnb=1:bch.nb nbhood.HM{cnb} = zeros(size(nbhood.Vd{cnb},1),size(Hind,2)); for k = 1:size(Hind,2) nbhood.HM{cnb}(:,k) = prod(nbhood.Vd{cnb}(:,Hind(:,k)),2)*mult(k); end; end; % Initialize T(band) % for each band voxel, take the minimum time needed from any of the % neighbouring alive voxels bind = find(band); bD=zeros(numel(DH),numel(bind)); for k=1:numel(DH) bD(k,:) = (10.^7)*... spm_sample_vol(DH(k), Dxyzvx(1,bind), Dxyzvx(2,bind), Dxyzvx(3,bind),0)'; end; for cb = 1:numel(bind) cnsub = nbhood.nbhood+nbhood.ones*(Dxyzvx(1:3,bind(cb))'); % Two step indexing % 1st: Neighbour voxels within volume cnvol = find(all(cnsub>0 & cnsub<=nbhood.ones*DH(1).dim(1:3),2)); % cnsub = cnsub(sel,:); % cnnum = nbhood.num(sel); % cninum= nbhood.inum(sel); % subscript indexing does not work vector-wise, therefore linear index % necessary cnind = sub2ind(DH(1).dim(1:3),cnsub(cnvol,1), cnsub(cnvol,2),... cnsub(cnvol,3)); % 2nd: Alive neighbours - index into cnvol cnavol = cnvol(alive(cnind)); aD=zeros(numel(DH),numel(cnavol)); for k=1:numel(DH) aD(k,:) = (10.^7)*... spm_sample_vol(DH(k),cnsub(cnavol,1),cnsub(cnavol,2),cnsub(cnavol,3),0)'; end; tmpT=zeros(size(cnavol)); for ca = 1:numel(cnavol) tmpT(ca) = nbhood.nbdist(nbhood.num(cnavol(ca)))./... fvel(aD(:,ca), bD(:,cb),... nbhood.Vd{nbhood.num(cnavol(ca))}, nbhood.Vd{nbhood.inum(cnavol(ca))},... nbhood.HM{nbhood.num(cnavol(ca))}, nbhood.HM{nbhood.inum(cnavol(ca))},... -nbhood.nbhood(cnavol(ca),1:3),bch.exp); end; T(bind(cb)) = min(tmpT); end; % DEBUG if debug dband = false(sumu+1, numel(dTind)); dalive = false(sumu+1, numel(dTind)); dT = inf(sumu+1, numel(dTind)); dband(1,:) = band(dTind); dalive(1,:) = alive(dTind); dT(1,:) = T(dTind); end; % ~DEBUG mT = zeros(1,sumu); f=spm_figure('GetWin', 'Interactive'); spm_figure('Clear', f); for numb=1:sumu bind=find(band); if isempty(bind) break; end; [mT(numb) ind1]=min(T(band)); if mT(numb) == Inf break; end; if rem(numb,100)==0 figure(f);plot(mT(1:numb)); xlabel('Iterations'); ylabel('Min time'); end; [cx cy cz] = ind2sub(DH(1).dim(1:3), bind(ind1(1))); alive(cx,cy,cz)=true; band(cx,cy,cz)=false; if ~isempty(EndDt) && all(alive(EndDt(:))) break; end; nbx = cx+nbhood.nbhood(:,1); nby = cy+nbhood.nbhood(:,2); nbz = cz+nbhood.nbhood(:,3); sel = (nbx>=1) & (nby>=1) & (nbz>=1) &... (nbx<=DH(1).dim(1)) & (nby<=DH(1).dim(2)) & (nbz<=DH(1).dim(3)); nbnum = nbhood.num(sel); nbinum= nbhood.inum(sel); nbx = nbx(sel); nby = nby(sel); nbz = nbz(sel); cD=zeros(numel(DH),size(nbx,1)+1); for k=1:numel(DH) cD(k,:) = (10.^7)*... spm_sample_vol(DH(k), [cx; nbx], [cy; nby], [cz; nbz],0)'; end; trec = inf(1,size(nbhood.nbhood, 1)); % neighbour select for nbk = 1:numel(nbx) if ~alive(nbx(nbk),nby(nbk),nbz(nbk)) && MaskDt(nbx(nbk),nby(nbk), ... nbz(nbk)) band(nbx(nbk),nby(nbk),nbz(nbk)) = true; vel = fvel(cD(:,1), cD(:,nbk+1), ... nbhood.Vd{nbnum(nbk)}, nbhood.Vd{nbinum(nbk)},... nbhood.HM{nbnum(nbk)}, nbhood.HM{nbinum(nbk)},... [cx-nbx(nbk), cy-nby(nbk), cz-nbz(nbk)],bch.exp); if vel > 0 % [nbhood.nbhood ones(18,1)]*[[eye(3) [nbx(nbk); nby(nbk); nbz(nbk)]]; 0 0 0 1]' nbrec = [nbhood.nbhood(:,1)+nbx(nbk),... nbhood.nbhood(:,2)+nby(nbk) nbhood.nbhood(:,3)+nbz(nbk)]; sel = nbrec(:,1)>=1 & nbrec(:,2)>=1 & nbrec(:,3)>=1 &... nbrec(:,1)<=DH(1).dim(1) & nbrec(:,2)<=DH(1).dim(2) &... nbrec(:,3)<=DH(1).dim(3); nbind = sub2ind(DH(1).dim(1:3),... nbrec(sel,1), nbrec(sel,2), nbrec(sel,3)); trec(sel) = T(nbind); trec(~sel) = Inf; if any(isfinite(trec)) try %FIXME nbdist % this fzero call has a huge overhead, but % dti_dt_fzero is out of date % tmp = dti_dt_fzero(mT(numb), opts, trec, nbhood.nbdist, vel); % tmp = fzero(@(t) diffT1(t, trec, nbhood.nbdist, vel), mT(numb)); tmp = fzero(@(t) sum(min((trec-t)./nbhood.nbdist,0).^2) - 1/vel.^2, mT(numb)); if (tmp<T(nbx(nbk),nby(nbk),nbz(nbk))) if tmp < mT(numb) Tloc(nbx(nbk),nby(nbk),nbz(nbk))=tmp; Tnumb(nbx(nbk),nby(nbk),nbz(nbk))=numb; end, D(nbx(nbk),nby(nbk),nbz(nbk)) = D(cx,cy,cz) + 1; P(nbx(nbk),nby(nbk),nbz(nbk)) = bind(ind1(1)); T(nbx(nbk),nby(nbk),nbz(nbk))=tmp; end; catch disp(lasterr), end else warning('Time not updated.'); end; end; end; end; % DEBUG if debug dband(numb+1,:) = band(dTind); dalive(numb+1,:) = alive(dTind); dT(numb+1,:) = T(dTind); end; % ~DEBUG % spm_progress_bar('Set',numb); end; Ta=full(T); Tb=full(T); Ta(~(isfinite(Ta)&alive)) = NaN; Tb(~(isfinite(Tb)&band)) = NaN; P(~alive)=NaN; D(~alive)=NaN; Htmp = DH(1); Htmp.dt = [spm_type('float32') spm_platform('bigend')]; THa = Htmp; THb = Htmp; THl = Htmp; DstH = Htmp; PH = Htmp; VH = Htmp; [p n e v] = spm_fileparts(Htmp.fname); switch bch.resfile case 's', [p1 n e1 v1] = spm_fileparts(bch.sroi{1}); case 't', [p1 n e1 v1] = spm_fileparts(bch.dtimg{1}); case 'e', if ~isempty(bch.eroi{1}) [p1 n e1 v1] = spm_fileparts(bch.eroi{1}); else warning('No end ROI defined, using start ROI.'); [p1 n e1 v1] = spm_fileparts(bch.sroi{1}); end; end; THa.fname = fullfile(bch.swd{1}, ['ta_' n e]); res.ta = {THa.fname}; THb.fname = fullfile(bch.swd{1}, ['tb_' n e]); res.tb = {THb.fname}; THl.fname = fullfile(bch.swd{1}, ['tl_' n e]); res.tl = {THl.fname}; DstH.fname = fullfile(bch.swd{1}, ['dst_' n e]); res.dst = {DstH.fname}; PH.fname = fullfile(bch.swd{1}, ['trc_' n e]); res.trc = PH.fname; VH.fname = fullfile(bch.swd{1}, ['vel_' n e]); res.vel = VH.fname; spm_write_vol(THa,reshape(Ta,THa.dim(1:3))); spm_write_vol(THb,reshape(Tb,THb.dim(1:3))); spm_write_vol(THl,reshape(Tloc,THb.dim(1:3))); spm_write_vol(DstH,reshape(D,DstH.dim(1:3))); spm_write_vol(PH,reshape(P,PH.dim(1:3))); spm_write_vol(VH,D./reshape(Ta,PH.dim(1:3))); if nargout>0 varargout{1} = res; end; if nargout>1 varargout{2} = bch; end; spm('pointer','arrow'); return; function err = diffT(t,t1,dx,vel) % t1 directions are x, y, z, -x, -y, -z err = max( max((t1(4)-t)/(-dx(1)),0), -min((t1(1)-t)/dx(1),0) ).^2 + ... max( max((t1(5)-t)/(-dx(2)),0), -min((t1(2)-t)/dx(2),0) ).^2 + ... max( max((t1(6)-t)/(-dx(3)),0), -min((t1(3)-t)/dx(3),0) ).^2 - 1/vel.^2; disc=[max((t1(4)-t)/(-dx(1)),0).^2 min((t1(1)-t)/dx(1),0).^2 ... max((t1(5)-t)/(-dx(2)),0).^2 min((t1(2)-t)/dx(2),0).^2 ... max((t1(6)-t)/(-dx(3)),0).^2 min((t1(3)-t)/dx(3),0).^2]; return; function err = diffT1(t,t1,dx,vel) % t1 directions are x, y, z, -x, -y, -z % max(-x -y -z replaced by min(x y z %err = min((t1(4)-t)/dx(1),0).^2 + min((t1(1)-t)/dx(1),0).^2 + ... % min((t1(5)-t)/dx(2),0).^2 + min((t1(2)-t)/dx(2),0).^2 + ... % min((t1(6)-t)/dx(3),0).^2 + min((t1(3)-t)/dx(3),0).^2 - 1/vel.^2; err = sum(min((t1-t)./dx,0).^2) - 1/vel.^2; return; function vel = fvel(D1,D2,G1,G2,HM1,HM2,dxyz,dexp) % Compute ADCs (or correcty B:D, which is a scaled ADC if B = b*gg' for a % gradient vector g) from tensors for all directions on unit sphere that % have current neighbourhood direction as nearest neighbour. ADCs will be % weighted by the euclidean distance between current neighbourhood % direction and ADC direction. This distance function can be sharpened by % specifying a direction exponential. Note that this sharpening is % independent of diffusion direction, it only imposes a weighting dependent % on the distance between front direction and ADC direction. Dtmp1=HM1*D1; Dtmp2=HM2*D2; Dsel1 = Dtmp1>0; Dsel2 = Dtmp2>0; ndxyz = dxyz/sqrt(sum(dxyz.^2)); vel = sqrt(Dtmp1(Dsel1)'*(G1(Dsel1,:)*ndxyz')/sum(Dsel1)*Dtmp2(Dsel2)'*(G2(Dsel2,:)*(-ndxyz'))/sum(Dsel2));
github
philippboehmsturm/antx-master
dti_dt_fzero.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/TimeOfArrival/dti_dt_fzero.m
15,171
utf_8
3d65517f6973f291d7b07a9f851580bb
function [b,fval,exitflag,output] = dti_dt_fzero(x,varargin) %FZERO Scalar nonlinear zero finding. % modified by VG from Matlab 6.5 for diffusion modelling: % hard-coded function to minimise. % % X = FZERO(FUN,X0) tries to find a zero of the function FUN near X0. % FUN accepts real scalar input X and returns a real scalar function value F % evaluated at X. The value X returned by FZERO is near a point where FUN % changes sign (if FUN is continuous), or NaN if the search fails. % % X = FZERO(FUN,X0), where X is a vector of length 2, assumes X0 is an % interval where the sign of FUN(X0(1)) differs from the sign of FUN(X0(2)). % An error occurs if this is not true. Calling FZERO with an interval % guarantees FZERO will return a value near a point where FUN changes % sign. % % X = FZERO(FUN,X0), where X0 is a scalar value, uses X0 as a starting guess. % FZERO looks for an interval containing a sign change for FUN and % containing X0. If no such interval is found, NaN is returned. % In this case, the search terminates when the search interval % is expanded until an Inf, NaN, or complex value is found. % % X = FZERO(FUN,X0,OPTIONS) minimizes with the default optimization % parameters replaced by values in the structure OPTIONS, an argument % created with the OPTIMSET function. See OPTIMSET for details. Used % options are Display and TolX. Use OPTIONS = [] as a place holder if % no options are set. % % X = FZERO(FUN,X0,OPTIONS,P1,P2,...) allows for additional arguments % which are passed to the function, F=feval(FUN,X,P1,P2,...). Pass an empty % matrix for OPTIONS to use the default values. % % [X,FVAL]= FZERO(FUN,...) returns the value of the objective function, % described in FUN, at X. % % [X,FVAL,EXITFLAG] = FZERO(...) returns a string EXITFLAG that % describes the exit condition of FZERO. % If EXITFLAG is: % > 0 then FZERO found a zero X % < 0 then no interval was found with a sign change, or % NaN or Inf function value was encountered during search % for an interval containing a sign change, or % a complex function value was encountered during search % for an interval containing a sign change. % % [X,FVAL,EXITFLAG,OUTPUT] = FZERO(...) returns a structure % OUTPUT with the number of iterations taken in OUTPUT.iterations. % % Examples % FUN can be specified using @: % X = fzero(@sin,3) % returns pi. % X = fzero(@sin, 3, optimset('disp','iter')) % returns pi, uses the default tolerance and displays iteration information. % % FUN can also be an inline object: % X = fzero(inline('sin(3*x)'),2); % % Limitations % X = fzero(inline('abs(x)+1'), 1) % returns NaN since this function does not change sign anywhere on the % real axis (and does not have a zero as well). % X = fzero(@tan,2) % returns X near 1.5708 because the discontinuity of this function near the % point X gives the appearance (numerically) that the function changes sign at X. % % See also ROOTS, FMINBND, @, INLINE. % The grandfathered FZERO calling sequences: % FZERO(F,X,TOl) sets the relative tolerance for the convergence test. % FZERO(F,X,TOL,TRACE) displays information at each iteration when % TRACE is nonzero. % FZERO(F,X,TOL,TRACE,P1,P2,...) allows for additional arguments % which are passed to the function, F(X,P1,P2,...). Pass an empty % matrix for TOL or TRACE to use the default value. % Copyright 1984-2002 The MathWorks, Inc. % $Revision: 374 $ $Date: 2004-06-11 08:18:07 +0200 (Fr, 11. Jun 2004) $ % This algorithm was originated by T. Dekker. An Algol 60 version, % with some improvements, is given by Richard Brent in "Algorithms for % Minimization Without Derivatives", Prentice-Hall, 1973. A Fortran % version is in Forsythe, Malcolm and Moler, "Computer Methods % for Mathematical Computations", Prentice-Hall, 1976. % old: function b = fzero(FunFcn,x,tol,trace,varargin) % Initialization fcount = 0; exitflag = 1; defaultopt = struct('Display','notify','TolX',eps); % If just 'defaults' passed in, return the default options in X if nargin==1 & nargout <= 1 & isequal(x,'defaults') b = defaultopt; return end if nargin < 1, error('FZERO requires at least one input arguments'); end % Note: don't send varargin in as a comma separated list!! numargin = nargin; numargout = nargout; [tol, trace, calltype, varargin] = ... parse_call(x,defaultopt,numargin,numargout,varargin); if strcmp(calltype,'old') % The old calling syntax is being used. warning('MATLAB:fzero:ObsoleteSyntax', ... ['This syntax for calling FZERO is obsolete. Use the\n',... ' following syntax instead:\n ' ... 'X = FZERO(FUN,X0,OPTIONS,P1,P2,...)\n',... ' See the help entry for FZERO for more information on \n',... ' syntax and usage.']) end % Convert to inline function as needed is done in PARSE_CALL if trace > 2 header = ' Func-count x f(x) Procedure'; step=' '; end if (~isfinite(x)) error('Second argument must be finite.') end % Interval input if (length(x) == 2) a = x(1); savea=a; b = x(2); saveb=b; % Put first feval in try catch try fa = diffT1(a,varargin{:}); catch es = sprintf(['FZERO cannot continue because user supplied' ... ' function \nfailed with the error below.\n\n%s '], ... lasterr); error(es) end fb = diffT1(b,varargin{:}); if any(~isfinite([fa fb])) | any(~isreal([fa fb])) error('Function values at interval endpoints must be finite and real.') end if trace > 2 disp(' ') disp(header) data = [a fa]; step=' initial'; fcount = fcount + 1; disp([sprintf('%5.0f %13.6g %13.6g ',fcount, data), step]) data = [b fb]; step = ' initial'; fcount = fcount + 1; disp([sprintf('%5.0f %13.6g %13.6g ',fcount, data), step]) else % this is in an else since in the "if", want the fcounts % added in one at a time, so can't do it before the if fcount = fcount + 2; end if ( fa == 0 ) b = a; if trace > 1 disp('Zero find terminated successfully.'); end output.iterations = fcount; output.funcCount = fcount; output.algorithm = 'bisection, interpolation'; fval = fa; return elseif ( fb == 0) % b = b; if trace > 1 disp('Zero find terminated successfully.'); end output.iterations = fcount; output.funcCount = fcount; output.algorithm = 'bisection, interpolation'; fval = fb; return elseif (fa > 0) == (fb > 0) error('The function values at the interval endpoints must differ in sign.') end % Starting guess scalar input elseif (length(x) == 1) % Put first feval in try catch try fx = diffT1(x,varargin{:}); catch if ~isempty(Ffcnstr) es = sprintf(['FZERO cannot continue because user supplied' ... ' %s ==> %s\nfailed with the error below.\n\n%s '], ... Ftype,Ffcnstr,lasterr); else es = sprintf(['FZERO cannot continue because user supplied' ... ' %s \nfailed with the error below.\n\n%s '], ... Ftype,lasterr); end error(es) end if fx == 0 b = x; if trace > 1 disp('Zero find terminated successfully'); end output.iterations = fcount; output.funcCount = fcount; output.algorithm = 'bisection, interpolation'; fval = fx; return elseif ~isfinite(fx) | ~isreal(fx) error('Function value at starting guess must be finite and real.'); end fcount = fcount + 1; if trace > 2 disp(' ') disp(header) data = [x fx]; step=' initial'; disp([sprintf('%5.0f %13.6g %13.6g ',fcount, data), step]) end if x ~= 0, dx = x/50; else, dx = 1/50; end % Find change of sign. twosqrt = sqrt(2); a = x; fa = fx; b = x; fb = fx; while (fa > 0) == (fb > 0) dx = twosqrt*dx; a = x - dx; fa = diffT1(a,varargin{:}); if ~isfinite(fa) | ~isreal(fa) exitflag = disperr(a,fa,trace); b = NaN; fval = NaN; output.iterations = fcount; output.funcCount = fcount; output.algorithm = 'bisection, interpolation'; return end fcount = fcount + 1; if trace > 2 data = [a fa]; step=' search'; disp([sprintf('%5.0f %13.6g %13.6g ',fcount, data), step]) end if (fa > 0) ~= (fb > 0) break end b = x + dx; fb = diffT1(b,varargin{:}); if ~isfinite(fb) | ~isreal(fb) exitflag = disperr(b,fb,trace); b = NaN; fval = NaN; return end fcount = fcount + 1; if trace > 2 data = [b fb]; step=' search'; disp([sprintf('%5.0f %13.6g %13.6g ',fcount, data), step]) end end % while if trace > 2 disp(' ') disp([' Looking for a zero in the interval [', ... num2str(a) , ', ', num2str(b), ']']); disp(' ') end savea = a; saveb = b; else error('Second argument must be of length 1 or 2.'); end % if (length(x) == 2 fc = fb; % Main loop, exit from middle of the loop while fb ~= 0 % Insure that b is the best result so far, a is the previous % value of b, and c is on the opposite of the zero from b. if (fb > 0) == (fc > 0) c = a; fc = fa; d = b - a; e = d; end if abs(fc) < abs(fb) a = b; b = c; c = a; fa = fb; fb = fc; fc = fa; end % Convergence test and possible exit m = 0.5*(c - b); toler = 2.0*tol*max(abs(b),1.0); if (abs(m) <= toler) | (fb == 0.0), break, end % Choose bisection or interpolation if (abs(e) < toler) | (abs(fa) <= abs(fb)) % Bisection d = m; e = m; step=' bisection'; else % Interpolation s = fb/fa; if (a == c) % Linear interpolation p = 2.0*m*s; q = 1.0 - s; else % Inverse quadratic interpolation q = fa/fc; r = fb/fc; p = s*(2.0*m*q*(q - r) - (b - a)*(r - 1.0)); q = (q - 1.0)*(r - 1.0)*(s - 1.0); end; if p > 0, q = -q; else p = -p; end; % Is interpolated point acceptable if (2.0*p < 3.0*m*q - abs(toler*q)) & (p < abs(0.5*e*q)) e = d; d = p/q; step=' interpolation'; else d = m; e = m; step=' bisection'; end; end % Interpolation % Next point a = b; fa = fb; if abs(d) > toler, b = b + d; else if b > c, b = b - toler; else b = b + toler; end end fb = diffT1(b,varargin{:}); fcount = fcount + 1; if trace > 2 data = [b fb]; disp([sprintf('%5.0f %13.6g %13.6g ',fcount, data), step]) end end % Main loop output.iterations = fcount; output.funcCount = fcount; output.algorithm = 'bisection, interpolation'; fval = diffT1(b,varargin{:}); if trace > 1 disp(['Zero found in the interval: [',num2str(savea),', ', num2str(saveb),'].']); end %------------------------------------------------------------------ function [tol, trace, calltype, otherargs]=parse_call(x,defaultopt,numargin,numargout,otherargs) % old call: function b = fzero(FunFcn,x,tol,trace,varargin) % new call: function b = fzero(FunFcn,x,options,varargin) % New syntax has only 1 inputs: fzero(x) if ( numargin < 2 ) calltype = 'new'; options = []; else % numargin >=3 thirdarg = otherargs{1}; otherargs = otherargs(2:end); if (numargout > 1) % new syntax if > 1 output calltype = 'new'; options = thirdarg; elseif isstruct(thirdarg) % (numargout <= 1) % x = fzero(f,x,options,...) calltype = 'new'; options = thirdarg; elseif length(thirdarg)==1 & numargin==2 % (numargout <= 1) % fzero(f,x,tol) calltype = 'old'; tol = thirdarg; trace = 0; elseif length(thirdarg)==1 & (numargin > 2 ) % (numargout <= 1) % x = fzero(f,x,tol,trace,...) calltype = 'old'; tol = thirdarg; trace = otherargs{1}; otherargs = otherargs(2:end); elseif isempty(thirdarg) & numargin==2 % (numargout <= 1) % x = fzero(f,x,[]) calltype = 'new'; options = []; elseif numargin > 2 & isempty(thirdarg) % x = fzero(f,x,[],...) % 4 or more args, 3rd is empty % Can't tell whether old or new call. warning('MATLAB:fzero:UndeterminedSyntax', ... ['Cannot determine from calling sequence whether to use new or\n', ... ' grandfathered FZERO function. Using new; if call was ', ... 'grandfathered\n FZERO syntax, this may give unexpected results.']); options = thirdarg; calltype= 'new'; else % 3 or more args but invalid thirdarg % x = fzero(f,x,thirdarg,...) options = thirdarg; calltype = 'new'; end end if isequal(calltype,'new') tol = optimget(options,'TolX',defaultopt,'fast'); printtype = optimget(options,'Display',defaultopt,'fast'); switch printtype case 'notify' trace = 1; case {'none', 'off'} trace = 0; case 'iter' trace = 3; case 'final' trace = 2; otherwise trace = 1; end end %------------------------------------------------------------------ function exitflag = disperr(y, fy, trace) %DISPERR Display an appropriate error message when FY is Inf, % NaN, or complex. Assumes Y is the value and FY is the function % value at Y. If FY is neither Inf, NaN, or complex, it generates % an error message. if ~isfinite(fy) % NaN or Inf detected exitflag = -1; if trace > 0 disp('Exiting fzero: aborting search for an interval containing a sign change'); disp(' because NaN or Inf function value encountered during search '); disp(['(Function value at ', num2str(y),' is ',num2str(fy),')']); disp('Check function or try again with a different starting value.') end elseif ~isreal(fy) % Complex value detected exitflag = -1; if trace > 0 disp('Exiting fzero: aborting search for an interval containing a sign change'); disp(' because complex function value encountered during search '); disp(['(Function value at ', num2str(y),' is ',num2str(fy),')']); disp('Check function or try again with a different starting value.') end else error('DISPERR (in FZERO) called with invalid argument.') end function err = diffT1(t,t1,dx,vel) % t1 directions are x, y, z, -x, -y, -z % max(-x -y -z replaced by min(x y z %err = min((t1(4)-t)/dx(1),0).^2 + min((t1(1)-t)/dx(1),0).^2 + ... % min((t1(5)-t)/dx(2),0).^2 + min((t1(2)-t)/dx(2),0).^2 + ... % min((t1(6)-t)/dx(3),0).^2 + min((t1(3)-t)/dx(3),0).^2 - 1/vel.^2; err = sum(min((t1-t)./dx,0).^2) - 1/vel.^2; return;
github
philippboehmsturm/antx-master
dti_evec_time3.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/TimeOfArrival/dti_evec_time3.m
13,671
utf_8
7a81df6fbc32eab4606e9ee08607fd64
function dti_evec_time3(varargin) % Compute time of arrival map for diffusion data % % References: % [Set96] Sethian, James A. A Fast Marching Level Set Method for % Monotonically Advancing Fronts. Proceedings of the National % Academy of Sciences, USA, 93(4):1591 -- 1595, 1996. % % FORMAT bchdefaults = dti_evec_time3('defaults') % ====== % returns the default batch structure as described below. This structure % can be used as a skeleton to fill in necessary values for batch processing. % % FORMAT [res bchdone]=dti_evec_time3(bch) % ====== % This function incorporates the GUI frontend and former dti_time3allway. % % This function is part of the diffusion toolbox for SPM5. For general help % about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id: dti_evec_time3.m 452 2006-06-08 09:27:02Z glauche $ rev = '$Revision: 452 $'; funcname = 'Time of arrival'; % menu setup if nargin==2 if ischar(varargin{1}) & ishandle(varargin{2}) if strcmp(lower(varargin{1}),'menu') Menu = uimenu(varargin{2},'Label',funcname,... 'Callback',mfilename); return; end; if strcmp(lower(varargin{1}),'hmenu') Menu = uimenu(varargin{2},'Label',['Help on ' funcname],... 'Callback',['spm_help(''' mfilename ''')']); return; end; end; end; % defaults mydefaults = struct('ecfiles',{{}}, 'evfiles',{{}}, 'salfiles',{{}},... 'mask',{{}},'sroi',{{}}, 'eroi',{{}}, 'frac',[], ... 'resfile',{{}}); if nargin==1 & ischar(varargin{1}) & strcmp(lower(varargin{1}),'defaults') varargout{1} = mydefaults; return; end; % function preliminaries Finter=spm_figure('GetWin','Interactive'); spm_input('!DeleteInputObj'); Finter=spm('FigName',funcname,Finter); SPMid = spm('FnBanner',mfilename,rev); % function code starts here % Check input arguments if (nargin==1) & isstruct(varargin{1}) % Check for spmr_pp-batch if isfield(varargin{1},'step') bch = fillstruct(mydefaults, varargin{1}.step); else bch = fillstruct(mydefaults, varargin{1}); end; nsub = numel(bch); else nsub = spm_input('# subjects','!+1','e',''); bch=repmat(mydefaults,[nsub 1]); end; for sub = 1:nsub spm_input(sprintf('subject %d', sub),1,'d',funcname); ssub = sprintf('Subj %d - ', sub); if isempty(bch(sub).ecfiles) bch(sub).ecfiles=spm_get(9, 'evec*IMAGE',... {[ssub 'Eigenvector images']}); end; if isempty(bch(sub).evfiles) bch(sub).evfiles=spm_get(3,'eval*IMAGE',... {[ssub 'Eigenvalue images']}); end; if isempty(bch(sub).salfiles) bch(sub).salfiles=spm_get([0 3],'s*IMAGE',... {[ssub 'Saliency images (optional)']}); if isempty(bch(sub).salfiles) bch(sub).salfiles={''}; end; end; if isempty(bch(sub).mask) bch(sub).mask=spm_get(1,'*IMAGE',{[ssub 'DTI data mask']}); end; if isempty(bch(sub).sroi) bch(sub).sroi=spm_get(1,'*roi*IMAGE',{[ssub 'Starting ROI']}); end; if isempty(bch(sub).eroi) bch(sub).eroi=spm_get([0 1], '*roi*IMAGE',... {[ssub 'Destination ROI (optional)']}); if isempty(bch(sub).eroi) bch(sub).eroi={''}; end; end; if isempty(bch(sub).frac) bch(sub).frac=spm_input([ssub 'fraction of voxels'],'!+1','e',1); end; if isempty(bch(sub).resfile) [p n e v] = fileparts(bch(sub).ecfiles{1}); bch(sub).resfile={spm_input([ssub 'results filename base'],'!+1', ... 's',p)}; end; end; for sub = 1:nsub fprintf('%s - subject %d of %d\n', funcname, sub, nsub); EcH = spm_vol(strvcat(bch(sub).ecfiles)); EcDt=zeros([3, 3, EcH(1).dim(1:3)]); % 3 for all 3 evecs EcDt(1,:,:,:,:)=shiftdim(spm_read_vols(EcH(1:3)),3); EcDt(2,:,:,:,:)=shiftdim(spm_read_vols(EcH(4:6)),3); EcDt(3,:,:,:,:)=shiftdim(spm_read_vols(EcH(7:9)),3); EvH = spm_vol(strvcat(bch(sub).evfiles)); EvDt=abs(shiftdim(spm_read_vols(EvH),3)); if isempty(bch(sub).salfiles{1}) bchsal=dti_saliencies('defaults'); res = dti_saliencies(setfield(bchsal,'files',bch(sub).evfiles)); bch(sub).salfiles = {res.sc{1},res.sp{1},res.ss{1}}; end; SalH = spm_vol(strvcat(bch(sub).salfiles)); SalDt=shiftdim(spm_read_vols(SalH),3); MaskH=spm_vol(bch(sub).mask{1}); MaskDt=spm_read_vols(MaskH); MaskDt(~isfinite(MaskDt))=0; StartDt=spm_read_vols(spm_vol(bch(sub).sroi{1}))&MaskDt; if isempty(bch(sub).eroi{1}) EndDt = []; else EndDt=spm_read_vols(spm_vol(bch(sub).eroi{1}))&MaskDt; if ~any(EndDt(:)) EndDt = []; end; end; % we need voxel size later on P = spm_imatrix(MaskH.mat); VOX = abs(P(7:9)); % Voxel selection xmin = 1; xmax = MaskH.dim(1);%118; ymin = 1; ymax = MaskH.dim(2);%118; sx = xmax - xmin + 1; sy = ymax - ymin + 1; sz = MaskH.dim(3); % set Eigenvalues and saliencies (and thereby velocity) to 0 for out of % brain voxels EvDt(:,~logical(MaskDt(xmin:xmax,ymin:ymax,1:MaskH.dim(3))))=0; SalDt(:,~logical(MaskDt(xmin:xmax,ymin:ymax,1:MaskH.dim(3))))=0; %fvel = inline('100*EvDt(1)*abs(sum(squeeze(EcDt1(1,:)).*squeeze(EcDt2(1,:))))+EvDt(2)*abs(sum(squeeze(EcDt1(2,:)).*squeeze(EcDt2(2,:))))+EvDt(3)*abs(sum(squeeze(EcDt1(3,:)).*squeeze(EcDt2(3,:))));','EvDt','EcDt1','EcDt2'); %fvel = inline(['100*sum(EvDt.*squeeze(abs(sum(squeeze(EcDt1)'... % '.*repmat(ds,3,1),2))))'... % '.*sum(EvDt.*squeeze(abs(sum(squeeze(EcDt1)'... % '.*squeeze(EcDt2),2))));'], ... % 'EvDt', 'EcDt1', 'EcDt2', 'ds'); fvel = inline(['SalDtc(1,:).*abs(sum(squeeze(EcDtc(1,:,:)).*ds)).*'... '(SalDtn(1,:).*'... 'abs(sum(squeeze(EcDtc(1,:,:)).*squeeze(EcDtn(1,:,:))))'... '+SalDtn(2,:).*'... '(1-abs(sum(squeeze(EcDtc(1,:,:)).*squeeze(EcDtn(3,:,:)))))'... '+SalDtn(3,:))'... '+SalDtc(2,:).*(1-abs(sum(squeeze(EcDtc(1,:,:)).*ds))).*'... '(SalDtn(1,:).*'... '(1-abs(sum(squeeze(EcDtc(3,:,:)).*squeeze(EcDtn(1,:,:)))))'... '+SalDtn(2,:).*'... 'abs(sum(squeeze(EcDtc(3,:,:)).*squeeze(EcDtn(3,:,:))))'... '+SalDtn(3,:))'... ],...% '+SalDtc(3,:)'], ... 'EcDtc','EcDtn','SalDtc','SalDtn','ds'); sumu=floor(bch(sub).frac*sum(EvDt(1,:)>0)); alive=logical(StartDt(xmin:xmax,ymin:ymax,1:MaskH.dim(3))); bandx(2:sx,:,:)=alive(1:sx-1,:,:); bandx(1:sx-1,:,:)=bandx(1:sx-1,:,:)|alive(2:sx,:,:); bandx=bandx&~alive&MaskDt; bandy(:,2:sy,:)=alive(:,1:sy-1,:); bandy(:,1:sy-1,:)=bandy(:,1:sy-1,:)|alive(:,2:sy,:); bandy=bandy&~alive&MaskDt; bandz(:,:,2:sz)=alive(:,:,1:sz-1); bandz(:,:,1:sz-1)=bandz(:,:,1:sz-1)|alive(:,:,2:sz); bandz=bandz&~alive&MaskDt; T=Inf*ones(sx,sy,sz); D=Inf*ones(sx,sy,sz); P=Inf*ones(sx,sy,sz); Tloc=zeros(sx,sy,sz); T(alive)=0; D(alive)=0; P(alive)=0; % Initialize T(band) T(bandx) = VOX(1)./fvel(EcDt(:,:,bandx), EcDt(:,:,bandx), ... SalDt(:,bandx), SalDt(:,bandx), ... repmat([1 0 0]',[1 sum(bandx(:))])); T(bandy) = VOX(2)./fvel(EcDt(:,:,bandy), EcDt(:,:,bandy),... SalDt(:,bandy), SalDt(:,bandy),... repmat([0 1 0]',[1 sum(bandy(:))])); T(bandz) = VOX(3)./fvel(EcDt(:,:,bandz), EcDt(:,:,bandz),... SalDt(:,bandz), SalDt(:,bandz),... repmat([0 0 1]',[1 sum(bandz(:))])); band=bandx+bandy+bandz>0; D(band)=1; clear bandx bandy bandz StartDt; global nbhood6; res = dti_sphere_nb(struct('nb',6)); nbhood6 = res.nbhood; global nbhood26; res = dti_sphere_nb(struct('nb',26)); nbhood26 = res.nbhood; global nbhood; nbhood=nbhood26; global nbdist; nbdist=sqrt(sum((nbhood.*repmat(VOX,[size(nbhood,1) 1])).^2,2))'; global opts; opts=optimset('fzero'); %spm_progress_bar('Init',sumu,'','voxels'); mT = zeros(1,sumu); f=spm_figure('GetWin', 'Interactive'); spm_figure('Clear', f); xlabel('Iterations'); ylabel('Min time'); for numb=1:sumu Bandind=find(band); if isempty(Bandind) break; end; [mT(numb) ind1]=min(T(band)); ind = Bandind(ind1(1)); if mT(numb) == Inf break; end; figure(f);plot(mT(1:numb)); [xc yc zc] = ind2sub([sx sy sz], ind); alive(xc,yc,zc)=1; band(xc,yc,zc)=0; if ~isempty(EndDt) & all(alive(EndDt(:))) break; end; EvDtc=EvDt(:,xc,yc,zc); SalDtc=SalDt(:,xc,yc,zc); EcDtc=EcDt(:,:,xc,yc,zc); xnb = xc+nbhood(:,1); ynb = yc+nbhood(:,2); znb = zc+nbhood(:,3); sel = (xnb>=1) & (ynb>=1) & (znb>=1) &... (xnb<=sx) & (ynb<=sy) & (znb<=sz); nbcur = nbhood(sel,:); xnb = xnb(sel); ynb = ynb(sel); znb = znb(sel); % neighbour select for nbk = 1:size(nbcur,1) if ~alive(xnb(nbk),ynb(nbk),znb(nbk)) band(xnb(nbk),ynb(nbk),znb(nbk)) = 1; SalDtn=SalDt(:,xnb(nbk),ynb(nbk),znb(nbk)); EcDtn=EcDt(:,:,xnb(nbk),ynb(nbk),znb(nbk)); dsc = nbcur(nbk,:); vel = SalDtc(1).*abs(sum(EcDtc(1,:).*dsc))... .*(SalDtn(1).*abs(sum(EcDtc(1,:).*EcDtn(1,:)))... +SalDtn(2).*(1-abs(sum(EcDtc(1,:).*EcDtn(3,:))))... +SalDtn(3))... +SalDtc(2).*(1-abs(sum(EcDtc(3,:).*dsc)))... .*(SalDtn(1).*(1-abs(sum(EcDtc(3,:).*EcDtn(1,:))))... +SalDtn(2).*abs(sum(EcDtc(3,:).*EcDtn(3,:)))... +SalDtn(3));%... % +SalDtc(3); if vel > 0 nbrec = [nbhood(:,1)+xnb(nbk),... nbhood(:,2)+ynb(nbk) nbhood(:,3)+znb(nbk)]; sel = nbrec(:,1)>=1 & nbrec(:,2)>=1 & nbrec(:,3)>=1 &... nbrec(:,1)<=sx & nbrec(:,2)<=sy & nbrec(:,3)<=sz; nbind = sub2ind([sx sy sz], nbrec(sel,1), nbrec(sel,2), nbrec(sel,3)); trec(sel) = T(nbind); trec(~sel) = Inf; if any(isfinite(trec)) try tmp = fzero(@diffT1, mT(numb), opts, trec, nbdist, vel); catch disp(lasterr), end else tmp = inf; end; else tmp = inf; end; if (tmp<T(xnb(nbk),ynb(nbk),znb(nbk))) D(xnb(nbk),ynb(nbk),znb(nbk)) = D(xc,yc,zc) + 1; P(xnb(nbk),ynb(nbk),znb(nbk)) = ind; T(xnb(nbk),ynb(nbk),znb(nbk))=tmp; if tmp < mT(numb) Tloc(xnb(nbk),ynb(nbk),znb(nbk))=tmp; end, end; end; end; % spm_progress_bar('Set',numb); end; Ta=full(T); Tb=full(T); Ta(~(isfinite(Ta)&alive)) = NaN; Tb(~(isfinite(Tb)&band)) = NaN; P(~alive)=NaN; D(~alive)=NaN; THa = EcH(1); THb = EcH(1); THl = EcH(1); DH = EcH(1); PH = EcH(1); VH = EcH(1); [p n e v] = fileparts(THa.fname); n = bch(sub).resfile{1}; THa.fname = fullfile(p,['ta_' n e v]); res(sub).ta = {THa.fname}; THb.fname = fullfile(p,['tb_' n e v]); res(sub).tb = {THb.fname}; THl.fname = fullfile(p,['tl_' n e v]); res(sub).tl = {THl.fname}; DH.fname = fullfile(p,['dst_' n e v]); res(sub).dst = {DH.fname}; PH.fname = fullfile(p,['trc_' n e v]); res(sub).trc = PH.fname; VH.fname = fullfile(p,['vel_' n e v]); res(sub).vel = VH.fname; spm_write_vol(THa,reshape(Ta,THa.dim(1:3))); spm_write_vol(THb,reshape(Tb,THb.dim(1:3))); spm_write_vol(THl,reshape(Tloc,THb.dim(1:3))); spm_write_vol(DH,reshape(D,DH.dim(1:3))); spm_write_vol(PH,reshape(P,PH.dim(1:3))); spm_write_vol(VH,D./reshape(Ta,PH.dim(1:3))); spm_input('!DeleteInputObj'); %spm_progress_bar('Clear'); return; end; function err = diffT(t,t1,dx,vel) % t1 directions are x, y, z, -x, -y, -z err = max( max((t1(4)-t)/(-dx(1)),0), -min((t1(1)-t)/dx(1),0) ).^2 + ... max( max((t1(5)-t)/(-dx(2)),0), -min((t1(2)-t)/dx(2),0) ).^2 + ... max( max((t1(6)-t)/(-dx(3)),0), -min((t1(3)-t)/dx(3),0) ).^2 - 1/vel.^2; disc=[max((t1(4)-t)/(-dx(1)),0).^2 min((t1(1)-t)/dx(1),0).^2 ... max((t1(5)-t)/(-dx(2)),0).^2 min((t1(2)-t)/dx(2),0).^2 ... max((t1(6)-t)/(-dx(3)),0).^2 min((t1(3)-t)/dx(3),0).^2]; return; function err = diffT1(t,t1,dx,vel) % t1 directions are x, y, z, -x, -y, -z % max(-x -y -z replaced by min(x y z %err = min((t1(4)-t)/dx(1),0).^2 + min((t1(1)-t)/dx(1),0).^2 + ... % min((t1(5)-t)/dx(2),0).^2 + min((t1(2)-t)/dx(2),0).^2 + ... % min((t1(6)-t)/dx(3),0).^2 + min((t1(3)-t)/dx(3),0).^2 - 1/vel.^2; err = sum(min((t1-t)./dx,0).^2) - 1/vel.^2; return;
github
philippboehmsturm/antx-master
dti_dw_wmean_review.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Visualisation/dti_dw_wmean_review.m
14,022
utf_8
5b57fd0970a0906497c1e37170a64be5
function varargout = dti_dw_wmean_review(cmd,varargin) % Compare image series to (weighted) means using a GUI if ischar(cmd) switch lower(cmd) case 'run' spm('pointer','watch'); job = local_getjob(varargin{1}); % do computation, return results in variable out % set up GUI & registry spm_figure('Clear','Graphics'); fg = spm_figure('FindWin','Graphics'); ud.V = spm_vol(char(job.osrcimgs)); ud.mV = spm_vol(char(job.msrcimgs)); ud.sV = spm_vol(char(job.ssrcimgs)); ud.hReg = axes('Visible','off', 'Parent',fg); % dummy axes for registry xyz = spm_XYZreg('RoundCoords',[0;0;0],ud.V(1).mat,ud.V(1).dim'); % align initial coordinates spm_XYZreg('InitReg',ud.hReg,ud.V(1).mat,ud.V(1).dim',xyz); tmp = ud.V(1).mat\[xyz;1]; ud.cp = [1 round(tmp(3))]; ud.ax = axes('Parent',fg, 'Position',[0.03 0.51 0.87 0.48]); ud.im = imagesc(scaletocmap(rand(ud.V(1).dim(3),numel(job.osrcimgs))), 'Parent', ud.ax, 'HitTest','off'); set(ud.ax,'ButtondownFcn',@summary_review, 'Tag',mfilename, ... 'xgrid','on', 'xminorgrid','on', 'xminortick','on', ... 'xcolor',[.7 .7 .7], 'gridlinestyle','-.') ud.cb = axes('Parent',fg, 'Position',[.92 .51 .03 .48]); setup_cm(ud.ax,fg,job.summaryopts); spm_XYZreg('Add2Reg',ud.hReg,ud.ax,@xyz_register); % get DTI information extbch.ltol = 1; extbch.dtol = 0; extbch.sep = 0; extbch.srcimgs = job.osrcimgs; extbch.ref.refscanner = 1; extbch.saveinf = 0; ud.dti = dti_extract_dirs(extbch); % difference summary ud.sx = zeros(ud.V(1).dim(3), numel(job.osrcimgs)); ud.px = zeros(ud.V(1).dim(3), numel(job.osrcimgs)); ud.npx = zeros(ud.V(1).dim(3), numel(job.osrcimgs)); ud.dx = zeros(ud.V(1).dim(3), numel(job.osrcimgs)); ud.ndx = zeros(ud.V(1).dim(3), numel(job.osrcimgs)); % image intensity range ud.win = zeros(numel(job.osrcimgs), 2); spm_progress_bar('init',numel(job.osrcimgs),'Images processed'); for k = 1:numel(job.osrcimgs) X = reshape(spm_read_vols([ud.V(k) ud.mV(k)]), [prod(ud.V(1).dim(1:2)), ud.V(1).dim(3) 2]); ud.sx(:,k) = sum(diff(X,[],3).^2); % sum of squared differences tmppx = abs(1-X(:,:,1)./X(:,:,2)); tmppx(~isfinite(tmppx)) = 0; ud.px(:,k) = sum(tmppx); % sum of relative differences ud.npx(:,k) = sum(tmppx>job.threshopts.pthresh); sdX = sqrt(reshape(spm_read_vols(ud.sV(k)), [prod(ud.V(1).dim(1:2)), ud.V(1).dim(3)])); tmpdx = abs(diff(X,[],3)./sdX); tmpdx(~isfinite(tmpdx)) = 0; ud.dx(:,k) = sum(tmpdx); ud.ndx(:,k) = sum(tmpdx>job.threshopts.sdthresh); ud.win(k,:) = [min(X(:)) max(X(:))]; % image intensity window spm_progress_bar('set', k); end spm_progress_bar('clear'); % precomputed min/max (per image) ud.msx = [min(ud.sx); max(ud.sx)]; ud.mpx = [min(ud.px); max(ud.px)]; ud.mnpx = [min(ud.npx); max(ud.npx)]; ud.mdx = [min(ud.dx); max(ud.dx)]; ud.mndx = [min(ud.ndx); max(ud.ndx)]; % save userdata set(ud.ax, 'Userdata',ud); % summary display summary_display(ud); % summary colorbar display summary_cb_display(ud); % image display image_display(ud); % highlight current slice highlight_cs(ud); if nargout > 0 varargout{1} = out; end spm('pointer','arrow'); case 'vout' job = local_getjob(varargin{1}); % initialise empty cfg_dep array dep = cfg_dep; dep = dep(false); % determine outputs, return cfg_dep array in variable dep varargout{1} = dep; case 'check' if ischar(varargin{1}) subcmd = lower(varargin{1}); subjob = varargin{2}; str = ''; switch subcmd % implement checks, return status string in variable str otherwise cfg_message('unknown:check', ... 'Unknown check subcmd ''%s''.', subcmd); end varargout{1} = str; else cfg_message('ischar:check', 'Subcmd must be a string.'); end case 'defaults' if nargin == 2 varargout{1} = local_defs(varargin{1}); else local_defs(varargin{1:2}); end otherwise cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd); end else cfg_message('ischar:cmd', 'Cmd must be a string.'); end function varargout = local_defs(defstr, defval) persistent defs; if isempty(defs) % initialise defaults defs.summaryopts.summary = 5; defs.summaryopts.mapping = 2; defs.summaryopts.grouping = 2; defs.threshopts.pthresh = .2; defs.threshopts.sdthresh = 2; end if ischar(defstr) % construct subscript reference struct from dot delimited tag string tags = textscan(defstr,'%s', 'delimiter','.'); subs = struct('type','.','subs',tags{1}'); try cdefval = subsref(defs, subs); catch cdefval = []; cfg_message('defaults:noval', ... 'No matching defaults value ''%s'' found.', defstr); end if nargin == 1 varargout{1} = cdefval; else defs = subsasgn(defs, subs, defval); end else cfg_message('ischar:defstr', 'Defaults key must be a string.'); end function job = local_getjob(job) if ~isstruct(job) cfg_message('isstruct:job', 'Job must be a struct.'); end function [im,mx,mn,opts] = summary_display_info(ud,imsel) opts.summary = find(strcmp(get(findobj(0,'-regexp','tag','dti_dw_wmean_review_summary'),'checked'),'on')); opts.mapping = find(strcmp(get(findobj(0,'-regexp','tag','dti_dw_wmean_review_mapping'),'checked'),'on')); opts.grouping = find(strcmp(get(findobj(0,'-regexp','tag','dti_dw_wmean_review_grouping'),'checked'),'on')); switch opts.summary case 1 % nvox > percent difference thresh im = ud.npx(:,imsel); mm = ud.mnpx; case 2 % sum percent difference im = ud.px(:,imsel); mm = ud.mpx; case 3 % sum squared difference im = ud.sx(:,imsel); mm = ud.msx; case 4 % nvox > standard difference thresh im = ud.ndx(:,imsel); mm = ud.mndx; case 5 % sum standard difference im = ud.dx(:,imsel); mm = ud.mdx; end switch opts.mapping case 1 % log im = log(im); mm = log(mm); case 2 % linear end switch opts.grouping case 1 % per image mx = mm(2,imsel); mn = mm(1,imsel); case 2 % per b value mx = zeros(1,numel(imsel)); mn = zeros(1,numel(imsel)); for k = 1:numel(ud.dti.ub) sel = ud.dti.ubj==k; mx(sel(imsel)) = max(mm(2,sel)); mn(sel(imsel)) = min(mm(1,sel)); end case 3 % all images mx = max(mm(2,:))*ones(1,numel(imsel)); mn = min(mm(1,:))*ones(1,numel(imsel)); end function summary_display(ud) [im,mx,mn] = summary_display_info(ud,1:size(ud.dx,2)); mx = repmat(mx, size(im,1),1); mn = repmat(mn, size(im,1),1); im = (im-mn)./(mx-mn); set(ud.im,'cdata',scaletocmap(im)); function summary_cb_display(ud) [im,mx,mn,opts] = summary_display_info(ud,ud.cp(1)); switch opts.mapping case 1 % log labels = exp([mn mx]); case 2 % linear labels = [mn mx]; end sp = min(1,(mx-mn)/20); imagesc(scaletocmap((mn:sp:mx)'),'parent',ud.cb); yl = get(ud.cb,'ylim'); set(ud.cb,'xtick',[],'ydir','normal','ytick',yl,'ytickl',labels,'yaxisl','right') highlight_cb(ud); function image_display(ud) spm_orthviews('Reset'); spm_orthviews('Image',ud.V(ud.cp(1)),[0.01 0.01 .48 .49]); spm_orthviews('Image',ud.mV(ud.cp(1)),[.51 0.01 .48 .49]); spm_orthviews('interp',0); spm_orthviews('space',1); spm_orthviews('window',1:2,ud.win(ud.cp(1),:)); spm_orthviews('register',ud.hReg); spm_orthviews('addcontext'); function xyz_register(cmd, varargin) % spm_XYZreg 'SetCoords' callback spm('pointer','watch'); ax = varargin{2}; ud = get(ax, 'userdata'); tmp = round(ud.V(ud.cp(1)).mat\[varargin{1};1]); if tmp(3) ~= ud.cp(2) ud.cp(2) = tmp(3); % update slice display highlight_cs(ud); end set(ax,'userdata',ud); spm('pointer','arrow'); function summary_review(ob,ev) % ButtonDownFcn for image axis if strcmp(get(gcbf,'selectiontype'),'normal') spm('pointer','watch'); ud = get(ob, 'userdata'); ocp = ud.cp; ud.cp = round(get(ob, 'currentpoint')); ud.cp = ud.cp(1,1:2); % keep row/column if ocp(1) ~= ud.cp(1) image_display(ud); summary_cb_display(ud); end if any(ocp ~= ud.cp) % update slice display % reposition to same (x,y) voxel as in previous slice oposvx = ud.V(ud.cp(1)).mat\[spm_orthviews('pos');1]; posmm = ud.V(ud.cp(1)).mat*[oposvx(1:2); ud.cp(2);1]; spm_XYZreg('SetCoords',posmm(1:3),ud.hReg,ud.ax); highlight_cs(ud); end set(ob,'userdata',ud); spm('pointer','arrow'); end function summary_map_group(tag, varargin) % Context menu callback % Toggle 'checked' property of selected menu item, unset others ud = get(findobj(spm_figure('GetWin','Graphics'),'tag',mfilename),'userdata'); set(findobj(spm_figure('GetWin','Graphics'),'tag',[mfilename '_' lower(tag)]),'checked','off'); set(gcbo,'checked','on'); summary_display(ud); summary_cb_display(ud); function image_blobs(tag, varargin) % Context menu callback % Add blobs to mean image display global st ud = get(findobj(spm_figure('FindWin','Graphics'),'tag',mfilename),'UserData'); [X1 xyz] = spm_read_vols(ud.V(ud.cp(1))); X2 = spm_read_vols(ud.mV(ud.cp(1))); spm_orthviews('rmblobs',2); switch lower(tag) case 'diff' dVOL = (X1-X2).^2; xyz = st.vols{2}.mat\[xyz;ones(1,size(xyz,2))]; spm_orthviews('addcolouredblobs',2,xyz(1:3,:),dVOL(:),st.vols{2}.mat,[1 0 0],'Squared difference'); spm_orthviews('AddColourBar',2,1); case 'std' Xs = sqrt(spm_read_vols(ud.sV(ud.cp(1)))); dVOL = abs(X1-X2)./Xs; dVOL(Xs==0) = 0; dVOL(dVOL>4) = 4; sel = dVOL(:)>1; if any(sel) xyz = st.vols{2}.mat\[xyz(:,sel);ones(1,sum(sel))]; dVOL = dVOL(sel); spm_orthviews('addblobs',2,xyz(1:3,:),dVOL(:),st.vols{2}.mat,'Standard difference'); st.vols{2}.blobs{1}.min = 1; end end spm_orthviews('redraw',2) function setup_cm(ax,fg,opts) cm = uicontextmenu('parent',fg); cm1 = uimenu(cm, 'Label','Difference Summary'); tag = 'summary'; cm2(5) = uimenu(cm1, 'Label','Sum standard Differences', 'Callback',@(ob,ev)summary_map_group(tag,ob,ev),'tag',[mfilename '_' tag]); cm2(4) = uimenu(cm1, 'Label','#vox > Standard Difference Threshold', 'Callback',@(ob,ev)summary_map_group(tag,ob,ev),'tag',[mfilename '_' tag]); cm2(3) = uimenu(cm1, 'Label','Sum squared Differences', 'Callback',@(ob,ev)summary_map_group(tag,ob,ev),'tag',[mfilename '_' tag]); cm2(2) = uimenu(cm1, 'Label','Sum percent Differences', 'Callback',@(ob,ev)summary_map_group(tag,ob,ev),'tag',[mfilename '_' tag]); cm2(1) = uimenu(cm1, 'Label','#vox > Percent Difference Threshold', 'Callback',@(ob,ev)summary_map_group(tag,ob,ev),'tag',[mfilename '_' tag]); set(cm2(opts.(tag)),'checked','on'); cm1 = uimenu(cm,'label','Intensity Mapping'); tag = 'mapping'; cm2(2) = uimenu(cm1,'label','Linear','Callback',@(ob,ev)summary_map_group(tag,ob,ev),'tag',[mfilename '_' tag]); cm2(1) = uimenu(cm1,'label','Log','Callback',@(ob,ev)summary_map_group(tag,ob,ev),'tag',[mfilename '_' tag]); set(cm2(opts.(tag)),'checked','on'); cm1 = uimenu(cm,'label','Image Grouping'); tag = 'grouping'; cm2(3) = uimenu(cm1,'label','All Data','Callback',@(ob,ev)summary_map_group(tag,ob,ev),'tag',[mfilename '_' tag]); cm2(2) = uimenu(cm1,'label','Per b-Value','Callback',@(ob,ev)summary_map_group(tag,ob,ev),'tag',[mfilename '_' tag]); cm2(1) = uimenu(cm1,'label','Per Image','Callback',@(ob,ev)summary_map_group(tag,ob,ev),'tag',[mfilename '_' tag]); set(cm2(opts.(tag)),'checked','on'); cm1 = uimenu(cm,'label','Overlay'); uimenu(cm1,'label','Squared Difference','Callback',@(ob,ev)image_blobs('diff',ob,ev)); uimenu(cm1,'label','Standard Difference','Callback',@(ob,ev)image_blobs('std',ob,ev)); set(ax,'Uicontextmenu',cm) function highlight_cs(ud) % highlight current slice/volume location hold(ud.ax,'on'); delete(findobj(ud.ax,'tag','highlight')); line(ud.cp(1)+[-.5 -.5 +.5 +.5 -.5], ud.cp(2)+[-.5 +.5 +.5 -.5 -.5], 'parent',ud.ax, 'color','w', 'linewidth',3, 'tag','highlight','hittest','off'); hold(ud.ax,'off'); highlight_cb(ud); function highlight_cb(ud) % highlight current slice value in color bar [im,mx,mn] = summary_display_info(ud,ud.cp(1)); im = im(ud.cp(2)); hold(ud.cb,'on'); delete(findobj(ud.cb,'tag','highlight')); yl = get(ud.cb,'ylim'); im = (yl(2)-yl(1))*(im-mn)./(mx-mn)+yl(1); line(get(ud.cb,'xlim'), [im im], 'parent',ud.cb, 'color','w', 'linewidth',3, 'tag','highlight','hittest','off'); hold(ud.cb,'off'); function rgb = scaletocmap(ind) tmpf = figure('visible','off'); tmpax = axes('parent',tmpf); cmap = colormap(tmpax,'jet'); delete(tmpf); ind=round(63*(ind-min(ind(:)))./(max(ind(:))-min(ind(:)))+1); ind(~isfinite(ind))=1; rgb = zeros([size(ind) 3]); for k = 1:3 rgb(:,:,k) = reshape(cmap(ind, k), size(ind)); end
github
philippboehmsturm/antx-master
dti_surf_decomp.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Visualisation/dti_surf_decomp.m
2,207
utf_8
83315266d87402226268df29007fff04
function dti_surf_decomp(D,x,l) % display a full tensor and its decomposition SD=zeros(size(D)); nrows = ceil(sqrt(length(l)+2)); ncols = ceil(sqrt(length(l)+2)); while (nrows-1)*ncols >= length(l)+2 nrows = nrows - 1; end; order = ndims(D); [Hind mult iHperm]=dti_dt_order(order); f = figure; for k=1:length(l) tx=l(k)*tensor_gop(x{k}); D=D-tx; SD=SD+tx; dwbch(k).data=dti_dt_reshape(tx,ndims(D),iHperm); dwbch(k).f = f; figure(f); dwbch(k).ax = subplot(nrows,ncols,k); view(3); end; dwbch(length(l)+1).data=dti_dt_reshape(D,ndims(D),iHperm); dwbch(length(l)+1).ax = subplot(nrows,ncols,length(l)+1); view(3); dwbch(length(l)+2).data=dti_dt_reshape(SD,ndims(D),iHperm); dwbch(length(l)+2).ax = subplot(nrows,ncols,length(l)+2); view(3); [dwbch.order] = deal(ndims(D)); [dwbch.scaling] = deal(0); [dwbch.register] = deal(0); [dwbch.res] = deal(.1); [dwbch.f] = deal(f); [dwres dwbch]=dti_surface(dwbch); [dwbch.scaling]=deal(subsref(max(cat(1,dwres.scaling)),struct('type','()','subs',{{2}}))); [dwres dwbch]=dti_surface(dwbch); axma = [-inf -inf -inf]; axmi = [inf inf inf]; for k=1:length(l) title(dwbch(k).ax,sprintf('Component %d', k)); axc = axis(dwbch(k).ax); axma = max(axma,axc([2 4 6])); axmi = min(axmi,axc([1 3 5])); end; title(dwbch(length(l)+1).ax,'Residual tensor'); axc = axis(dwbch(length(l)+1).ax); axma = max(axma,axc([2 4 6])); axmi = min(axmi,axc([1 3 5])); title(dwbch(length(l)+2).ax,'Fitted tensor'); axc = axis(dwbch(length(l)+2).ax); axma = max(axma,axc([2 4 6])); axmi = min(axmi,axc([1 3 5])); for k=1:(numel(dwbch)) axis(dwbch(k).ax,[axmi(1) axma(1) axmi(2) axma(2) axmi(3) axma(3)]); if k<=numel(x) plotxdirs(x(k),axmi,axma,dwbch(k).ax); end; end; plotxdirs(x,axmi,axma,dwbch(length(l)+2).ax); function plotxdirs(x,axmi,axma,ax) return; % do nothing hold on; for k=1:length(x) s(1:3)=(axma-1)'./x{k}(:,1); s(4:6)=(axmi-1)'./x{k}(:,1); sp=min(s(s>0)); sn=max(s(s<0)); l(k)=line([sn*x{k}(1,1) sp*x{k}(1,1)]+1,... [sn*x{k}(2,1) sp*x{k}(2,1)]+1,... [sn*x{k}(3,1) sp*x{k}(3,1)]+1,'Parent',ax); % dw surface has center % at voxel (1,1,1) end;
github
philippboehmsturm/antx-master
dti_dw_generate.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Simulations/dti_dw_generate.m
10,420
utf_8
14b2ae9008e16b91cf39091535470a36
function varargout = dti_dw_generate(bch) % generate simulated diffusion weighted data % % Batch processing: % FORMAT function dti_dw_generate(bch) % ====== % Input argument: % bch struct with fields %/*\begin{description}*/ %/*\item[*/ .dim/*]*/ [Inf Inf Inf] or [xdim ydim zdim] dimension of output images %/*\item[*/ .res/*]*/ sphere resolution (determines number of evaluated % diffusion directions) %/*\item[*/ .b/*]*/ b Value %/*\item[*/ .i0/*]*/ Intensity of b0 image %/*\item[*/ .lines/*]*/ lines substructures %/*\item[*/ .prefix/*]*/ filename stub %/*\item[*/ .swd/*]*/ working directory %/*\end{description}*/ % lines substructure %/*\begin{description}*/ %/*\item[*/ .t/*]*/ 1xN evaluation points for line functions, defaults to [1:10] %/*\item[*/ .fxfun, .fyfun, .fzfun/*]*/ function specifications %/*\item[*/ .iso/*]*/ ratio of isotropic diffusion (0 no isotropic diffusion, % 1 no directional dependence) %/*\item[*/ .fwhm/*]*/ exponential weight for non-isotropic diffusion (0 no % weighting, +Inf only signal along line) %/*\end{description}*/ % This function generates fibres according to the specifications % given in its input argument. Each specification describes a line in 3-D % space, parameterised by lines.t. % % fxfun, fyfun and fzfun can be the following functions that take as % input a parameter t and an struct array with additional parameters: % 'linear' % ret=a*t + off; % 'tanhp' % ret=r*tanh(f*t+ph) + off; % 'sinp' % ret=r*sin(f*t+ph) + off; % 'cosp' % ret=r*cos(f*t+ph) + off; % % fxfun, fyfun, fzfun can alternatively be specified directly as arrays % fxfun(t), fyfun(t), fzfun(t) of size nlines-by-numel(t). In that case, % no evaluation of fxprm, fyprm, fzprm takes place. It is checked, that % the length of each array line matches the length of lines.t. % All parameters can be specified as 1x1, Mx1, 1xN, or MxN, where N must % match the number of evaluation points in t. A line will be derived for % each combination of parameters. % At each grid point (rounded x(t),y(t),z(t)) the 1st derivative of the % line function (i.e. line direction) is computed. The diffusion gradient % directions are assumed to lie on a sphere produced by Matlab's % isosurface command. The sphere is evaluated on a grid % [-1:bch.res:1]. % The diffusivity profile of each line is assumed to depend only on the % angle between line direction and current diffusion gradient % direction. When multiple lines are running through the same voxel, % diffusivities will be averaged. % A set of diffusion weighted images will be written to disk consisting % of a b0 image and one image for each diffusion gradient direction. % These images can then be used as input to the tensor estimation % routines. If finite dimensions for the images are given, lines will be % clipped to fit into the image. Otherwise, the maximum dimensions are % determined by the maximum line coordinates. % % This function is part of the diffusion toolbox for SPM5. For general help % about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id: dti_dw_generate.m 706M 2010-04-08 13:53:37Z (lokal) $ rev = '$Revision: 706M $'; funcname = 'DWI generator'; % function preliminaries if ischar(bch) switch lower(bch) case 'vfiles', varargout{1} = @vfiles_and_sphere; return; otherwise error('Unknown command option: %s', bch); end; end; Finter=spm_figure('GetWin','Interactive'); spm_input('!DeleteInputObj'); Finter=spm('FigName',funcname,Finter); SPMid = spm('FnBanner',mfilename,rev); % function code starts here % compute lines from spec spm_progress_bar('init', numel(bch.lines),... 'Computing line coordinates',... 'Lines completed'); cul = 1; for cl = 1:numel(bch.lines) tmpx = evalfun(bch.lines(cl).fxfun,bch.lines(cl).t); tmpy = evalfun(bch.lines(cl).fyfun,bch.lines(cl).t); tmpz = evalfun(bch.lines(cl).fzfun,bch.lines(cl).t); % now combine into lines - external counter cul for cx = 1:size(tmpx,1) for cy = 1:size(tmpy,1) for cz = 1:size(tmpz,1) res.x{cul} = tmpx(cx,:); res.y{cul} = tmpy(cy,:); res.z{cul} = tmpz(cz,:); lind(cul) = cl; cul = cul+1; end; end; end; spm_progress_bar('set',cl); end; nl = cul-1; % differentiate lines spm_progress_bar('init', nl,... 'Computing line differentials',... 'Lines completed'); dx = cell(cl,1); dy = cell(cl,1); dz = cell(cl,1); mxx = zeros(cl,1); mnx = zeros(cl,1); mxy = zeros(cl,1); mny = zeros(cl,1); mxz = zeros(cl,1); mnz = zeros(cl,1); for cl = 1:nl dx{cl} = diff(res.x{cl}); dy{cl} = diff(res.y{cl}); dz{cl} = diff(res.z{cl}); dl = sqrt(dx{cl}.^2+dy{cl}.^2+dz{cl}.^2); dx{cl} = dx{cl}./dl; dy{cl} = dy{cl}./dl; dz{cl} = dz{cl}./dl; % estimate an initial bounding box cmx = max(ceil(spm_matrix(bch.movprms(1,:))*... [res.x{cl}; res.y{cl}; res.z{cl}; ... ones(size(res.z{cl}))]),[],2); cmn = min(ceil(spm_matrix(bch.movprms(1,:))*... [res.x{cl}; res.y{cl}; res.z{cl}; ... ones(size(res.z{cl}))]),[],2); mxx(cl) = cmx(1); mxy(cl) = cmx(2); mxz(cl) = cmx(3); mnx(cl) = cmn(1); mny(cl) = cmn(2); mnz(cl) = cmn(3); spm_progress_bar('set',cl); end; spm_progress_bar('clear'); [res.files F g] = vfiles_and_sphere(bch); % prepend b0 weighting, create b vector b = bch.b*ones(size(g,1)+1,1); b(1) = 0; g = [0 0 0; g]; cdim = bch.dim; mxdim = [min(mnx) min(mny) min(mnz); max(mxx) max(mxy) max(mxz)]; cdim(~isfinite(cdim)) = mxdim(~isfinite(cdim)); % create image information mat = eye(4); mat(1:3,4) = cdim(1,:)'; ref = eye(4); % check movement params if size(bch.movprms,1) == 1 movprms = repmat(bch.movprms,size(g,1),1); elseif size(bch.movprms,1) == size(g,1) movprms = bch.movprms; else error('Wrong number of movement parameters'); end; imdim = ceil(diff(cdim)); % loop over directions im0 = zeros(imdim); spm_progress_bar('init', size(g,1),... 'Evaluating diffusion profiles',... 'Directions completed'); for d = 1:size(g,1) im = zeros(imdim); im1 = zeros(imdim); wt = zeros(imdim); RM = spm_matrix(movprms(d,:)); for cl = 1:nl rxyz = round(mat\RM*[res.x{cl}; res.y{cl}; res.z{cl}; ones(size(res.z{cl}))]); limdim = repmat(imdim,size(bch.lines(lind(cl)).t,2),1); sel = all(rxyz(1:3,:)'<=limdim,2) & ... all(rxyz(1:3,:)' > 0,2); sel = find(sel(1:end-1)); imsel = sub2ind(imdim, rxyz(1,sel), rxyz(2,sel), rxyz(3,sel)); if b(d) > 0 lg = repmat(g(d,:),size(bch.lines(lind(cl)).t,2)-1,1); rdxyz = RM*[dx{cl}; dy{cl}; dz{cl}; zeros(size(dz{cl}))]; ang = abs(sum(rdxyz(1:3,:)' .* lg,2))'; im(imsel) = im(imsel) + bch.lines(lind(cl)).D* ... (bch.lines(lind(cl)).iso + (1-bch.lines(lind(cl)).iso)* ... ang(sel).*exp(-bch.lines(lind(cl)).fwhm*(1-ang(sel)).^2)); wt(imsel) = wt(imsel)+1; else im1(imsel) = 1; end end; [p n e v] = spm_fileparts(res.files{d}); V = struct('fname',fullfile(p,[n e]), ... 'dim',imdim, 'dt',[spm_type('float32') spm_platform('bigend')], 'mat',mat,... 'pinfo',[Inf;Inf;0]); V = spm_create_vol(V); if b(d) > 0 wt(wt==0)=1; im1 = exp(-b(d)*im./wt); im1(im==0)=0; end V = spm_write_vol(V,bch.i0*(bch.nr*rand(imdim)+im1)); dti_get_dtidata(V.fname, struct('b',bch.b, 'g',g(d,:),'mat',mat,'ref',ref)); spm_progress_bar('set',d); end; spm_progress_bar('clear'); varargout{1} = res; return; %----------------------------------------------------------------------- % Line evaluation %----------------------------------------------------------------------- function ret=evalfun(fun,t) % returns a #parameter-combinations-by-size(t,2) array of line points if isfield(fun,'data') if size(fun.data,2)==size(t,2) ret = fun.data; else error('wrong number of elements in function data'); end; else funname = fieldnames(fun); ret = feval(funname{1}, t, fun.(funname{1})); end; return function ret=linear(t,prm) na = size(prm.a,1); no = size(prm.off,1); ret = zeros(na*no,size(t,2)); for ca = 1:na for co = 1:no ret((ca-1)*na+co,:)=prm.a(ca,:).*t + prm.off(co,:); end; end; return; function ret=tanhp(t,prm) nr = size(prm.r,1); nf = size(prm.f,1); np = size(prm.ph,1); no = size(prm.off,1); ret = zeros(nr*nf*np*no,size(t,2)); for cr = 1:nr for cf = 1:nf for cp = 1:np for co = 1:no ret((((cr-1)*nr+cf-1)*nf+cp-1)*np+co,:) = ... prm.r(cr,:).*tanh(prm.f(cf,:).*t+prm.ph(cp,:))... + prm.off(co,:); end; end; end; end; return; function ret=sinp(t,prm) nr = size(prm.r,1); nf = size(prm.f,1); np = size(prm.ph,1); no = size(prm.off,1); ret = zeros(nr*nf*np*no,size(t,2)); for cr = 1:nr for cf = 1:nf for cp = 1:np for co = 1:no ret((((cr-1)*nr+cf-1)*nf+cp-1)*np+co,:) = ... prm.r(cr,:).*sin(prm.f(cf,:).*t+prm.ph(cp,:))... + prm.off(co,:); end; end; end; end; return; %----------------------------------------------------------------------- % virtual files %----------------------------------------------------------------------- function varargout = vfiles_and_sphere(bch) [xs ys zs] = ndgrid(-1:bch.res:1); [F g] = isosurface(xs,ys,zs,xs.^2+ys.^2+zs.^2,1); g = g./(sqrt(sum(g.^2,2))*[1 1 1]); fileformat = sprintf('sim%s_%%0%dd.nii,1', bch.prefix, ... floor(log10(size(g,1)))+1); vf = cell(size(g,1)+1,1); for k = 0:size(g,1) vf{k+1} = fullfile(bch.swd{1},sprintf(fileformat,k)); end; varargout{1} = vf; if nargout == 3 varargout{2} = F; varargout{3} = g; end;
github
philippboehmsturm/antx-master
dti_simu_rot.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Simulations/dti_simu_rot.m
3,291
utf_8
4713e57a55cb425c81676f9c0eeef50d
function [faD, faMD, divMD, Dsim, rots] = dti_simu_rot(varargin) % function rots = dti_simu_rot(evals,mxrot,pflag) % % evals: mx3 matrix eigenvalues of original tensor (default [1 1 1]) % mxrot: nx1 vector of maximum rotation in degrees % pflag: plot results? (default no) % % This function is part of the diffusion toolbox for SPM5. For general help % about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id$ rev='$Revision$'; evals = [1 1 1]; mxrot = 10; pflag = 0; if nargin >= 1 switch size(varargin{1},2) case 3 evals = varargin{1}; case 6 clear evals; Dstart = varargin{1}; otherwise error('Need 3-vector of eigenvalues or 6 tensor elements as input'); end; ntens = size(varargin{1},1); end; if nargin >= 2 mxrot = varargin{2}; end; if nargin >= 3 pflag = varargin{3}; end; for j=1:ntens for l = 1:length(mxrot) if exist('evals','var') D = diag(evals(j,:)); else D = [Dstart(j,1) Dstart(j,4) Dstart(j,5);... Dstart(j,4) Dstart(j,2) Dstart(j,6);... Dstart(j,5) Dstart(j,6) Dstart(j,3)]; end; [Dsim{l,j} rots{l,j}]=gen_time_series(D,'rot_sym',mxrot(l)/180*pi,140,1); MD = mean(Dsim{l,j},3); [v,d] = eig(MD); d=diag(d); [tmp ind]=sort(-d); [vo,do] = eig(D); do=diag(do); [tmp,indo]=sort(-do); divMD(j,l) = sum(vo(:,indo(1))'*v(:,ind(1))); faMD(j,l) = sqrt(3/2*sum(sum( (MD-trace(MD)/3*eye(3)).^2 ))... /sum(sum(MD.^2))); if pflag plot_time_series(Dsim{l,j},rots{l,j},mxrot(l)); end; end; faD(j) = sqrt(3/2*sum(sum( (D(:,:,1)-trace(D(:,:,1))/3*eye(3)).^2 ))... /sum(sum(D(:,:,1).^2))); end; [tmp,ind] = sort(faD); faD=faD(ind); faMD=faMD(ind,:); divMD=divMD(ind,:); figure;subplot(2,1,1);plot(mxrot,faMD./repmat(faD',1,length(mxrot))); subplot(2,1,2);plot(mxrot,acos(abs(divMD))*180/pi); legend(num2str(faD')); function [Dsim, rots] = gen_time_series(Dstart, rotfun, mxrot, nruns, itflag) rots = zeros(nruns,3); Dsim(:,:,1) = Dstart; for k=2:nruns rots(k,:) = feval(rotfun,mxrot); if itflag % movement relative to previous time point rots(k,:) = rots(k-1,:)+rots(k,:); end; M = spm_matrix([0 0 0 rots(k,:)]); Dsim(:,:,k) = M(1:3,1:3)'*Dsim(:,:,1)*M(1:3,1:3); end; function rot = rot_sym(mxrot) rot = mxrot*rand(1,3)-mxrot/2; function rot = rot_asym(mxrot) rot = mxrot*rand(1,3)-3/7*mxrot; function plot_time_series(D,rots,mxrot) f=figure; subplot(1,2,1); view(3); p0 = [0 0 0]; [v,d] = eig(D(:,:,1)); d=diag(d); dl=line([p0;v(:,1)'*d(1)],[p0;v(:,2)'*d(2)],[p0;v(:,3)'*d(3)],... 'Color','r','LineWidth',.2); hold on; for k=2:size(D,3)-1 MD = mean(D(:,:,1:k),3); [v,d] = eig(MD); d=diag(d); dl1=line([p0;v(:,1)'*d(1)],[p0;v(:,2)'*d(2)],[p0;v(:,3)'*d(3)],... 'Color','b','LineWidth',.5); end; MD = mean(D,3); [v,d] = eig(MD); d=diag(d); dl1=line([p0;v(:,1)'*d(1)],[p0;v(:,2)'*d(2)],[p0;v(:,3)'*d(3)],... 'Color','m','LineWidth',2); mx=max(abs(axis)); axis([-mx mx -mx mx -mx mx]); axis square; subplot(1,2,2); plot(rots*180/pi); xlabel(sprintf('Maximum rotation %f degrees',mxrot));
github
philippboehmsturm/antx-master
dti_run_parcellation.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Parcellation/dti_run_parcellation.m
8,801
utf_8
aad7ce031463c97b5ae2c7ab495e2c1a
function varargout = dti_run_parcellation(cmd, varargin) % Template function to implement callbacks for an cfg_exbranch. The calling % syntax is % varargout = cfg_run_template(cmd, varargin) % where cmd is one of % 'run' - out = cfg_run_template('run', job) % Run a job, and return its output argument % 'vout' - dep = cfg_run_template('vout', job) % Examine a job structure with all leafs present and return an % array of cfg_dep objects. % 'check' - str = cfg_run_template('check', subcmd, subjob) % Examine a part of a fully filled job structure. Return an empty % string if everything is ok, or a string describing the check % error. subcmd should be a string that identifies the part of % the configuration to be checked. % 'defaults' - defval = cfg_run_template('defaults', key) % Retrieve defaults value. key must be a sequence of dot % delimited field names into the internal def struct which is % kept in function local_def. An error is returned if no % matching field is found. % cfg_run_template('defaults', key, newval) % Set the specified field in the internal def struct to a new % value. % Application specific code needs to be inserted at the following places: % 'run' - main switch statement: code to compute the results, based on % a filled job % 'vout' - main switch statement: code to compute cfg_dep array, based % on a job structure that has all leafs, but not necessarily % any values filled in % 'check' - create and populate switch subcmd switchyard % 'defaults' - modify initialisation of defaults in subfunction local_defs % Callbacks can be constructed using anonymous function handles like this: % 'run' - @(job)cfg_run_template('run', job) % 'vout' - @(job)cfg_run_template('vout', job) % 'check' - @(job)cfg_run_template('check', 'subcmd', job) % 'defaults' - @(val)cfg_run_template('defaults', 'defstr', val{:}) % Note the list expansion val{:} - this is used to emulate a % varargin call in this function handle. % % This code is part of a batch job configuration system for MATLAB. See % help matlabbatch % for a general overview. %_______________________________________________________________________ % Copyright (C) 2007 Freiburg Brain Imaging % Volkmar Glauche % $Id: cfg_run_template.m 315 2008-07-14 14:34:05Z glauche $ rev = '$Rev: 315 $'; %#ok if ischar(cmd) switch lower(cmd) case 'run' job = local_getjob(varargin{1}); % do computation, return results in variable out V = spm_vol(char(job.tracts)); Vm= spm_vol(char(job.mask)); spm_check_orientations([Vm;V(:)]); [vx vy vz] = ind2sub(Vm.dim(1:3),find(spm_read_vols(Vm))); dat = zeros(numel(V),numel(vx),'single'); for k = 1:numel(V) tmp = spm_sample_vol(V(k), vx(:)', vy(:)', vz(:)', 0); tmp = tmp./max(tmp(:));%scale to max zind = tmp < eps|~isfinite(tmp); tmp = log(tmp); tmp(zind) = 0; dat(k, :) = single(tmp);%tmp*tmp'; end [priors,means,covs,post] = spm_kmeans(dat,job.clustering.nc, ... job.clustering.init,job.clustering.retcov); out.clustering.dat = dat; out.clustering.priors = priors; out.clustering.means = means; out.clustering.covs = covs; out.clustering.post = post; if isfield(job.reco,'rois') [ms, errStr] = maskstruct_read(job.reco.rois.maskstruct{1}); if ~isempty(errStr) error(errStr); end [sz errStr] = maskstruct_query(ms,'sizeAy'); if ~isempty(errStr) error(errStr); end if numel(job.reco.rois.ind) == 1 && ~isfinite(job.reco.rois.ind) [mno errStr] = maskstruct_query(ms,'maskNo'); if ~isempty(errStr) error(errStr); end ind = 1:mno; else ind = job.reco.rois.ind; end if numel(ind) ~= size(dat,1) error('Number of masks does not match number source images.'); end dnc = floor(log10(job.clustering.nc))+1; [p n e v] = spm_fileparts(job.tracts{1}); [mrs errStr] = maskstruct_query(ms,'getMRMask',1); if ~isempty(errStr) error(errStr); end for k = 1:job.clustering.nc out.ind{k} = ind(logical(post(:,k))); cm = false(sz); for l = out.ind{k} [cm1 errStr] = maskstruct_query(ms,'getMask',l); if ~isempty(errStr) error(errStr); end cm = cm | cm1; end out.parcellation{k} = fullfile(p, sprintf('parc%d_%0*d%s%s', ... job.clustering.nc, ... dnc, k, n, ... e)); mrs.dataAy = cm; mrstruct_to_nifti(mrs, out.parcellation{k}, 'uint8'); end end if nargout > 0 varargout{1} = out; end case 'vout' job = local_getjob(varargin{1}); % initialise empty cfg_dep array dep = cfg_dep; % determine outputs, return cfg_dep array in variable dep dep(1).sname = 'Clustering data struct'; dep(1).src_output = substruct('.','clustering'); dep(1).tgt_spec = cfg_findspec({{'strtype','e'}}); if isfield(job.reco,'rois') dep(2) = cfg_dep; dep(2).sname = 'Parcellation images'; dep(2).src_output = substruct('.','parcellation'); dep(2).tgt_spec = cfg_findspec({{'filter','image', ... 'strtype','e'}}); end if isnumeric(job.clustering.nc) for k = 1:job.clustering.nc dep(k+2) = cfg_dep; dep(k+2).sname = sprintf(['Selection index cluster ' ... '%d'], k); dep(k+2).src_output = substruct('.','ind','{}',{k}); dep(k+2).tgt_spec = cfg_findspec({{'strtype','n'}}); end end varargout{1} = dep; case 'check' if ischar(varargin{1}) subcmd = lower(varargin{1}); subjob = varargin{2}; str = ''; switch subcmd % implement checks, return status string in variable str otherwise cfg_message('unknown:check', ... 'Unknown check subcmd ''%s''.', subcmd); end varargout{1} = str; else cfg_message('ischar:check', 'Subcmd must be a string.'); end case 'defaults' if nargin == 2 varargout{1} = local_defs(varargin{1}); else local_defs(varargin{1:2}); end otherwise cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd); end else cfg_message('ischar:cmd', 'Cmd must be a string.'); end function varargout = local_defs(defstr, defval) persistent defs; if isempty(defs) % initialise defaults end if ischar(defstr) % construct subscript reference struct from dot delimited tag string tags = textscan(defstr,'%s', 'delimiter','.'); subs = struct('type','.','subs',tags{1}'); try cdefval = subsref(local_def, subs); catch cdefval = []; cfg_message('defaults:noval', ... 'No matching defaults value ''%s'' found.', defstr); end if nargin == 1 varargout{1} = cdefval; else defs = subsasgn(defs, subs, defval); end else cfg_message('ischar:defstr', 'Defaults key must be a string.'); end function job = local_getjob(job) if ~isstruct(job) cfg_message('isstruct:job', 'Job must be a struct.'); end
github
philippboehmsturm/antx-master
dti_smarch.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/TensorVoting/dti_smarch.m
6,382
utf_8
c5384f80ec0f9295c3d50d433e20b04b
function FV=dti_smarch(n,S,hiS,loS) % % This function is part of the diffusion toolbox for SPM5. For general help % about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id$ rev = '$Revision$'; FV=struct('F',[],'V',[]); % n: XDIM-by-YDIM-by-ZDIM-by-3 array of surface normals % (represented in VOXEL space) % s: XDIM-by-YDIM-by-ZDIM array of saliencies (eval2-eval3) szS = size(S); %dS(:,:,:,1) = cat(1,S(2:end,:,:),S(end,:,:))-S; %dS(:,:,:,2) = cat(2,S(:,2:end,:),S(:,end,:))-S; %dS(:,:,:,3) = cat(3,S(:,:,2:end),S(:,:,end))-S; dS(:,:,:,1) = (cat(1,S(2:end,:,:),S(end,:,:))-cat(1,S(1,:,:), S(1:end-1,:,:)))/2; dS(:,:,:,2) = (cat(2,S(:,2:end,:),S(:,end,:))-cat(2,S(:,1,:), S(:,1:end-1,:)))/2; dS(:,:,:,3) = (cat(3,S(:,:,2:end),S(:,:,end))-cat(3,S(:,:,1), S(:,:,1:end-1)))/2; h = pqheap('init',S); nFV = 1; while ((S(h.p(1)) > hiS) & (h.N > 0)) maxF = 100; maxV = 1000; cuF = 0; cuV = 0; F = repmat(NaN,[maxF 13]); V = repmat(NaN,[maxV 3]); cuS = double(h.p(1)); [cuSx cuSy cuSz] = ind2sub(szS,cuS); nb = cuS+[-1; 1;... -szS(1); szS(1);... -szS(1)*szS(2);szS(1)*szS(2)]; % initialise neighbourhoud nb = nb([cuSx > 1; cuSx < szS(1); ... cuSy > 1; cuSy < szS(2); ... cuSz > 1; cuSz < szS(3)]); nb = nb((S(nb) > loS) & (h.q(nb) > 0)); % non-visited voxels above loS while cuS~=0 if all([cuSx cuSy cuSz] < szS) % range check [FVtmp C] = SingleSubVoxelMarch(n(cuSx:cuSx+1, cuSy:cuSy+1, ... cuSz:cuSz+1,:),... dS(cuSx:cuSx+1, cuSy:cuSy+1,... cuSz:cuSz+1,:)); if ~isempty(FVtmp.F) addF = size(FVtmp.F,1); addV = size(FVtmp.V,1); FVtmp.V = FVtmp.V + repmat([cuSx cuSy cuSz], [addV 1]); FVtmp.F = FVtmp.F + cuV; if cuF + addF > maxF tmp = F(1:cuF,:); maxF= maxF + 100; F = repmat(NaN,[maxF 13]); F(1:cuF,:) = tmp; end; F(cuF+1:cuF+addF,:) = FVtmp.F; cuF = cuF + addF; if cuV + addV > maxV tmp = V(1:cuV,:); maxV= maxV + 1000; V = repmat(NaN,[maxV 3]); V(1:cuV,:) = tmp; end; V(cuV+1:cuV+addV,:) = FVtmp.V; cuV = cuV + addV; nbrem = cuS+[-1, 1;... -szS(1), szS(1);... -szS(1)*szS(2),szS(1)*szS(2)]; nbrem = nbrem([cuSx > 1, cuSx < szS(1); ... cuSy > 1, cuSy < szS(2); ... cuSz > 1, cuSz < szS(3)] & C==0); else nbrem = cuS+[-1, 1;... -szS(1), szS(1);... -szS(1)*szS(2),szS(1)*szS(2)]; nbrem = nbrem([cuSx > 1, cuSx < szS(1); ... cuSy > 1, cuSy < szS(2); ... cuSz > 1, cuSz < szS(3)]); end; nb = setdiff(nb, nbrem(:)); % remove unconnected neighbours end; tmp = pqheap('delete',S,h,cuS); if ~isempty(nb) cuS = nb(1); [cuSx cuSy cuSz] = ind2sub(szS,cuS); nbtmp = cuS+[-1; 1;... -szS(1); szS(1);... -szS(1)*szS(2);szS(1)*szS(2)]; nbtmp = nbtmp([cuSx > 1; cuSx < szS(1); ... cuSy > 1; cuSy < szS(2); ... cuSz > 1; cuSz < szS(3)]); nbtmp = nbtmp((S(nbtmp) > loS) & (h.q(nbtmp) > 0)); nb = union(nb(2:end),nbtmp); % add to neighbourhoud else cuS = 0; end; end; if cuF > 0 FV(nFV) = struct('F',F(1:cuF,:),'V',V(1:cuV,:)); nFV = nFV +1; end; end; function [FV,C] = SingleSubVoxelMarch(n,dS) FV = struct('V',[],'F',[]); C = []; % normalise direction of normals in cuboid with respect to n(1,1,1,:) ns = ones(2,2,2); for k=1:2 for l=1:2 for m=1:2 ns(k,l,m) = sign(sum(n(1,1,1,:).*n(k,l,m,:))); end; end; end; %ns = sign(sum(repmat(n(1,1,1,:),[2,2,2,1]).*n,4)); for k = 1:3 nn(:,:,:,k) = ns.*n(:,:,:,k); end; q = sum(dS.*nn, 4); c1 = [0 1 0 1]'; c2 = [0 0 1 1]'; zc = cat(1, reshape(q(1,:,:)./(q(1,:,:)-q(2,:,:)),[4 1]),... reshape(q(:,1,:)./(q(:,1,:)-q(:,2,:)),[4 1]),... reshape(q(:,:,1)./(q(:,:,1)-q(:,:,2)),[4 1])); if any(~isfinite(zc(:))) return; end; FV.V = cat(1, cat(2, zc(1:4), c1, c2),... cat(2, c1, zc(5:8), c2),... cat(2, c1, c2, zc(9:12))); edges = repmat(NaN,[12 2]); eind = 1; C = ones(3,2); % connectivity to neighbours zcsel = cat(3,[5 11 7 9; 6 12 8 10]',... % x = const [1 10 3 9; 2 12 4 11]',... % y = const [1 6 2 5; 3 8 4 7]'); % z = const for k = 1:3 % coordinate for l = 1:2 % value of coordinate zc1 = zc(zcsel(:,l,k)); zc1sel = (zc1 > 0) & (zc1 < 1); % zero crossings in voxel? switch sum(zc1sel) case 2 edges(eind,:) = zcsel(zc1sel,l,k)'; eind = eind+1; case 4 switch k case 1 % x = const q1 = squeeze(q(l,:,:)); case 2 % y = const q1 = squeeze(q(:,l,:)); case 3 % z = const q1 = squeeze(q(:,:,l)); end; x = mean(zc1([1 3])); y = mean(zc1([2 4])); if ((1-y)*((1-x)*q1(1,1) + x*q1(2,1)) + ... y*((1-x)*q1(1,2) + x*q1(2,2))) >= 0 edges(eind,:) = zcsel(1:2,l,k)'; edges(eind+1,:) = zcsel(3:4,l,k)'; else edges(eind,:) = zcsel(2:3,l,k)'; edges(eind+1,:) = zcsel([1 4],l,k)'; end; eind = eind+2; otherwise C(k,l)=0; end, end; end; Find = 1; edges = edges(1:eind-1,:); while ~isempty(edges) F = [NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN]; Fcind = 3; F(1:2) = edges(1,:); edges = edges(2:end,:); [i j] = find(edges==F(2)); while ~isempty(i) if length(i)>1 warning('spm_tbx_Diffusion:dti_smarch_EdgeVertex',... 'More than one edge per Vertex left'); end; if j == 1 F(Fcind) = edges(i,2); else F(Fcind) = edges(i,1); end; edges = [edges(1:i-1,:); edges(i+1:end,:)]; [i j] = find(edges==F(Fcind)); Fcind = Fcind+1; end; if sum(isfinite(F)) > 2 FV.F(Find,:) = F; Find = Find+1; end; end; function ret = misc(x) qV = [1 1 1; 2 1 1; 1 2 1; 2 2 1; 1 1 2; 2 1 2; 1 2 2; 2 2 2]; qF = [1 2 4 3; 1 2 6 5; 1 5 7 3; 5 6 8 7; 2 4 8 6; 3 4 8 7]; zcF= cat(3, [1 1 1; 2 1 3; 1 2 1; 1 1 3],... [1 1 1; 2 1 2; 2 1 1; 1 1 2],... [1 1 2; 1 2 3; 1 2 2; 1 1 3],... [1 2 1; 2 2 2; 2 2 1; 1 2 2],... [2 1 3; 2 2 2; 2 2 3; 2 1 2],... [2 2 3; 2 2 1; 1 2 3; 2 1 1]);
github
philippboehmsturm/antx-master
dti_cmarch.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/TensorVoting/dti_cmarch.m
9,862
utf_8
335a363c4facfc2aad7044da190813f4
function Lines=dti_cmarch(Vt,S,hiS,loS,minlen) % Vt: 3-by-1 cell array of volume handles or XDIM-by-YDIM-by-ZDIM arrays of % vector components for surface normals (represented in VOXEL space) % S: XDIM-by-YDIM-by-ZDIM array of saliencies (eg. eval1-eval2) % % This function is part of the diffusion toolbox for SPM5. For general help % about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id$ rev = '$Revision$'; szS = size(S); h = pqheap('init',S); nL = 1; while ((S(h.p(1)) > hiS) & (h.N > 0)) maxL = 100; cuL = 0; cuL1 = 0; L = repmat(NaN,[maxL 3]); L1 = []; rev = 0; cuS = double(h.p(1)); [cuSx cuSy cuSz] = ind2sub(szS,cuS); stS = cuS; % save start coordinate stSx = cuSx; stSy = cuSy; stSz = cuSz; while cuS~=0 if ~any([cuSx cuSy cuSz] > szS-2) &... ~any([cuSx cuSy cuSz] == 1) % range check dS1(1,1,1,:) = [S(cuSx ,cuSy ,cuSz )-S(cuSx-1,cuSy ,cuSz ); S(cuSx ,cuSy ,cuSz )-S(cuSx ,cuSy-1,cuSz ); S(cuSx ,cuSy ,cuSz )-S(cuSx ,cuSy ,cuSz-1)]; dS1(1,1,2,:) = [S(cuSx ,cuSy ,cuSz )-S(cuSx-1,cuSy ,cuSz ); S(cuSx ,cuSy ,cuSz )-S(cuSx ,cuSy-1,cuSz ); S(cuSx ,cuSy ,cuSz+2)-S(cuSx ,cuSy ,cuSz+1)]; dS1(1,2,1,:) = [S(cuSx ,cuSy ,cuSz )-S(cuSx-1,cuSy ,cuSz ); S(cuSx ,cuSy+2,cuSz )-S(cuSx ,cuSy+1,cuSz ); S(cuSx ,cuSy ,cuSz )-S(cuSx ,cuSy ,cuSz-1)]; dS1(1,2,2,:) = [S(cuSx ,cuSy ,cuSz )-S(cuSx-1,cuSy ,cuSz ); S(cuSx ,cuSy+2,cuSz )-S(cuSx ,cuSy+1,cuSz ); S(cuSx ,cuSy ,cuSz+2)-S(cuSx ,cuSy ,cuSz+1)]; dS1(2,1,1,:) = [S(cuSx+2,cuSy ,cuSz )-S(cuSx+1,cuSy ,cuSz ); S(cuSx ,cuSy ,cuSz )-S(cuSx ,cuSy-1,cuSz ); S(cuSx ,cuSy ,cuSz )-S(cuSx ,cuSy ,cuSz-1)]; dS1(2,1,2,:) = [S(cuSx+2,cuSy ,cuSz )-S(cuSx+1,cuSy ,cuSz ); S(cuSx ,cuSy ,cuSz )-S(cuSx ,cuSy-1,cuSz ); S(cuSx ,cuSy ,cuSz+2)-S(cuSx ,cuSy ,cuSz+1)]; dS1(2,2,1,:) = [S(cuSx+2,cuSy ,cuSz )-S(cuSx+1,cuSy ,cuSz ); S(cuSx ,cuSy+2,cuSz )-S(cuSx ,cuSy+1,cuSz ); S(cuSx ,cuSy ,cuSz )-S(cuSx ,cuSy ,cuSz-1)]; dS1(2,2,2,:) = [S(cuSx+2,cuSy ,cuSz )-S(cuSx+1,cuSy ,cuSz ); S(cuSx ,cuSy+2,cuSz )-S(cuSx ,cuSy+1,cuSz ); S(cuSx ,cuSy ,cuSz+2)-S(cuSx ,cuSy ,cuSz+1)]; dS(:,:,:,1) = S([cuSx cuSx+1]+1, [cuSy cuSy+1] , [cuSz cuSz+1] ) - ... S([cuSx cuSx+1] , [cuSy cuSy+1] , [cuSz cuSz+1] ); dS(:,:,:,2) = S([cuSx cuSx+1] , [cuSy cuSy+1]+1, [cuSz cuSz+1] ) - ... S([cuSx cuSx+1] , [cuSy cuSy+1] , [cuSz cuSz+1] ); dS(:,:,:,3) = S([cuSx cuSx+1] , [cuSy cuSy+1] , [cuSz cuSz+1]+1) - ... S([cuSx cuSx+1] , [cuSy cuSy+1] , [cuSz cuSz+1] ); [cxi cyi czi] = ndgrid(cuSx:cuSx+1, cuSy:cuSy+1, cuSz:cuSz+1); t1(:,:,1)=spm_sample_vol(Vt{1},cxi,cyi,czi,0); t1(:,:,2)=spm_sample_vol(Vt{2},cxi,cyi,czi,0); t1(:,:,3)=spm_sample_vol(Vt{3},cxi,cyi,czi,0); t=reshape(t1,[2 2 2 3]); Ltmp = SingleSubVoxelCMarch(t,... dS);%(cuSx:cuSx+1, cuSy:cuSy+1,... % cuSz:cuSz+1,:)); % dS1); else Ltmp = []; end; tmp = pqheap('delete',S,h,cuS); if ~isempty(Ltmp) % add point to line segment if cuL == maxL tmp = L(1:cuL,:); maxL = maxL + 100; L = repmat(NaN, [maxL 3]); L(1:cuL,:) = tmp; end; cuL = cuL+1; fprintf('\rLine %d segment %2.0d',nL,cuL+cuL1); L(cuL,:) = Ltmp+[cuSx cuSy cuSz]; if cuL > 1 d = squeeze(L(cuL,:) - L(cuL-1,:)); else d = squeeze(t(1,1,1,:)); end; dst=NaN*ones(3,1); for k=1:3 if d(k)>0 dst(k) = (1-Ltmp(k))/abs(d(k)); elseif d(k)<0 dst(k) = Ltmp(k)/abs(d(k)); end; end; [tmp ind] = min(dst); switch ind case 1, cuSx = cuSx+sign(d(1)); case 2, cuSy = cuSy+sign(d(2)); case 3, cuSz = cuSz+sign(d(3)); end; if (all([cuSx cuSy cuSz] < szS) & all([cuSx cuSy cuSz] >= 1)) cuS = sub2ind(szS, cuSx, cuSy, cuSz); else Ltmp = []; % FIXME force reversal at volume boundary end; end; if ((S(cuS) < loS) | isempty(Ltmp) | (h.q(cuS) == 0)) if (rev == 0) & (cuL>0) % try other direction d(1) = spm_sample_vol(Vt{1},stSx,stSy,stSz,0); d(2) = spm_sample_vol(Vt{2},stSx,stSy,stSz,0); d(3) = spm_sample_vol(Vt{3},stSx,stSy,stSz,0); dst=NaN*ones(3,1); Ltmp = L(1,:) - [stSx stSy stSz]; for k=1:3 if d(k)>0 dst(k) = (1-Ltmp(k))/abs(d(k)); elseif d(k)<0 dst(k) = Ltmp(k)/abs(d(k)); end; end; [tmp ind] = min(dst); switch ind case 1, cuSx = stSx+sign(d(1)); case 2, cuSy = stSy+sign(d(2)); case 3, cuSz = stSz+sign(d(3)); end; if all([cuSx cuSy cuSz] <= szS) & all([cuSx cuSy cuSz] >= 1) cuS = sub2ind(szS, cuSx, cuSy, cuSz); if (h.q(cuS) == 0) break; end; rev = 1; cuL1 = cuL-1; L1 = L(1:cuL,:); maxL = 100; cuL = 1; L = repmat(NaN, [maxL 3]); if ~isempty(L1) L(1,:) = L1(1,:); end; else % reversal failed cuS = 0; break; end; else % already reversed or no start point found cuS = 0; break; end; end; end; if (cuL+cuL1 > 1) if isempty(L1) Lines{nL} = L(1:cuL,:); else Lines{nL} = [L1(end:-1:1,:); L(2:cuL,:)] ; end; if size(Lines{nL},1) > minlen nL = nL+1; fprintf('\n'); end; end; if h.N == 0 break; end; end; fprintf('\n'); function L = SingleSubVoxelCMarch(t, dS) L = []; if any(~isfinite(t(:))) return; end; % vertex coordinates P = [0 0 0; 0 0 1; 0 1 0; 0 1 1; 1 0 0; 1 0 1; 1 1 0; 1 1 1]' -.5; % edges of cuboid (index into P) E = [ 1 2; 1 3; 1 5; 2 4; 2 6; 3 4; 3 7; 4 8; 5 6; 5 7; 6 8; 7 8]; % normalise direction of tangents in cuboid with respect to t(1,1,1,:) % ns = ones(2,2,2); % for k=1:2 % for l=1:2 % for m=1:2 % ns(k,l,m) = sign(sum(t(1,1,1,:).*t(k,l,m,:))); % if ns(k,l,m) == 0 % ns(k,l,m) = 1; % end; % end; % end; % end; % VG 2002-28-12 ns = sign(sum(repmat(t(1,1,1,:), [2 2 2]).*t, 4)); ns(find(ns==0)) = 1; tn = [0;0;0]; for k = 1:3 tn(k) = sum(sum(sum(ns.*t(:,:,:,k))))/8; end; if all(tn==0) fprintf('tn==0\n'); return; end; %tn=tn./sqrt(sum(tn.^2)); u = repmat(NaN,[12 1]); % u values Eu = repmat(NaN,[12 1]); % corresponding edges Q = repmat(NaN,[3 12]); nQ = 0; % compute intersection points of tangential plane for k = 1:12 d = P(:,E(k,2)) - P(:,E(k,1)); td = sum(tn.*d); if td ~= 0 u(nQ+1) = -sum(tn.*P(:,E(k,1)))/td; if (u(nQ+1) >= 0) & (u(nQ+1) <= 1) Q(:,nQ+1) = P(:,E(k,1)) + d*u(nQ+1); Eu(nQ+1) = k; nQ = nQ + 1; end; end; end; if nQ < 4 fprintf('only %f intersection points found\n', nQ); return; end; % coordinate transformation into tangential plane x = Q(:,1)/sqrt(sum(Q(:,1).^2)); z = tn/sqrt(sum(tn.^2)); y = [x(2)*z(3)-x(3)*z(2); ... x(3)*z(1)-x(1)*z(3); ... x(1)*z(2)-x(2)*z(1)]; y = y./sqrt(sum(y.^2)); R = [x'; y'; z']; % 07-04-03 RQ1 = R*Q(:,1:nQ); % sort points (gives convex hull) - see Sedgewick, p 404f ang = zeros([nQ 1]); for k=2:nQ dQ=RQ1(:,k)-RQ1(:,1); adQ=sum(abs(dQ)); if adQ==0 ang(k)=0; else ang(k)=dQ(2)/adQ; end; if (dQ(1) < 0) ang(k)=2-ang(k); elseif (dQ(2) < 0) ang(k)=4+ang(k); end; end; [tmp ind] = sort(ang); RQ = RQ1(:,ind); sEu= Eu(ind); su = u(ind); % compute qu, qv in tangential plane qu = repmat(NaN,[nQ 1]); qv = repmat(NaN,[nQ 1]); for k = 1:nQ g = squeeze(dS(P(1,E(sEu(k),1))+1.5,P(2,E(sEu(k),1))+1.5,P(3,E(sEu(k),1))+1.5,:) +... (dS(P(1,E(sEu(k),2))+1.5,P(2,E(sEu(k),2))+1.5,P(3,E(sEu(k),2))+1.5,:)-... dS(P(1,E(sEu(k),1))+1.5,P(2,E(sEu(k),1))+1.5,P(3,E(sEu(k),1))+1.5,:)))*su(k); q = R*[tn(2)*g(3) - tn(3)*g(2);... tn(3)*g(1) - tn(1)*g(3);... tn(1)*g(2) - tn(2)*g(1)]; qu(k) = q(1); qv(k) = q(2); end; % find zero crossings qu1 = qu([2:end 1]); zcu = find((sign(qu) + (qu==0)) == -(sign(qu1) + (qu1==0))); qv1 = qv([2:end 1]); zcv = find((sign(qv) + (qv==0)) == -(sign(qv1) + (qv1==0))); qu(qu==0)=eps; qv(qv==0)=eps; if length(zcu)~=2|length(zcv)~=2 % fprintf('not 2 zero crossings found\n'); return; end; for k = 1:2 if zcu(k) == nQ zcu1 = 1; else zcu1 = zcu(k)+1; end; % RQu(:,k) = RQ(1:2,zcu(k)) + ... % abs(qu(zcu(k)))/(abs(qu(zcu(k)))+abs(qu1(zcu(k)))) * ... % (RQ(1:2,zcu1) - RQ(1:2,zcu(k))); RQu(:,k) = RQ(1:2,zcu(k)) + ... qu(zcu(k))/(qu(zcu(k))-qu(zcu1)) * ... (RQ(1:2,zcu1) - RQ(1:2,zcu(k))); if zcv(k) == nQ zcv1 = 1; else zcv1 = zcv(k)+1; end; % RQv(:,k) = RQ(1:2,zcv(k)) + ... % abs(qv(zcv(k)))/(abs(qv(zcv(k)))+abs(qv1(zcv(k)))) * ... % (RQ(1:2,zcv1) - RQ(1:2,zcv(k))); RQv(:,k) = RQ(1:2,zcv(k)) + ... qv(zcv(k))/(qv(zcv(k))+qv(zcv1)) * ... (RQ(1:2,zcv1) - RQ(1:2,zcv(k))); end; % intersection - see Bronstein, p 219f du = RQu(:,2) - RQu(:,1); dv = RQv(:,2) - RQv(:,1); cu = RQu(1,1)*du(2) - RQu(2,1)*du(1); cv = RQv(1,1)*dv(2) - RQv(2,1)*dv(1); nom = det([-du(2) du(1); -dv(2) dv(1)]); xuv = det([du(1) cu; dv(1) cv])/nom; yuv = det([cu -du(2); cv -dv(2)])/nom; L = (inv(R)*[xuv; yuv; 0])' +.5; if any(L>1.0)|any(L<0.0) %1.05 and -.05 % fprintf('%1.2f %1.2f %1.2f intersect outside cuboid\n', L); L=[]; end; if any(~isfinite(L)) L=[]; end; function x = misc(x1) % constant coordinates for edge - not needed C = [ 1 1 0; 1 0 1; 0 1 1; 1 0 1; 0 1 1; 1 1 0; 0 1 1; 0 1 1; 1 1 0; 1 0 1; 1 0 1; 1 1 0];
github
philippboehmsturm/antx-master
csmarch.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/TensorVoting/csmarch.m
3,759
utf_8
0a717371ecf68cb749a000e5d3a34dc0
function ret=march Vt = spm_vol(spm_get(3,'evec1*s*IMAGE','Curve tangents')); Vt = {Vt(1), Vt(2), Vt(3)}; n = spm_read_vols(spm_vol(spm_get(3,'evec3*s*IMAGE','Surface normals'))); Ev = spm_read_vols(spm_vol(spm_get(3,'eval*s*IMAGE','Eigenvalues'))); St = (Ev(:,:,:,1) - Ev(:,:,:,2));%./Ev(:,:,:,1); Sn = (Ev(:,:,:,2) - Ev(:,:,:,3));%./Ev(:,:,:,1); Ss = Ev(:,:,:,3);%./Ev(:,:,:,1); clear Ev b=[0 0 0]; % border xsel=b(1)+1:(size(St,1)-b(1));%30:63; ysel=b(2)+1:(size(St,2)-b(2));%35:83; zsel=b(3)+1:(size(St,3)-b(3)); t=t(xsel,ysel,zsel,:); St=St(xsel,ysel,zsel); St(~isfinite(St)|~any(isfinite(t),4)|St<0)=0; n=n(xsel,ysel,zsel,:); Sn=Sn(xsel,ysel,zsel); Sn(~isfinite(Sn)|~any(isfinite(n),4)|Sn<0)=0; hiSt = 1.2*mean(St(St(:)>0)); loSt = .05*mean(St(St(:)>0)); f=figure(2); for k=1:size(St,3) subplot(ceil(size(St,3)/5),5,k); ... imagesc((St(:,:,k)>hiSt)+(St(:,:,k)>loSt),[0 2]); axis off; daspect([1 1 1]); end colormap gray figure(f); title(sprintf('Curve saliency - # seeds: %d; # voxels: %d',sum(St(:)>hiSt),sum(St(:)>loSt))); hiSn = 6*mean(Sn(Sn(:)>0)); loSn = 4.5*mean(Sn(Sn(:)>0)); f=figure(3); for k=1:size(Sn,3) subplot(ceil(size(Sn,3)/5),5,k); ... imagesc((Sn(:,:,k)>hiSn)+(Sn(:,:,k)>loSn),[0 2]); axis off; daspect([1 1 1]); end colormap gray figure(f); title(sprintf('Surface saliency - # seeds: %d; # voxels: %d',sum(Sn(:)>hiSn),sum(Sn(:)>loSn))); L = dti_cmarch(t,St,hiSt,loSt); FV= dti_smarch(n,Sn,hiSn,loSn); M = Vt{1}.mat; figure(4); for k=1:length(L) d = abs(L{k}(1,:)-L{k}(end,:)); [tmp ind] = max(d); switch ind(1) case 1 lc = 'red'; case 2 lc = 'green'; case 3 lc = 'blue'; end; switch length(L{k}) case {15,16,17,18,19,20} lw = 1; case {21,22,23,24,25,26,27,28,29,30} lw = 2; otherwise disp(length(L{k})); lw = 3; end; % transform into SPM world coordinates L{k}(:,1) = L{k}(:,1)+xsel(1)-1; L{k}(:,2) = L{k}(:,2)+ysel(1)-1; L{k}(:,3) = L{k}(:,3)+zsel(1)-1; xyz = M*[L{k} ones(size(L{k},1),1)]'; L{k} = xyz(1:3,:)'; li(k)=line(L{k}(:,1),L{k}(:,2),L{k}(:,3),'color',lc,'linewidth',lw); end view(3); daspect([1 1 1]); xlabel('x'); hold on; if isempty(FV) return, end; figure(5); for k=1:length(FV) % FVC = zeros(size(FV(k).V)); for l=1:3 mx = max(FV(k).V(:,l)); mn = min(FV(k).V(:,l)); d(l) = mx-mn; % if mx ~= mn % FVC(:,l) = (FV(k).V(:,l) - mn)/(mx-mn); % end; end; % p(k)=patch('Faces',FV(k).F, 'Vertices',FV(k).V, 'FaceVertexCData',FVC, ... % 'Edgecolor','none','Facecolor','interp'); [tmp ind] = max(d); switch(ind) case 1 cp = 'red'; case 2 cp = 'green'; case 3 cp = 'blue'; end; FV(k).V(:,1) = FV(k).V(:,1)+xsel(1)-1; FV(k).V(:,2) = FV(k).V(:,2)+ysel(1)-1; FV(k).V(:,3) = FV(k).V(:,3)+zsel(1)-1; xyz = M*[FV(k).V ones(size(FV(k).V,1),1)]'; FV(k).V = xyz(1:3,:)'; p(k)=patch('Faces',FV(k).F, 'Vertices',FV(k).V, 'FaceColor',cp, ... 'Edgecolor','none'); end view(3); daspect([1 1 1]); xlabel('x'); ret.L=L; ret.FV=FV; function ret = misc1(x) figure; ps=patch(isosurface(Ss,.8)); set(ps, 'FaceColor', 'red', 'EdgeColor', 'none');%,'FaceAlpha',.5); daspect([1 1 1]) view(3) camlight; lighting phong ret.li=li; ret.p=p; ret.ps=ps; function ret=misc(x) %S=zeros(12,12,12); %t=zeros(12,12,12,3); %for k=2:11 % S([k-1 k+1],k,k)=.2; % S(k,[k-1 k+1],k)=.2; % S(k,k,[k-1 k+1])=.2; % S(k,k,k)=1; % t([k-1 k+1],k,k,1:3)=.2; % t(k,[k-1 k+1],k,1:3)=.2; % t(k,k,[k-1 k+1],1:3)=.2; % t(k,k,k,:)=[1 1 1]; %end; %for k=2:11 % S(k,4:6,4:6)=S(k,4:6,4:6)+.3; % S(k,5,5) = 1.5; % t(k,4:6,4:6,1)=t(k,4:6,4:6,1)+repmat(.5,[1 3 3]); % t(k,5,5,:)=[1.7 0 0]; %end; %S=S+.01*rand(12,12,12); %t=t+.01*rand(12,12,12,3);
github
philippboehmsturm/antx-master
dti_vote_field.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/TensorVoting/dti_vote_field.m
6,717
utf_8
3016b3e2520fd95b1ba21413e39c0c8b
function [f, ss] = dti_vote_field(t, varargin); % changed tensor order to alphabetical convention % % This function is part of the diffusion toolbox for SPM5. For general help % about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id$ rev = '$Revision$'; if nargin > 1 fwhma = varargin{1}; else fwhma = .5; end; if nargin > 2 fwhmd = varargin{2}; else fwhmd = .3; end; if nargin > 3 kstep = varargin{3}; else kstep = 1/3; end; if nargin > 4 klen = varargin{4}; else klen = 3; end; if nargin > 5 stcut = varargin{5}; else stcut = .005; end; % 5 percent strength cutoff warning off; persistent dti_vf_x dti_vf_y dti_vf_z dti_vf_szf dti_vf_cent; if isempty(dti_vf_x) [dti_vf_x,dti_vf_y,dti_vf_z]=ndgrid(-klen:kstep:klen); dti_vf_szf=size(dti_vf_x); dti_vf_cent = sub2ind(dti_vf_szf,(dti_vf_szf(1)-1)/2+1,(dti_vf_szf(2)-1)/2+1,(dti_vf_szf(3)-1)/2+1); end; [v d] = eig([t(1) t(2) t(3); ... t(2) t(4) t(5); ... t(3) t(5) t(6)]); d=abs(diag(d)); % we should only have positive eigenvalues anyway [tmp ind] = sort(-d); % need to sort in descending order v=v(:,ind); d=d(ind); f = zeros([6 prod(dti_vf_szf)]); ss = zeros(1,prod(dti_vf_szf)); % rotation in template system kxyz=inv(v)*[dti_vf_x(:) dti_vf_y(:) dti_vf_z(:)]'; kxyz12 =kxyz(1,:).^2+kxyz(2,:).^2; kxyz23 =kxyz(2,:).^2+kxyz(3,:).^2; kxyz123=kxyz12+kxyz(3,:).^2; % stick field % height = distance from x==0 in y-z-plane h=sqrt(kxyz23); % r^2 = (r-h)^2 + x^2 r=kxyz123./(2*h); % rotation about y axis calpha=(r-h)./r; calpha(r==Inf)=1; salpha=sqrt(1-calpha.^2); aalpha=abs(acos(calpha)); % don't connect arc to points with rotation angles greater than pi sel=(aalpha>pi/2); % length scaling according to angle l = r.*aalpha; l(aalpha==0)=abs(kxyz(1,aalpha==0)); c=r.^(-2); c(r==Inf)=0; %lm=min(klen./abs([dti_vf_x(:) dti_vf_y(:) dti_vf_z(:)]')); lm=min(1./abs(v(:,1))); %strength = exp(-fwhma*c).*exp(-fwhmd*l.^2); strength = exp(-fwhma*c).*exp(-fwhmd*(l./lm).^2); strength(~isfinite(strength)) = 0; strength(strength<stcut) = 0; strength(sel) = 0; % rotation about x axis (for rotational symmetry) cbeta=(kxyz(1,:)./sqrt(kxyz123)); sbeta=sqrt(1-cbeta.^2); xs1=kxyz(1,:).*calpha; ys1=h.*salpha.*cbeta; zs1=h.*salpha.*sbeta; lenscale=strength./sqrt(xs1.^2+ys1.^2+zs1.^2); xs=lenscale.*abs(xs1).*sign(kxyz(1,:)); ys=lenscale.*abs(ys1).*sign(kxyz(2,:)); zs=lenscale.*abs(zs1).*sign(kxyz(3,:)); % rotate back, align to 1st eigenvector xstmp=v*[xs(:) ys(:) zs(:)]'; xs=xstmp(1,:); ys=xstmp(2,:); zs=xstmp(3,:); xs(dti_vf_cent)=v(1,1); ys(dti_vf_cent)=v(2,1); zs(dti_vf_cent)=v(3,1); strength(dti_vf_cent)=1; xs(~isfinite(xs))=0; ys(~isfinite(ys))=0; zs(~isfinite(zs))=0; f(1,:) = f(1,:) + (d(1)-d(2))*xs.*xs; f(2,:) = f(2,:) + (d(1)-d(2))*xs.*ys; f(3,:) = f(3,:) + (d(1)-d(2))*xs.*zs; f(4,:) = f(4,:) + (d(1)-d(2))*ys.*ys; f(5,:) = f(5,:) + (d(1)-d(2))*ys.*zs; f(6,:) = f(6,:) + (d(1)-d(2))*zs.*zs; ss = ss+strength; % plate field % height is just abs(z) % r^2 = (r-h)^2 + (x^2 + y^2) r=(kxyz123)./(2*abs(kxyz(3,:))); % rotation out of (x,y)-plane calpha=(r-abs(kxyz(3,:)))./r; calpha(r==Inf)=1; salpha=sqrt(1-calpha.^2); aalpha=abs(acos(calpha)); aalpha(kxyz(3,:)==0)=0; % don't connect arc to points with rotation angles greater than pi sel=(aalpha>pi/2); % length scaling according to angle l = r.*aalpha; l(aalpha==0)=sqrt(kxyz(1,aalpha==0).^2+kxyz(2,aalpha==0).^2); c=r.^(-2); c(r==Inf)=0; lm=min(1./abs(v(:,3))); %strength = exp(-fwhma*c).*exp(-fwhmd*l.^2); strength = exp(-fwhma*c).*exp(-fwhmd*(l./lm).^2); strength(~isfinite(strength)) = 0; strength(strength<stcut) = 0; strength(sel) = 0; % 1st eigenvector xy=sqrt(kxyz12); xr1=kxyz(1,:)./xy.*calpha; yr1=kxyz(2,:)./xy.*calpha; zr1=salpha; lenscale=strength./sqrt(xr1.^2+yr1.^2+zr1.^2); xr=lenscale.*abs(xr1).*sign(kxyz(1,:)); yr=lenscale.*abs(yr1).*sign(kxyz(2,:)); zr=lenscale.*abs(zr1).*sign(kxyz(3,:)); % 2nd eigenvector: (-y,x,0) lenscale=strength./sqrt(kxyz12); xt=lenscale.*(-kxyz(2,:)); yt=lenscale.*kxyz(1,:); zt=zeros(size(kxyz(3,:))); % rotate back, align to 3rd eigenvector xrtmp=v*[xr(:) yr(:) zr(:)]'; xr=xrtmp(1,:); yr=xrtmp(2,:); zr=xrtmp(3,:); xr(dti_vf_cent)=v(1,1); yr(dti_vf_cent)=v(2,1); zr(dti_vf_cent)=v(3,1); xr(~isfinite(xr))=0; yr(~isfinite(yr))=0; zr(~isfinite(zr))=0; % rotate back, align to 3rd eigenvector xttmp=v*[xt(:) yt(:) zt(:)]'; xt=xttmp(1,:); yt=xttmp(2,:); zt=xttmp(3,:); xt(dti_vf_cent)=v(1,2); yt(dti_vf_cent)=v(2,2); zt(dti_vf_cent)=v(3,2); xt(~isfinite(xt))=0; yt(~isfinite(yt))=0; zt(~isfinite(zt))=0; % add to voting field f(1,:) = f(1,:) + (d(2)-d(3))*(xr.*xr+xt.*xt); f(2,:) = f(2,:) + (d(2)-d(3))*(xr.*yr+xt.*yt); f(3,:) = f(3,:) + (d(2)-d(3))*(xr.*zr+xt.*zt); f(4,:) = f(4,:) + (d(2)-d(3))*(yr.*yr+yt.*yt); f(5,:) = f(5,:) + (d(2)-d(3))*(yr.*zr+yt.*zt); f(6,:) = f(6,:) + (d(2)-d(3))*(zr.*zr+zt.*zt); ss = ss+strength; % ball field lm=1; %strength=exp(-fwhmd*kxyz123); strength=exp(-fwhmd*kxyz123./lm.^2); strength(strength<stcut) = 0; zrs=zeros(size(strength(:))); x1tmp=v*[strength(:) zrs(:) zrs(:)]'; x1=x1tmp(1,:); y1=x1tmp(2,:); z1=x1tmp(3,:); x2tmp=v*[zrs(:) strength(:) zrs(:)]'; x2=x2tmp(1,:); y2=x2tmp(2,:); z2=x2tmp(3,:); x3tmp=v*[zrs(:) zrs(:) strength(:)]'; x3=x3tmp(1,:); y3=x3tmp(2,:); z3=x3tmp(3,:); % add to voting field f(1,:) = f(1,:) + d(3)*(x1.*x1+x2.*x2+x3.*x3); f(2,:) = f(2,:) + d(3)*(x1.*y1+x2.*y2+x3.*y3); f(3,:) = f(3,:) + d(3)*(x1.*z1+x2.*z2+x3.*z3); f(4,:) = f(4,:) + d(3)*(y1.*y1+y2.*y2+y3.*y3); f(5,:) = f(5,:) + d(3)*(y1.*z1+y2.*z2+y3.*z3); f(6,:) = f(6,:) + d(3)*(z1.*z1+z2.*z2+z3.*z3); ss = ss+strength; ss = reshape(ss/3,dti_vf_szf); f = reshape(f,[6 dti_vf_szf]); function f=dti_vote_field_old(t) fwhmk = .7; % kernel fwhm fwhma = .2; % aperture fwhm [xk,yk,zk]=meshgrid(-1:.2:1); % symmetric distance kernel dkrnl = xk.^2+yk.^2+zk.^2; % symmetric kernel with gaussian shape sqdkrnl = sqrt(dkrnl); sqdkrnl(sqdkrnl==0) = eps; nkrnl(:,:,:,1)=xk./sqdkrnl; nkrnl(:,:,:,2)=yk./sqdkrnl; nkrnl(:,:,:,3)=zk./sqdkrnl; krnl = nkrnl.*repmat(exp(-(dkrnl)./fwhmk),[1 1 1 3]); sk=size(krnl); % get eigenvectors, eigenvalues f=zeros([sk(1:3) 3 3]); if isfinite(t) [v,d]=eig(t); for k=1:3 % angle between eigenvector and kernel, exponential decay krnl(6,6,6,:)=v(:,k); nkrnl(6,6,6,:)=v(:,k); akrnl = exp(-(1-abs(sum(nkrnl.*repmat(shiftdim(v(:,k)',-2),... [sk(1:3) 1]),4)))./fwhma); tmp=repmat(krnl.*repmat(akrnl,[1 1 1 3]),[1 1 1 1 3]); % 3x3 columns of vectors f = f + d(k).*tmp.*permute(tmp,[1 2 3 5 4]); % 3x3c.*3x3r => 3x3 tensor end; end;
github
philippboehmsturm/antx-master
dti_compare.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Comparisons/dti_compare.m
5,297
utf_8
f8d35047719abee9ce3579295637e742
function dti_compare(job) % Compare tensors % % Determine affine transformation (without shearing) that would map % tensors voxel-by-voxel to a volume of reference tensors. % % This function is part of the diffusion toolbox for SPM5. For general % help about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id$ rev = '$Revision$'; funcname = 'Compare tensors'; % function preliminaries Finter=spm_figure('GetWin','Interactive'); Finter=spm('FigName',funcname,Finter); SPMid = spm('FnBanner',mfilename,rev); % function code starts here IDTI1=spm_vol(job.refdtimg); IDTI2=spm_vol(job.dtimg); IMsk=spm_vol(job.maskimg); [p2 n2 e]=spm_fileparts(IDTI2(1).fname); for k=1:6 IComp(k)=IDTI2(1); IComp(k).fname=fullfile(p1,[job.prefix sprintf('%02d_',k+3) n2 e]); IComp(k) = spm_create_vol(IComp(k)); end; %-Start progress plot %----------------------------------------------------------------------- spm_progress_bar('Init',IDTI1(1).dim(3),'','planes completed'); %-Loop over planes computing result Y %----------------------------------------------------------------------- for p = 1:IDTI1(1).dim(3), comp=zeros(6,DTIdim(1),DTIdim(2)); B = inv(spm_matrix([0 0 -p 0 0 0 1 1 1])); X1=zeros(3,3,DTIdim(1),DTIdim(2)); msk = spm_slice_vol(IMsk,B,DTIdim,0); if any(msk(:)) X1(1,1,:,:) = spm_slice_vol(IDTI1(1),B,DTIdim,0); % hold 0 X1(1,2,:,:) = spm_slice_vol(IDTI1(2),B,DTIdim,0); % hold 0 X1(1,3,:,:) = spm_slice_vol(IDTI1(3),B,DTIdim,0); % hold 0 X1(2,1,:,:) = X1(1,2,:,:); X1(2,2,:,:) = spm_slice_vol(IDTI1(4),B,DTIdim,0); % hold 0 X1(2,3,:,:) = spm_slice_vol(IDTI1(5),B,DTIdim,0); % hold 0 X1(3,1,:,:) = X1(1,3,:,:); X1(3,2,:,:) = X1(2,3,:,:); X1(3,3,:,:) = spm_slice_vol(IDTI1(6),B,DTIdim,0); % hold 0 X2=zeros(3,3,DTIdim(1),DTIdim(2)); X2(1,1,:,:) = spm_slice_vol(IDTI2(1),B,DTIdim,0); % hold 0 X2(1,2,:,:) = spm_slice_vol(IDTI2(2),B,DTIdim,0); % hold 0 X2(1,3,:,:) = spm_slice_vol(IDTI2(3),B,DTIdim,0); % hold 0 X2(2,1,:,:) = X2(1,2,:,:); X2(2,2,:,:) = spm_slice_vol(IDTI2(4),B,DTIdim,0); % hold 0 X2(2,3,:,:) = spm_slice_vol(IDTI2(5),B,DTIdim,0); % hold 0 X2(3,1,:,:) = X2(1,3,:,:); X2(3,2,:,:) = X2(2,3,:,:); X2(3,3,:,:) = spm_slice_vol(IDTI2(6),B,DTIdim,0); % hold 0 if any(X1(:)) || any(X2(:)) for k=1:DTIdim(1) for l=1:DTIdim(2) if(msk(k,l)) tmp=X1(:,:,k,l)/X2(:,:,k,l); if ~isnan(tmp) && any(tmp) try comp(:,k,l) = vg_imatrix(tmp); catch fprintf('Warning\n'); end; end; end; end; end; end; end; for k=1:6 spm_write_plane(IComp(k),squeeze(comp(k,:,:)),p); end; spm_progress_bar('Set',p); end; spm_progress_bar('Clear') function P = vg_imatrix(M) % returns the parameters for creating an affine transformation % FORMAT P = spm_imatrix(M) % M - Affine transformation matrix % P - Parameters (see spm_matrix for definitions) %___________________________________________________________________________ % @(#)spm_imatrix.m 2.1 John Ashburner & Stefan Kiebel 98/12/18 % Translations and zooms %----------------------------------------------------------------------- R = M(1:3,1:3); C = chol(R'*R); P = [0 0 0 diag(C)']; if det(R)<0, P(4)=-P(4);end % Fix for -ve determinants % Shears %----------------------------------------------------------------------- %C = diag(diag(C))\C; %P(10:12) = C([4 7 8]); %R0 = spm_matrix([0 0 0 0 0 0 P(7:12)]); %R0 = R0(1:3,1:3); %R1 = R/R0; % vg: we assume to have no shears R1=R; % This just leaves rotations in matrix R1 %----------------------------------------------------------------------- %[ c5*c6, c5*s6, s5] %[-s4*s5*c6-c4*s6, -s4*s5*s6+c4*c6, s4*c5] %[-c4*s5*c6+s4*s6, -c4*s5*s6-s4*c6, c4*c5] P(2) = asin(rang(R1(1,3))); if (abs(P(2))-pi/2).^2 < 1e-9, P(1) = 0; P(3) = atan2(-rang(R1(2,1)), rang(-R1(3,1)/R1(1,3))); else c = cos(P(2)); P(1) = atan2(rang(R1(2,3)/c), rang(R1(3,3)/c)); P(3) = atan2(rang(R1(1,2)/c), rang(R1(1,1)/c)); end; return; % There may be slight rounding errors making b>1 or b<-1. function a = rang(b) a = min(max(b, -1), 1); return;
github
philippboehmsturm/antx-master
dti_dw_cluster_std_differences.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Comparisons/dti_dw_cluster_std_differences.m
9,851
utf_8
8b5309280d8bdb0d4bf71b0542fb38e5
function varargout = dti_dw_cluster_std_differences(cmd, varargin) % Template function to implement callbacks for an cfg_exbranch. The calling % syntax is % varargout = dti_dw_cluster_std_differences(cmd, varargin) % where cmd is one of % 'run' - out = dti_dw_cluster_std_differences('run', job) % Run a job, and return its output argument % 'vout' - dep = dti_dw_cluster_std_differences('vout', job) % Examine a job structure with all leafs present and return an % array of cfg_dep objects. % 'check' - str = dti_dw_cluster_std_differences('check', subcmd, subjob) % Examine a part of a fully filled job structure. Return an empty % string if everything is ok, or a string describing the check % error. subcmd should be a string that identifies the part of % the configuration to be checked. % 'defaults' - defval = dti_dw_cluster_std_differences('defaults', key) % Retrieve defaults value. key must be a sequence of dot % delimited field names into the internal def struct which is % kept in function local_def. An error is returned if no % matching field is found. % dti_dw_cluster_std_differences('defaults', key, newval) % Set the specified field in the internal def struct to a new % value. % Application specific code needs to be inserted at the following places: % 'run' - main switch statement: code to compute the results, based on % a filled job % 'vout' - main switch statement: code to compute cfg_dep array, based % on a job structure that has all leafs, but not necessarily % any values filled in % 'check' - create and populate switch subcmd switchyard % 'defaults' - modify initialisation of defaults in subfunction local_defs % Callbacks can be constructed using anonymous function handles like this: % 'run' - @(job)dti_dw_cluster_std_differences('run', job) % 'vout' - @(job)dti_dw_cluster_std_differences('vout', job) % 'check' - @(job)dti_dw_cluster_std_differences('check', 'subcmd', job) % 'defaults' - @(val)dti_dw_cluster_std_differences('defaults', 'defstr', val{:}) % Note the list expansion val{:} - this is used to emulate a % varargin call in this function handle. % % This code is part of a batch job configuration system for MATLAB. See % help matlabbatch % for a general overview. %_______________________________________________________________________ % Copyright (C) 2007 Freiburg Brain Imaging % Volkmar Glauche % $Id: dti_dw_cluster_std_differences.m 715 2010-09-01 15:14:38Z glauche $ rev = '$Rev: 715 $'; %#ok if ischar(cmd) switch lower(cmd) case 'run' job = local_getjob(varargin{1}); % do computation, return results in variable out out.thresh=repmat(struct([]),size(job.thresh)); for cth = 1:numel(job.thresh) out.thresh(cth).imsum = cell(size(job.osrcimgs)); out.thresh(cth).nc = zeros(size(job.osrcimgs)); out.thresh(cth).cs = cell(size(job.osrcimgs)); out.thresh(cth).limgs = cell(size(job.osrcimgs)); out.thresh(cth).mcs = zeros(size(job.osrcimgs)); end domask = ~isempty(job.maskimg) && ~isempty(job.maskimg{1}); if domask VM = spm_vol(job.maskimg{1}); end gmean = numel(job.msrcimgs) == 1; if gmean Vm = spm_vol(job.msrcimgs{1}); Vs = spm_vol(job.ssrcimgs{1}); end spm_progress_bar('init', numel(job.osrcimgs)); for ci = 1:numel(job.osrcimgs) Vi = spm_vol(job.osrcimgs{ci}); % create temporary standard difference file, do clustering % on this file V = rmfield(Vi,'private'); [p n e v] = spm_fileparts(V.fname); V.fname = fullfile(p, ['SD' n '_ctmp' e]); if ~gmean Vm = spm_vol(job.msrcimgs{ci}); Vs = spm_vol(job.ssrcimgs{ci}); end if domask V = spm_imcalc([Vm; Vi; Vs; VM], V, '(abs(i1-i2)./sqrt(i3+(i3==0))).*i4'); else V = spm_imcalc([Vm; Vi; Vs], V, 'abs(i1-i2)./sqrt(i3+(i3==0))'); end odat = spm_read_vols(V); dat=reshape(odat,[prod(V.dim(1:2)), V.dim(3)]); for cth = 1:numel(job.thresh) out.thresh(cth).imsum{ci} = sum(dat > job.thresh(cth).th); [ldat, out.thresh(cth).nc(ci)] = spm_bwlabel(double(odat > job.thresh(cth).th),6); out.thresh(cth).cs{ci} = zeros(out.thresh(cth).nc(ci),1); for l = 1:out.thresh(cth).nc(ci) out.thresh(cth).cs{ci}(l) = sum(ldat(:)==l); end end % remove temporary file rmjob{1}.cfg_basicio.file_move.files = {V.fname}; rmjob{1}.cfg_basicio.file_move.action.delete = false; spm_jobman('run',rmjob); spm_progress_bar('set', ci); end spm_progress_bar('clear'); sel = false(numel(job.thresh),numel(job.osrcimgs)); for cth = 1:numel(job.thresh) [out.thresh(cth).cs{cellfun(@isempty,out.thresh(cth).cs)}]=deal(0); out.thresh(cth).mcs = cellfun(@max,out.thresh(cth).cs); sel(cth,:) = out.thresh(cth).mcs < job.thresh(cth).csize; out.thresh(cth).ind = find(sel(cth,:)); end out.ind = find(all(sel)); out.goodimgs = job.osrcimgs(all(sel)); out.badimgs = job.osrcimgs(~all(sel)); if nargout > 0 varargout{1} = out; end case 'vout' job = local_getjob(varargin{1}); % initialise empty cfg_dep array dep(1) = cfg_dep; dep(1).sname = '''Good'' images'; dep(1).src_output = substruct('.','goodimgs'); dep(1).tgt_spec = cfg_findspec({{'filter','image'}}); dep(2) = cfg_dep; dep(2).sname = '''Bad'' images'; dep(2).src_output = substruct('.','badimgs'); dep(2).tgt_spec = cfg_findspec({{'filter','image'}}); dep(3) = cfg_dep; dep(3).sname = 'Inclusion index (all thresholds)'; dep(3).src_output = substruct('.','ind'); dep(3).tgt_spec = cfg_findspec({{'strtype','n'}}); for cth = 1:numel(job.thresh) dep(cth +3) = cfg_dep; dep(cth +3).sname = sprintf('Inclusion index %d',cth); dep(cth +3).src_output = substruct('.','thresh','()',{cth},'.','ind'); dep(cth +3).tgt_spec = cfg_findspec({{'strtype','n'}}); dep(cth+1*numel(job.thresh)+3) = cfg_dep; dep(cth+1*numel(job.thresh)+3).sname = sprintf('Threshold %d results', cth); dep(cth+1*numel(job.thresh)+3).src_output = substruct('.','thresh','()',{cth}); dep(cth+1*numel(job.thresh)+3).tgt_spec = cfg_findspec({{'strtype','e'}}); end % determine outputs, return cfg_dep array in variable dep varargout{1} = dep; case 'check' if ischar(varargin{1}) subcmd = lower(varargin{1}); subjob = varargin{2}; str = ''; switch subcmd % implement checks, return status string in variable str case 'srcimgs' nummsrc = numel(subjob.msrcimgs); if nummsrc ~= numel(subjob.ssrcimgs) str = '# mean images must match # std images.'; elseif nummsrc > 1 && nummsrc ~= numel(subjob.osrcimgs) str = '# mean/std images must either be 1 or match # original images.'; end otherwise cfg_message('unknown:check', ... 'Unknown check subcmd ''%s''.', subcmd); end varargout{1} = str; else cfg_message('ischar:check', 'Subcmd must be a string.'); end case 'defaults' if nargin == 2 varargout{1} = local_defs(varargin{1}); else local_defs(varargin{1:2}); end otherwise cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd); end else cfg_message('ischar:cmd', 'Cmd must be a string.'); end function varargout = local_defs(defstr, defval) persistent defs; if isempty(defs) % initialise defaults end if ischar(defstr) % construct subscript reference struct from dot delimited tag string tags = textscan(defstr,'%s', 'delimiter','.'); subs = struct('type','.','subs',tags{1}'); try cdefval = subsref(local_def, subs); catch cdefval = []; cfg_message('defaults:noval', ... 'No matching defaults value ''%s'' found.', defstr); end if nargin == 1 varargout{1} = cdefval; else defs = subsasgn(defs, subs, defval); end else cfg_message('ischar:defstr', 'Defaults key must be a string.'); end function job = local_getjob(job) if ~isstruct(job) cfg_message('isstruct:job', 'Job must be a struct.'); end
github
philippboehmsturm/antx-master
dti_classify.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Comparisons/dti_classify.m
3,968
utf_8
bc5148c48e1e41da6651a82f4df1e273
function C=dti_classify(job) % Classify DTI data based on anisotropy and direction of first eigenvector % % This function is part of the diffusion toolbox for SPM5. For general % help about this toolbox, bug reports, licensing etc. type % spm_help vgtbx_config_Diffusion % in the matlab command window after the toolbox has been launched. %_______________________________________________________________________ % % @(#) $Id$ rev='$Revision$'; EvecHandle=spm_vol(job.e1img); DTIData=spm_read_vols(EvecHandle); FAHandle=spm_vol(job.faimg); FAData=spm_read_vols(FAHandle); MaskHandle=spm_vol(job.maskimg); U=logical(spm_read_vols(MaskHandle)); dim=size(U); FAsel = (FAData>job.fathresh); Uan = U.*FAsel; Uis = U.*(~FAsel); % assume DTIdata to be stored as x*y*z*datadim array cno = 1; Can=classify(Uan, DTIData, @collinear, @neighbour6, 1); fprintf('\nIsotrop\n'); Cis=classify(Uis, DTIData, @isotrop, @neighbour6, max(Can(:))+1); C=Uan.*Can + Uis.*Cis; CHandle=EvecHandle(1); [p n e] = spm_fileparts(CHandle.fname); CHandle.fname = fullfile(p,[job.prefix n e]); spm_write_vol(CHandle,C); function C = classify(U, DTIData, classfunc, nbfunc, cno) dim = size(DTIData); C = zeros(dim(1:3)); while (sum(U(:))) N=zeros(dim(1:3)); Nlist=cell(dim(1:3)); [px py pz] = ind2sub(size(U),find(U)); px=px(1); py=py(1); pz=pz(1); C(px,py,pz)=cno; U(px,py,pz)=0; [N Nlist] = feval(nbfunc,U,N,Nlist,[px,py,pz]); fprintf('\r%d - ( %2d, %2d, %2d)',cno, px, py, pz); while (sum(N(:))) [qx qy qz] = ind2sub(size(N),find(N)); q=[qx(1) qy(1) qz(1)]; N(q(1),q(2),q(3))=0; while (~isempty(Nlist{q(1),q(2),q(3)})) p1 = Nlist{q(1),q(2),q(3)}(1,:); if feval(classfunc, DTIData, p1, q) C(q(1),q(2),q(3)) = cno; U(q(1),q(2),q(3)) = 0; Nlist{q(1),q(2),q(3)} = []; [N Nlist] = feval(nbfunc, U,N,Nlist,q); fprintf(' %.0d',fix(sum(N(:)))); figure(2);subplot(10,13,q(3));image(C(:,:,q(3))); axis off; else s = size(Nlist{q(1),q(2),q(3)}); Nlist{q(1),q(2),q(3)} = Nlist{q(1),q(2),q(3)}(2:s(1),:); if isempty(Nlist{q(1),q(2),q(3)}) N(q(1),q(2),q(3))=0; end; end; end; end; if sum(C(:)==cno) > 2 cno = cno+1; fprintf('\n'); else C(C==cno) = 0; end; end; function flag=collinear(DTIData, p1, p2) dim=size(DTIData); % dp=p2-p1; % p1+dp = p2 % p = p1 -dp; % if (0<p) & (p < dim(1:3)) % c(1) = sum(DTIData(p(1), p(2), p(3),:) .* DTIData(p2(1), p2(2), p2(3),:)); % "2"-Nachbar von p2 % w(1) = 0; %else % c(1)=NaN; % w(1)=0; %end; %p = p2 + dp; %if (0<p) & (p < dim(1:3)) % c(2) = sum(DTIData(p(1), p(2), p(3),:) .* DTIData(p1(1), p1(2), p1(3),:)); % "2"-Nachbar von p1 % w(2) = 0; %else % c(2)=NaN; % w(2)=0; %end; c(3) = sum(DTIData(p2(1), p2(2), p2(3),:) .* DTIData(p1(1), p1(2), p1(3),:)); w(3) = 3; flag = (abs(c(3) > .99));% | (((abs(acos(c(3))-acos(c(1))) < .05) ... % | (abs(acos(c(3))-acos(c(2))) <.05)) & (abs(c(3)) >.6)) ; %if flag % [squeeze(DTIData(p2(1), p2(2), p2(3),:) .* DTIData(p1(1), p1(2), p1(3),:))]' % [squeeze(DTIData(p2(1), p2(2), p2(3),:))]' % [squeeze(DTIData(p1(1), p1(2), p1(3),:))]' %end; function flag=isotrop(DTIData, p1, p2) flag = 1; function [N, Nlist]=neighbour27(U,N,Nlist,p) for dx = -1:1 for dy = -1:1 for dz = -1:1 p1=p + [dx dy dz]; if (p1>0) && (p1 <= size(N)) N(p1(1),p1(2),p1(3))=U(p1(1),p1(2),p1(3)); if U(p1(1),p1(2),p1(3)) Nlist{p1(1),p1(2),p1(3)} = [Nlist{p1(1),p1(2),p1(3)}; p]; end; end; end; end; end; function [N, Nlist]=neighbour6(U,N,Nlist,p) for k=1:3 d=zeros(1,3); d(k)=1; p1=p + d; if (p1>0) && (p1 <= size(N)) N(p1(1),p1(2),p1(3))=U(p1(1),p1(2),p1(3)); if U(p1(1),p1(2),p1(3)) Nlist{p1(1),p1(2),p1(3)} = [Nlist{p1(1),p1(2),p1(3)}; p]; end; end; p1=p - d; if (p1>0) && (p1 <= size(N)) N(p1(1),p1(2),p1(3))=U(p1(1),p1(2),p1(3)); if U(p1(1),p1(2),p1(3)) Nlist{p1(1),p1(2),p1(3)} = [Nlist{p1(1),p1(2),p1(3)}; p]; end; end; end;
github
philippboehmsturm/antx-master
dti_dw_wmean_variance.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/Diffusion/Comparisons/dti_dw_wmean_variance.m
8,189
utf_8
fc27520ac5df97767041faecfaee2764
function varargout = dti_dw_wmean_variance(cmd, varargin) % Generate a series of weighted mean and variance images from a DWI series % varargout = dti_dw_wmean_variance(cmd, varargin) % where cmd is one of % 'run' - out = dti_dw_wmean_variance('run', job) % Run a job, and return its output argument % 'vout' - dep = dti_dw_wmean_variance('vout', job) % Examine a job structure with all leafs present and return an % array of cfg_dep objects. % 'check' - str = dti_dw_wmean_variance('check', subcmd, subjob) % Examine a part of a fully filled job structure. Return an empty % string if everything is ok, or a string describing the check % error. subcmd should be a string that identifies the part of % the configuration to be checked. % 'defaults' - defval = dti_dw_wmean_variance('defaults', key) % Retrieve defaults value. key must be a sequence of dot % delimited field names into the internal def struct which is % kept in function local_def. An error is returned if no % matching field is found. % dti_dw_wmean_variance('defaults', key, newval) % Set the specified field in the internal def struct to a new % value. % Application specific code needs to be inserted at the following places: % 'run' - main switch statement: code to compute the results, based on % a filled job % 'vout' - main switch statement: code to compute cfg_dep array, based % on a job structure that has all leafs, but not necessarily % any values filled in % 'check' - create and populate switch subcmd switchyard % 'defaults' - modify initialisation of defaults in subfunction local_defs % Callbacks can be constructed using anonymous function handles like this: % 'run' - @(job)dti_dw_wmean_variance('run', job) % 'vout' - @(job)dti_dw_wmean_variance('vout', job) % 'check' - @(job)dti_dw_wmean_variance('check', 'subcmd', job) % 'defaults' - @(val)dti_dw_wmean_variance('defaults', 'defstr', val{:}) % Note the list expansion val{:} - this is used to emulate a % varargin call in this function handle. % % This code is part of a batch job configuration system for MATLAB. See % help matlabbatch % for a general overview. %_______________________________________________________________________ % Copyright (C) 2007 Freiburg Brain Imaging % Volkmar Glauche % $Id: dti_dw_wmean_variance.m 715 2010-09-01 15:14:38Z glauche $ rev = '$Rev: 715 $'; %#ok if ischar(cmd) switch lower(cmd) case 'run' job = local_getjob(varargin{1}); % do computation, return results in variable out Vi = spm_vol(char(job.srcimgs)); Vm = rmfield(Vi,'private'); [Vm.private] = deal([]); [Vm.descrip] = deal('weighted mean'); [Vm.pinfo] = deal([1;0;0]); [Vm.dt] = deal([spm_type('float32') spm_platform('bigend')]); Vs = rmfield(Vi,'private'); [Vs.private] = deal([]); [Vs.descrip] = deal('unbiased sample variance'); [Vs.pinfo] = deal([1;0;0]); [Vs.dt] = deal([spm_type('float32') spm_platform('bigend')]); if false %isfield(bch.errorvar,'errauto') % ltol, dtol and sep can be set using the GUI and need to % be present in extbch extbch = bch.errorvar.errauto; else % only need to sort for b values extbch.ltol = 1; extbch.dtol = 0; extbch.sep = 0; end; extbch.srcimgs = job.srcimgs; extbch.ref.refscanner = 1; extbch.saveinf = 0; extres = dti_extract_dirs(extbch); for cb = 1:numel(extres.ub) bsel = find(extres.ubj == cb); % angle between between diffusion directions - maximum % weight for angle zero, exp decay to angle pi/2 cg = exp(-acos(abs(extres.allg(bsel,:)*extres.allg(bsel,:)'))); cg = cg - min(cg(:)); % or: cos(angle between between diffusion directions) % cg = abs(extres.allg(bsel,:)*extres.allg(bsel,:)'); nsrc = numel(bsel); for k = 1:nsrc [p n e] = spm_fileparts(Vi(bsel(k)).fname); % weights according to angle between diffusion % directions if all(cg(k,:) == 0) % no weighting in case of all-zero weights (b0 % images) w = ones(size(cg(k,:))); else w = cg(k,:); end w = w./sum(w); % compute weighted mean Vm(bsel(k)).fname = fullfile(p, ['m' job.infix n e]); Vm(bsel(k)) = spm_imcalc(Vi(bsel),Vm(bsel(k)),'w*X',{1},w); % compute unbiased weighted sample variance - see % http://en.wikipedia.org/wiki/Weighted_mean#Weighted_sample_variance Vs(bsel(k)).fname = fullfile(p, ['s' job.infix n e]); u = 1/(1-sum(w.^2)); % unbiased weighting Vs(bsel(k)) = spm_imcalc([Vm(bsel(k)); Vi(bsel)], ... Vs(bsel(k)),'u*w*(X(2:end,:)-repmat(X(1,:),nsrc,1)).^2',{1},u,w,nsrc); end end out.wmean = {Vm.fname}; out.wvar = {Vs.fname}; if nargout > 0 varargout{1} = out; end case 'vout' job = local_getjob(varargin{1}); % initialise empty cfg_dep array dep(1) = cfg_dep; dep(1).sname = 'Weighted mean images'; dep(1).src_output = substruct('.','wmean'); dep(1).tgt_spec = cfg_findspec({{'filter','image'}}); dep(2) = cfg_dep; dep(2).sname = 'Weighted variance images'; dep(2).src_output = substruct('.','wvar'); dep(2).tgt_spec = cfg_findspec({{'filter','image'}}); % determine outputs, return cfg_dep array in variable dep varargout{1} = dep; case 'check' if ischar(varargin{1}) subcmd = lower(varargin{1}); subjob = varargin{2}; str = ''; switch subcmd % implement checks, return status string in variable str otherwise cfg_message('unknown:check', ... 'Unknown check subcmd ''%s''.', subcmd); end varargout{1} = str; else cfg_message('ischar:check', 'Subcmd must be a string.'); end case 'defaults' if nargin == 2 varargout{1} = local_defs(varargin{1}); else local_defs(varargin{1:2}); end otherwise cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd); end else cfg_message('ischar:cmd', 'Cmd must be a string.'); end function varargout = local_defs(defstr, defval) persistent defs; if isempty(defs) % initialise defaults end if ischar(defstr) % construct subscript reference struct from dot delimited tag string tags = textscan(defstr,'%s', 'delimiter','.'); subs = struct('type','.','subs',tags{1}'); try cdefval = subsref(local_def, subs); catch cdefval = []; cfg_message('defaults:noval', ... 'No matching defaults value ''%s'' found.', defstr); end if nargin == 1 varargout{1} = cdefval; else defs = subsasgn(defs, subs, defval); end else cfg_message('ischar:defstr', 'Defaults key must be a string.'); end function job = local_getjob(job) if ~isstruct(job) cfg_message('isstruct:job', 'Job must be a struct.'); end
github
philippboehmsturm/antx-master
spm_eeg_inv_ecd_DrawDip.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/dcm_meeg/spm_eeg_inv_ecd_DrawDip.m
19,836
utf_8
c1fb718e9c4d595b873949ad1274953d
function varargout = spm_eeg_inv_ecd_DrawDip(action,varargin) % Display the dipoles as obtained from the optim routine % % Use it with arguments or not: % - spm_eeg_inv_ecd_DrawDip('Init') % The routine asks for the dipoles file and image to display % - spm_eeg_inv_ecd_DrawDip('Init',sdip) % The routine will use the avg152T1 canonical image % - spm_eeg_inv_ecd_DrawDip('Init',sdip,P) % The routines dispays the dipoles on image P. % % If multiple seeds have been used, you can select the seeds to display % by pressing their index. % Given that the sources could have different locations, the slices % displayed will be the 3D view at the *average* or *mean* locations of % selected sources. % If more than 1 dipole was fitted at a time, then selection of source 1 % to N is possible through the pull-down selector. % % The location of the source/cut is displayed in mm and voxel, as well as % the underlying image intensity at that location. % The cross hair position can be hidden by clicking on its button. % % Nota_1: If the cross hair is manually moved by clicking in the image or % changing its coordinates, the dipole displayed will NOT be at % the right displayed location. That's something that needs to be improved... % % Nota_2: Some seeds may have not converged within the limits fixed, % these dipoles are not displayed... % % Fields needed in sdip structure to plot on an image: % + n_seeds: nr of seeds set used, i.e. nr of solutions calculated % + n_dip: nr of fitted dipoles on the EEG time series % + loc: location of fitted dipoles, cell{1,n_seeds}(3 x n_dip) % remember that loc is fixed over the time window. % + j: sources amplitude over the time window, % cell{1,n_seeds}(3*n_dip x Ntimebins) % + Mtb: index of maximum power in EEG time series used %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Christophe Phillips, % $Id: spm_eeg_inv_ecd_DrawDip.m 3692 2010-01-21 21:43:31Z guillaume $ global st Fig = spm_figure('FindWin'); colors = strvcat('y','b','g','r','c','m'); % 6 possible colors marker = strvcat('o','x','+','*','s','d','v','p','h'); % 9 possible markers Ncolors = length(colors); Nmarker = length(marker); if nargin == 0, action = 'Init'; end; switch lower(action), %________________________________________________________________________ case 'init' %------------------------------------------------------------------------ % FORMAT spm_eeg_inv_ecd_DrawDip('Init',sdip,P) % Initialise the variables with GUI % e.g. spm_eeg_inv_ecd_DrawDip('Init') %------------------------------------------------------------------------ spm('Clear') if nargin<2 load(spm_select(1,'^.*S.*dip.*\.mat$','Select dipole file')); if ~exist('sdip') & exist('result') sdip = result; end else sdip = varargin{1}; end % if the exit flag is not in the structure, assume everything went ok. if ~isfield(sdip,'exitflag') sdip.exitflag = ones(1,sdip.n_seeds); end Pcanonical = fullfile(spm('dir'),'canonical','avg152T1.nii'); if nargin<3 if ~isstruct(st) % P = spm_select(1,'image','Image to display dipoles on'); P = Pcanonical; elseif isempty(st.vols{1}) % P = spm_select(1,'image','Image to display dipoles on'); P = Pcanonical; end else P = varargin{2}; end if ischar(P), P = spm_vol(P); end; spm_orthviews('Reset'); spm_orthviews('Image', P, [0.0 0.45 1 0.55]); spm_orthviews('MaxBB'); st.callback = 'spm_image(''shopos'');'; WS = spm('WinScale'); % Build GUI %============================= % Location: %----------- uicontrol(Fig,'Style','Frame','Position',[60 25 200 325].*WS,'DeleteFcn','spm_image(''reset'');'); uicontrol(Fig,'Style','Frame','Position',[70 250 180 90].*WS); uicontrol(Fig,'Style','Text', 'Position',[75 320 170 016].*WS,'String','Crosshair Position'); uicontrol(Fig,'Style','PushButton', 'Position',[75 316 170 006].*WS,... 'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin'); % uicontrol(fg,'Style','PushButton', 'Position',[75 315 170 020].*WS,'String','Crosshair Position',... % 'Callback','spm_orthviews(''Reposition'',[0 0 0]);','ToolTipString','move crosshairs to origin'); uicontrol(Fig,'Style','Text', 'Position',[75 295 35 020].*WS,'String','mm:'); uicontrol(Fig,'Style','Text', 'Position',[75 275 35 020].*WS,'String','vx:'); uicontrol(Fig,'Style','Text', 'Position',[75 255 75 020].*WS,'String','Img Intens.:'); st.mp = uicontrol(Fig,'Style','edit', 'Position',[110 295 135 020].*WS,'String','','Callback','spm_image(''setposmm'')','ToolTipString','move crosshairs to mm coordinates'); st.vp = uicontrol(Fig,'Style','edit', 'Position',[110 275 135 020].*WS,'String','','Callback','spm_image(''setposvx'')','ToolTipString','move crosshairs to voxel coordinates'); st.in = uicontrol(Fig,'Style','Text', 'Position',[150 255 85 020].*WS,'String',''); c = 'if get(gco,''Value'')==1, spm_orthviews(''Xhairs'',''off''), else, spm_orthviews(''Xhairs'',''on''); end;'; uicontrol(Fig,'Style','togglebutton','Position',[95 220 125 20].*WS,... 'String','Hide Crosshairs','Callback',c,'ToolTipString','show/hide crosshairs'); % Dipoles/seeds selection: %-------------------------- uicontrol(Fig,'Style','Frame','Position',[300 25 180 325].*WS); sdip.hdl.hcl = uicontrol(Fig,'Style','pushbutton','Position',[310 320 100 20].*WS, ... 'String','Clear all','CallBack','spm_eeg_inv_ecd_DrawDip(''ClearAll'')'); sdip.hdl.hseed=zeros(sdip.n_seeds,1); for ii=1:sdip.n_seeds if sdip.exitflag(ii)==1 sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','togglebutton','String',num2str(ii),... 'Position',[310+rem(ii-1,8)*20 295-fix((ii-1)/8)*20 20 20].*WS,... 'CallBack','spm_eeg_inv_ecd_DrawDip(''ChgSeed'')'); else sdip.hdl.hseed(ii) = uicontrol(Fig,'Style','Text','String',num2str(ii), ... 'Position',[310+rem(ii-1,8)*20 293-fix((ii-1)/8)*20 20 20].*WS) ; end end uicontrol(Fig,'Style','text','String','Select dipole # :', ... 'Position',[310 255-fix((sdip.n_seeds-1)/8)*20 110 20].*WS); txt_box = cell(sdip.n_dip,1); for ii=1:sdip.n_dip, txt_box{ii} = num2str(ii); end txt_box{sdip.n_dip+1} = 'all'; sdip.hdl.hdip = uicontrol(Fig,'Style','popup','String',txt_box, ... 'Position',[420 258-fix((sdip.n_seeds-1)/8)*20 40 20].*WS, ... 'Callback','spm_eeg_inv_ecd_DrawDip(''ChgDip'')'); % Dipoles orientation and strength: %----------------------------------- uicontrol(Fig,'Style','Frame','Position',[70 120 180 90].*WS); uicontrol(Fig,'Style','Text', 'Position',[75 190 170 016].*WS, ... 'String','Dipole orientation & strength'); uicontrol(Fig,'Style','Text', 'Position',[75 165 65 020].*WS,'String','vn_x_y_z:'); uicontrol(Fig,'Style','Text', 'Position',[75 145 75 020].*WS,'String','theta, phi:'); uicontrol(Fig,'Style','Text', 'Position',[75 125 75 020].*WS,'String','Dip intens.:'); sdip.hdl.hor1 = uicontrol(Fig,'Style','Text', 'Position',[140 165 105 020].*WS,'String','a'); sdip.hdl.hor2 = uicontrol(Fig,'Style','Text', 'Position',[150 145 85 020].*WS,'String','b'); sdip.hdl.int = uicontrol(Fig,'Style','Text', 'Position',[150 125 85 020].*WS,'String','c'); st.vols{1}.sdip = sdip; % First plot = all the seeds that converged ! l_conv = find(sdip.exitflag==1); if isempty(l_conv) error('No seed converged towards a stable solution, nothing to be displayed !') else spm_eeg_inv_ecd_DrawDip('DrawDip',l_conv,1) set(sdip.hdl.hseed(l_conv),'Value',1); % toggle all buttons end % get(sdip.hdl.hseed(1),'Value') % for ii=1:sdip.n_seeds, delete(hseed(ii)); end % h1 = uicontrol(Fig,'Style','togglebutton','Position',[600 25 10 10].*WS) % h2 = uicontrol(Fig,'Style','togglebutton','Position',[620 100 20 20].*WS,'String','1') % h2 = uicontrol(Fig,'Style','checkbox','Position',[600 100 10 10].*WS) % h3 = uicontrol(Fig,'Style','radiobutton','Position',[600 150 20 20].*WS) % h4 = uicontrol(Fig,'Style','radiobutton','Position',[700 150 20 20].*WS) % delete(h2),delete(h3),delete(h4), % delete(hdip) %________________________________________________________________________ case 'drawdip' %------------------------------------------------------------------------ % FORMAT spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip,sdip) % e.g. spm_eeg_inv_ecd_DrawDip('DrawDip',1,1,sdip) % e.g. spm_eeg_inv_ecd_DrawDip('DrawDip',[1:5],1,sdip) % when displaying a set of 'close' dipoles % this defines the limit between 'close' and 'far' % lim_cl = 10; %mm % No more limit. All source displayed as projected on mean 3D cut. if nargin<2 error('At least i_seed') end i_seed = varargin{1}; if nargin<3 i_dip = 1; else i_dip = varargin{2}; end if nargin<4 if isfield(st.vols{1},'sdip') sdip = st.vols{1}.sdip; else error('I can''t find sdip structure'); end else sdip = varargin{3}; st.vols{1}.sdip = sdip; end if any(i_seed>sdip.n_seeds) | i_dip>(sdip.n_dip+1) error('Wrong i_seed or i_dip index in spm_eeg_inv_ecd_DrawDip'); end % Note if i_dip==(sdip.n_dip+1) all dipoles are displayed simultaneously if i_dip==(sdip.n_dip+1) i_dip=1:sdip.n_dip; end % if seed indexes passed is wrong (no convergence) remove the wrong ones i_seed(find(sdip.exitflag(i_seed)~=1)) = []; if isempty(i_seed) error('You passed the wrong seed indexes...') end if size(i_seed,2)==1, i_seed=i_seed'; end % Display business %----------------- loc_mm = sdip.loc{i_seed(1)}(:,i_dip); if length(i_seed)>1 % unit = ones(1,sdip.n_dip); for ii = i_seed(2:end) loc_mm = loc_mm + sdip.loc{ii}(:,i_dip); end loc_mm = loc_mm/length(i_seed); end if length(i_dip)>1 loc_mm = mean(loc_mm,2); end % Place the underlying image at right cuts spm_orthviews('Reposition',loc_mm); if length(i_dip)>1 tabl_seed_dip = [kron(ones(length(i_dip),1),i_seed') ... kron(i_dip',ones(length(i_seed),1))]; else tabl_seed_dip = [i_seed' ones(length(i_seed),1)*i_dip]; end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % First point to consider % loc_mm = sdip.loc{i_seed(1)}(:,i_dip); % % % PLace the underlying image at right cuts % spm_orthviews('Reposition',loc_mm); % % spm_orthviews('Reposition',loc_vx); % % spm_orthviews('Xhairs','off') % % % if i_seed = set, Are there other dipoles close enough ? % tabl_seed_dip=[i_seed(1) i_dip]; % table summarising which set & dip to use. % if length(i_seed)>1 % unit = ones(1,sdip.n_dip); % for ii = i_seed(2:end)' % d2 = sqrt(sum((sdip.loc{ii}-loc_mm*unit).^2)); % l_cl = find(d2<=lim_cl); % if ~isempty(l_cl) % for jj=l_cl % tabl_seed_dip = [tabl_seed_dip ; [ii jj]]; % end % end % end % end % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Scaling, according to all dipoles in the selected seed sets. % The time displayed is the one corresponding to the maximum EEG power ! Mn_j = -1; l3 = -2:0; for ii = 1:length(i_seed) for jj = 1:sdip.n_dip Mn_j = max([Mn_j sqrt(sum(sdip.j{ii}(jj*3+l3,sdip.Mtb).^2))]); end end Mn_j = Mn_j + eps; st.vols{1}.sdip.tabl_seed_dip = tabl_seed_dip; % Display all dipoles, the 1st one + the ones close enough. % Run through the 6 colors and 9 markers to differentiate the dipoles. % NOTA: 2 dipoles coming from the same set will have same colour/marker ind = 1 ; dip_h = zeros(6,size(tabl_seed_dip,1),1); % each dipole displayed has 6 handles: % 2 per view (2*3): one for the line, the other for the circle js_m = zeros(3,1); % Deal with case of multiple i_seed and i_dip displayed. % make sure dipole from same i_seed have same colour but different marker. pi_dip = find(diff(tabl_seed_dip(:,2))); if isempty(pi_dip) % i.e. only one dip displayed per seed, use old fashion for ii=1:size(tabl_seed_dip,1) if ii>1 if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1) ind = ind+1; end end ic = mod(ind-1,Ncolors)+1; im = fix(ind/Ncolors)+1; loc_pl = sdip.loc{tabl_seed_dip(ii,1)}(:,tabl_seed_dip(ii,2)); js = sdip.j{tabl_seed_dip(ii,1)}(tabl_seed_dip(ii,2)*3+l3,sdip.Mtb); dip_h(:,ii) = add1dip(loc_pl,5e2*js/(eps+Mn_j*20),marker(im),colors(ic),st.vols{1}.ax,Fig,st.bb); js_m = js_m+js; end else for ii=1:pi_dip(1) if ii>1 if tabl_seed_dip(ii,1)~=tabl_seed_dip(ii-1,1) ind = ind+1; end end ic = mod(ind-1,Ncolors)+1; for jj=1:sdip.n_dip im = mod(jj-1,Nmarker)+1; loc_pl = sdip.loc{tabl_seed_dip(ii,1)}(:,jj); js = sdip.j{tabl_seed_dip(ii,1)}(jj*3+l3,sdip.Mtb); js_m = js_m+js; dip_h(:,ii+(jj-1)*pi_dip(1)) = ... add1dip(loc_pl,js/Mn_j*20,marker(im),colors(ic), ... st.vols{1}.ax,Fig,st.bb); end end end st.vols{1}.sdip.ax = dip_h; % Display dipoles orientation and strength js_m = js_m/size(tabl_seed_dip,1); [th,phi,Ijs_m] = cart2sph(js_m(1),js_m(2),js_m(3)); Njs_m = round(js_m'/(eps+Ijs_m*100))/100; Angle = round([th phi]*1800/pi)/10; set(sdip.hdl.hor1,'String',[num2str(Njs_m(1)),' ',num2str(Njs_m(2)), ... ' ',num2str(Njs_m(3))]); set(sdip.hdl.hor2,'String',[num2str(Angle(1)),' ',num2str(Angle(2))]); set(sdip.hdl.int,'String',Ijs_m); % Change the colour of toggle button of dipoles actually displayed for ii=tabl_seed_dip(:,1) set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 1 .7]); end %________________________________________________________________________ case 'clearall' %------------------------------------------------------------------------ % Clears all dipoles, and reset the toggle buttons if isfield(st.vols{1},'sdip') sdip = st.vols{1}.sdip; else error('I can''t find sdip structure'); end disp('Clears all dipoles') spm_eeg_inv_ecd_DrawDip('ClearDip'); for ii=1:st.vols{1}.sdip.n_seeds if sdip.exitflag(ii)==1 set(st.vols{1}.sdip.hdl.hseed(ii),'Value',0); end end set(st.vols{1}.sdip.hdl.hdip,'Value',1); %________________________________________________________________________ case 'chgseed' %------------------------------------------------------------------------ % Changes the seeds displayed % disp('Change seed') sdip = st.vols{1}.sdip; if isfield(sdip,'tabl_seed_dip') prev_seeds = p_seed(sdip.tabl_seed_dip); else prev_seeds = []; end l_seed = zeros(sdip.n_seeds,1); for ii=1:sdip.n_seeds if sdip.exitflag(ii)==1 l_seed(ii) = get(sdip.hdl.hseed(ii),'Value'); end end l_seed = find(l_seed); % Modify the list of seeds displayed if length(l_seed)==0 % Nothing left displayed i_seed=[]; elseif isempty(prev_seeds) % Just one dipole added, nothing before i_seed=l_seed; elseif length(prev_seeds)>length(l_seed) % One seed removed i_seed = prev_seeds; for ii=1:length(l_seed) p = find(prev_seeds==l_seed(ii)); if ~isempty(p) prev_seeds(p) = []; end % prev_seeds is left with the index of the one removed end i_seed(find(i_seed==prev_seeds)) = []; % Remove the dipole & change the button colour spm_eeg_inv_ecd_DrawDip('ClearDip',prev_seeds); set(sdip.hdl.hseed(prev_seeds),'BackgroundColor',[.7 .7 .7]); else % One dipole added i_seed = prev_seeds; for ii=1:length(prev_seeds) p = find(prev_seeds(ii)==l_seed); if ~isempty(p) l_seed(p) = []; end % l_seed is left with the index of the one added end i_seed = [i_seed ; l_seed]; end i_dip = get(sdip.hdl.hdip,'Value'); spm_eeg_inv_ecd_DrawDip('ClearDip'); if ~isempty(i_seed) spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip); end %________________________________________________________________________ case 'chgdip' %------------------------------------------------------------------------ % Changes the dipole index for the first seed displayed disp('Change dipole') sdip = st.vols{1}.sdip; i_dip = get(sdip.hdl.hdip,'Value'); if isfield(sdip,'tabl_seed_dip') i_seed = p_seed(sdip.tabl_seed_dip); else i_seed = []; end if ~isempty(i_seed) spm_eeg_inv_ecd_DrawDip('ClearDip') spm_eeg_inv_ecd_DrawDip('DrawDip',i_seed,i_dip); end %________________________________________________________________________ case 'cleardip' %------------------------------------------------------------------------ % FORMAT spm_eeg_inv_ecd_DrawDip('ClearDip',seed_i) % e.g. spm_eeg_inv_ecd_DrawDip('ClearDip') % clears all displayed dipoles % e.g. spm_eeg_inv_ecd_DrawDip('ClearDip',1) % clears the first dipole displayed if nargin>2 seed_i = varargin{1}; else seed_i = 0; end if isfield(st.vols{1},'sdip') sdip = st.vols{1}.sdip; else return; % I don't do anything, as I can't find sdip strucure end if isfield(sdip,'ax') Nax = size(sdip.ax,2); else return; % I don't do anything, as I can't find axes info end if seed_i==0 % removes everything for ii=1:Nax for jj=1:6 delete(sdip.ax(jj,ii)); end end for ii=sdip.tabl_seed_dip(:,1) set(sdip.hdl.hseed(ii),'BackgroundColor',[.7 .7 .7]); end sdip = rmfield(sdip,'tabl_seed_dip'); sdip = rmfield(sdip,'ax'); elseif seed_i<=Nax % remove one seed only l_seed = find(sdip.tabl_seed_dip(:,1)==seed_i); for ii=l_seed for jj=1:6 delete(sdip.ax(jj,ii)); end end sdip.ax(:,l_seed) = []; sdip.tabl_seed_dip(l_seed,:) = []; else error('Trying to clear unspecified dipole'); end st.vols{1}.sdip = sdip; %________________________________________________________________________ otherwise, warning('Unknown action string') end; return; %________________________________________________________________________ %________________________________________________________________________ %________________________________________________________________________ %________________________________________________________________________ % % SUBFUNCTIONS %________________________________________________________________________ %________________________________________________________________________ function dh = add1dip(loc,js,mark,col,ax,Fig,bb) % Plots the dipoles on the 3 views % Then returns the handle to the plots loc(1,:) = loc(1,:) - bb(1,1)+1; loc(2,:) = loc(2,:) - bb(1,2)+1; loc(3,:) = loc(3,:) - bb(1,3)+1; % +1 added to be like John's orthview code dh = zeros(6,1); figure(Fig) % Transverse slice, # 1 set(Fig,'CurrentAxes',ax{1}.ax) set(ax{1}.ax,'NextPlot','add') dh(1) = plot(loc(1),loc(2),[mark,col],'LineWidth',2); dh(2) = plot(loc(1)+[0 js(1)],loc(2)+[0 js(2)],col,'LineWidth',2); set(ax{1}.ax,'NextPlot','replace') % Coronal slice, # 2 set(Fig,'CurrentAxes',ax{2}.ax) set(ax{2}.ax,'NextPlot','add') dh(3) = plot(loc(1),loc(3),[mark,col],'LineWidth',2); dh(4) = plot(loc(1)+[0 js(1)],loc(3)+[0 js(3)],col,'LineWidth',2); set(ax{2}.ax,'NextPlot','replace') % Sagital slice, # 3 set(Fig,'CurrentAxes',ax{3}.ax) set(ax{3}.ax,'NextPlot','add') % dh(5) = plot(dim(2)-loc(2),loc(3),[mark,col],'LineWidth',2); % dh(6) = plot(dim(2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2); dh(5) = plot(bb(2,2)-bb(1,2)-loc(2),loc(3),[mark,col],'LineWidth',2); dh(6) = plot(bb(2,2)-bb(1,2)-loc(2)+[0 -js(2)],loc(3)+[0 js(3)],col,'LineWidth',2); set(ax{3}.ax,'NextPlot','replace') return %________________________________________________________________________ function pr_seed = p_seed(tabl_seed_dip) % Gets the list of seeds used in the previous display ls = sort(tabl_seed_dip(:,1)); if length(ls)==1 pr_seed = ls; else pr_seed = ls([find(diff(ls)) ; length(ls)]); end
github
philippboehmsturm/antx-master
spm_dcm_phase_results.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/dcm_meeg/spm_dcm_phase_results.m
4,023
utf_8
ebef13805761004edd122059cb98863f
function [DCM] = spm_dcm_phase_results(DCM,Action) % Results for Dynamic Causal Modeling (DCM) for phase coupling % FORMAT spm_dcm_phase_results(DCM,Action); % Action: % 'Sin(Data) - Region j' % 'Coupling (As)' % 'Coupling (Bs)' %__________________________________________________________________________ % Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging % Will Penny % $Id: spm_dcm_phase_results.m 3472 2009-10-16 17:10:26Z will $ % get figure handle %-------------------------------------------------------------------------- Fgraph = spm_figure('GetWin','Graphics'); colormap(gray) figure(Fgraph) clf xY = DCM.xY; nt = length(xY.y); % Nr of trial types nr = size(DCM.As,1); % Nr of sources nu = length(DCM.B); % Nr of experimental effects ns = size(xY.y{1},1); % Nr of time bins pst = xY.pst; % peri-stmulus time % switch %-------------------------------------------------------------------------- switch(lower(Action)) case{lower('Coupling (As)')} dx=min(0.1,1/nr); hold on cx=0; cy=0; text(cx,cy,'Posterior mean'); % reconstitute time-frequency coupling %---------------------------------------------------------------------- for i = 1:nr for j = 1:nr if (i==1) text(i*dx+cx,(j+1)*dx+cy,DCM.Sname{j}); end if (j==1) text((i+1)*dx+cx,j*dx+cy,DCM.Sname{i}); end text((i+1)*dx+cx,(j+1)*dx+cy,sprintf('%1.3f',abs(DCM.Ep.As(j,i)))); end end axis ij axis off title('Endogenous coupling (As)') cx=0; cy=0.5; text(cx,cy,'Posterior probability |As| > 0'); for i = 1:nr for j = 1:nr if (i==1) text(i*dx+cx,(j+1)*dx+cy,DCM.Sname{j}); end if (j==1) text((i+1)*dx+cx,j*dx+cy,DCM.Sname{i}); end text((i+1)*dx+cx,(j+1)*dx+cy,sprintf('%1.3f',DCM.Pp.As(j,i))); end end axis ij axis off case{lower('Coupling (Bs)')} dx=min(0.1,1/nr); hold on cx=0; cy=0; text(cx,cy,'Posterior mean'); % reconstitute time-frequency coupling %---------------------------------------------------------------------- for i = 1:nr for j = 1:nr if (i==1) text(i*dx+cx,(j+1)*dx+cy,DCM.Sname{j}); end if (j==1) text((i+1)*dx+cx,j*dx+cy,DCM.Sname{i}); end text((i+1)*dx+cx,(j+1)*dx+cy,sprintf('%1.3f',DCM.Ep.Bs{1}(j,i))); end end axis ij axis off title({'changes in coupling (Bs)';DCM.xU.name{1}}) cx=0; cy=0.5; text(cx,cy,'Posterior probability |Bs| > 0'); for i = 1:nr for j = 1:nr if (i==1) text(i*dx+cx,(j+1)*dx+cy,DCM.Sname{j}); end if (j==1) text((i+1)*dx+cx,j*dx+cy,DCM.Sname{i}); end text((i+1)*dx+cx,(j+1)*dx+cy,sprintf('%1.3f',DCM.Pp.Bs{1}(j,i))); end end axis ij axis off case {lower('Sin(Data) - Region 1')} plot_trials(DCM,1); case {lower('Sin(Data) - Region 2')} plot_trials(DCM,2); case {lower('Sin(Data) - Region 3')} if nr>2 plot_trials(DCM,3); else disp('There is no region 3'); end case {lower('Sin(Data) - Region 4')} if nr>3 plot_trials(DCM,4); else disp('There is no region 4'); end end function [] = plot_trials(DCM,j) % Only show a maximum of max_nt trials max_nt=16; nt = length(DCM.xY.y); nt=min(nt,max_nt); rnt=ceil(sqrt(nt)); for i=1:nt, subplot(rnt,rnt,i); plot(DCM.xY.pst,sin(DCM.xY.y{i}(:,j))); hold on plot(DCM.xY.pst,sin(DCM.y{i}(:,j)),'r'); title(sprintf('Trial %d: %s',i,DCM.xY.code{i})); end drawnow
github
philippboehmsturm/antx-master
spm_fx_mfm.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/dcm_meeg/spm_fx_mfm.m
10,959
utf_8
09cfd1e3edc8e5baca7c0a987c5b51b7
function [f,J,Q] = spm_fx_mfm(x,u,P,M) % state equations for neural-mass and mean-field models % FORMAT [f,J,Q] = spm_fx_mfm(x,u,P,M) % % x - states and covariances % % x{1}(i,j,k) - k-th state of j-th population on i-th source % i.e., running over sources, pop. and states % x{2}(:,:,i,j) - covariance among k states % i.e., running over states x states, sources and pop. % % population: 1 - excitatory spiny stellate cells (input cells) % 2 - inhibitory interneurons % 3 - excitatory pyramidal cells (output cells) % % state: 1 V - voltage % 2 gE - conductance (excitatory) % 3 gI - conductance (inhibitory) % %-------------------------------------------------------------------------- % refs: % % Marreiros et al (2008) Population dynamics under the Laplace assumption % % See also: % % Friston KJ. % The labile brain. I. Neuronal transients and nonlinear coupling. Philos % Trans R Soc Lond B Biol Sci. 2000 Feb 29;355(1394):215-36. % % McCormick DA, Connors BW, Lighthall JW, Prince DA. % Comparative electrophysiology of pyramidal and sparsely spiny stellate % neurons of the neocortex. J Neurophysiol. 1985 Oct;54(4):782-806. % % Brunel N, Wang XJ. % What determines the frequency of fast network oscillations with irregular % neural discharges? I. Synaptic dynamics and excitation-inhibition % balance. J Neurophysiol. 2003 Jul;90(1):415-30. % % Brunel N, Wang XJ. % Effects of neuromodulation in a cortical network model of object working % memory dominated by recurrent inhibition. J Comput Neurosci. 2001 % Jul-Aug;11(1):63-85. % %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Karl Friston % $Id: spm_fx_mfm.m 4096 2010-10-22 19:40:34Z karl $ % get dimensions and configure state variables %-------------------------------------------------------------------------- try, x = spm_unvec(x,M.x); end xin = x; if iscell(x) mfm = 1; % mean-field model else mfm = 0; x = {x}; % neural-mass model end ns = size(x{1},1); % number of sources np = size(x{1},2); % number of populations nc = length(P.A); % number of connections % extrinsic connection strengths %========================================================================== % exponential transform to ensure positivity constraints %-------------------------------------------------------------------------- A{1} = exp(P.A{1})/2; % forward A{2} = exp(P.A{2})/4; % backward A{3} = exp(P.A{3})/4; % lateral C = exp(P.C); % subcortical % switches on extrinsic afferent connections (np x nc) %-------------------------------------------------------------------------- try SA = P.SA; catch SA = sparse([1 0 1; 0 1 1; 0 0 0]); end % intrinsic connection strengths %========================================================================== G = exp(P.G); try % get intrinsic connections %---------------------------------------------------------------------- GE = P.GE; GI = P.GI; catch % intrinsic connections (np x np) - excitatory %---------------------------------------------------------------------- GE = [0 0 1/2; 0 0 1; 1/2 0 0 ]; % intrinsic connections (np x np) - inhibitory %---------------------------------------------------------------------- GI = [0 1/4 0; 0 0 0; 0 1 0]; end % rate constants (ns x np) (excitatory 4ms, inhibitory 16ms) %-------------------------------------------------------------------------- KE = exp(-P.T)*1000/4; % excitatory time constants KI = 1000/16; % inhibitory time constants % Voltages %-------------------------------------------------------------------------- VL = -70; % reversal potential leak (K) VE = 60; % reversal potential excite (Na) VI = -90; % reversal potential inhib (Cl) VR = -40; % threshold potential CV = exp(P.CV)*8/1000; % membrane capacitance GL = 1; % leak conductance fxx = sparse([2 3 1 1],[1 1 2 3],-1/CV); % curvature: df(V)/dxx % mean-field effects: the paramters of the sigmoid activation function %========================================================================== if mfm % covariance among states (mV^2) %---------------------------------------------------------------------- for i = 1:ns for j = 1:np Cx{i,j} = x{2}(:,:,i,j); Vx(i,j) = Cx{i,j}(1,1); % population variance end end D = sparse(diag([1/8 1 1])); % diffusion D = exp(P.S)*D; else % neural-mass approximation to covariance of states %---------------------------------------------------------------------- try Cx = M.Cx; catch Cx = [75 0.2 0.8; 0.2 0.004 0 ; 0.8 0 0.02]; end Cx = exp(P.S)*Cx; Vx = Cx(1,1); end % mean population firing and afferent extrinsic input %-------------------------------------------------------------------------- m = spm_Ncdf_jdw(x{1}(:,:,1),VR,Vx); for k = 1:nc a(:,k) = A{k}*m(:,end); end % Exogenous input (to first population x{:,1}) %-------------------------------------------------------------------------- U = C*u(:); % Exogenous input (to excitatory populations) %-------------------------------------------------------------------------- try B = exp(P.X)/8; catch B = 0; end % flow and dispersion over every (ns x np) subpopulation %========================================================================== f = x; for i = 1:ns for j = 1:np % 1st moment - expected states %================================================================== % intrinsic coupling %------------------------------------------------------------------ E = G(i)*GE(j,:)*m(i,:)'; I = GI(j,:)*m(i,:)'; % extrinsic coupling (excitatory only) and background activity %------------------------------------------------------------------ E = E + SA(j,:)*a(i,:)' + B; % Voltage %------------------------------------------------------------------ f{1}(i,j,1) = (GL*(VL - x{1}(i,j,1)) + ... x{1}(i,j,2)*(VE - x{1}(i,j,1)) + ... x{1}(i,j,3)*(VI - x{1}(i,j,1)) )/CV; % Exogenous input (U) %------------------------------------------------------------------ if j == 1 f{1}(i,j,1) = f{1}(i,j,1) + U(i)/CV; end % Conductances %------------------------------------------------------------------ f{1}(i,j,2) = (E - x{1}(i,j,2))*KE(i); f{1}(i,j,3) = (I - x{1}(i,j,3))*KI; % 2nd moments - covariances %================================================================== if mfm % add curvature-dependent dispersion to flow %-------------------------------------------------------------- f{1}(i,j,1) = f{1}(i,j,1) + tr(Cx{i,j},fxx)/2; % df/dx %-------------------------------------------------------------- Sg = -GL - x{1}(i,j,2) - x{1}(i,j,3); fx = [Sg/CV (VE - x{1}(i,j,1))/CV (VI - x{1}(i,j,1)/CV); 0 -KE(i) 0 ; 0 0 -KI ]; % dCdt %-------------------------------------------------------------- St = fx*Cx{i,j} + D; f{2}(:,:,i,j) = St + St'; else % fixed covariance (Cx) %-------------------------------------------------------------- f{1}(i,j,1) = f{1}(i,j,1) + tr(Cx,fxx)/2; end end end % vectorise equations of motion %========================================================================== f = spm_vec(f); if nargout < 2, return, end % Jacobian %========================================================================== J = spm_cat(spm_diff('spm_fx_mfm',xin,u,P,M,1)); if nargout < 3, return, end % Delays %========================================================================== % Delay differential equations can be integrated efficiently (but % approximately) by absorbing the delay operator into the Jacobian % % dx(t)/dt = f(x(t - d)) % = Q(d)f(x(t)) % % J(d) = Q(d)df/dx %-------------------------------------------------------------------------- % [specified] fixed parameters %-------------------------------------------------------------------------- try D = M.pF.D; catch D = [2 16]; end d = -D.*exp(P.D)/1000; nk = 3; % number of states Sp = kron(ones(nk,nk),kron( eye(np,np),eye(ns,ns))); % states: same pop. Ss = kron(ones(nk,nk),kron(ones(np,np),eye(ns,ns))); % states: same source Dp = ~Ss; % states: different sources Ds = ~Sp & Ss; % states: same source different pop. D = d(2)*Dp + d(1)*Ds; % disable for mean field models (temporarily) %-------------------------------------------------------------------------- if mfm Cp = kron(ones(nk,1),kron(kron(eye(np,np) ,eye(ns,ns)),ones(1,nk*nk))); Cs = kron(ones(nk,1),kron(kron(ones(np,np),eye(ns,ns)),ones(1,nk*nk))); Dp = kron(kron( eye(np,np),eye(ns,ns)),kron(ones(nk,nk),ones(nk,nk))); Ds = kron(kron(ones(np,np),eye(ns,ns)),kron(ones(nk,nk),ones(nk,nk))); Sp = spm_cat({Sp Cp; Cp' Dp}); Ss = spm_cat({Ss Cs; Cs' Ds}); Dp = ~Ss; % states: different sources Ds = ~Sp & Ss; % states: same source different pop. D = d(2)*Dp + d(1)*Ds; end % Implement: dx(t)/dt = f(x(t - d)) = inv(1 - D.*dfdx)*f(x(t)) % = Q*f = Q*J*x(t) %-------------------------------------------------------------------------- Q = inv(speye(length(J)) - D.*J); % trace(a*b) %-------------------------------------------------------------------------- function x = tr(a,b); %__________________________________________________________________________ b = b'; x = a(:)'*b(:);
github
philippboehmsturm/antx-master
spm_api_erp.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/dcm_meeg/spm_api_erp.m
46,323
utf_8
11703ffca3f14fa523b3ddecc5f685f2
function varargout = spm_api_erp(varargin) % SPM_API_ERP Application M-file for spm_api_erp.fig % FIG = SPM_API_ERP launch spm_api_erp GUI. % SPM_API_ERP('callback_name', ...) invoke the named callback. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Karl Friston % $Id: spm_api_erp.m 4570 2011-11-23 17:09:59Z vladimir $ if nargin == 0 || nargin == 1 % LAUNCH GUI fig = openfig(mfilename,'reuse'); S0 = spm('WinSize','0',1); set(fig,'units','pixels'); Fdim = get(fig,'position'); set(fig,'position',[S0(1) S0(2) 0 0] + Fdim); Fgraph = spm_figure('GetWin','Graphics'); % Use system color scheme for figure: set(fig,'Color',get(0,'defaultUicontrolBackgroundColor')); % Generate a structure of handles to pass to callbacks, and store it. handles = guihandles(fig); handles.Fgraph = Fgraph; guidata(fig, handles); if nargin == 1 load_Callback(fig, [], handles, varargin{1}) end if nargout > 0 varargout{1} = fig; end elseif ischar(varargin{1}) % INVOKE NAMED SUBFUNCTION OR CALLBACK try if (nargout) [varargout{1:nargout}] = feval(varargin{:}); % FEVAL switchyard else feval(varargin{:}); % FEVAL switchyard end catch disp(lasterr); end end %-DCM files and directories: Load and save %========================================================================== % --- Executes on button press in load. % ------------------------------------------------------------------------- function varargout = load_Callback(hObject, eventdata, handles, varargin) try DCM = varargin{1}; [p,f] = fileparts(DCM.name); catch [f,p] = uigetfile('*.mat','please select DCM file'); cd(p) name = fullfile(p,f); DCM = load(name,'-mat'); DCM = DCM.DCM; DCM.name = name; handles.DCM = DCM; guidata(hObject,handles); end % Type of analysis %-------------------------------------------------------------------------- % 'ERP' - Event related responses % 'CSD' - Cross-spectral density % 'SSR' - Steady-state responses % 'IND' - Induced responses % 'PHA' - (for phase coupling) try model = DCM.options.analysis; catch model = get(handles.ERP,'String'); model = model{get(handles.ERP,'Value')}; DCM.options.analysis = model; end switch model case{'ERP'}, set(handles.ERP,'Value',1); case{'CSD'}, set(handles.ERP,'Value',2); case{'SSR'}, set(handles.ERP,'Value',3); case{'IND'}, set(handles.ERP,'Value',4); case{'PHA'}, set(handles.ERP,'Value',5); otherwise end handles = ERP_Callback(hObject, eventdata, handles); % Type of model (neuronal) %-------------------------------------------------------------------------- % 'ERP' - (linear second order NMM slow) % 'SEP' - (linear second order NMM fast) % 'CMC' - (linear second order NMM Canonical microcircuit) % 'LFP' - (linear second order NMM self-inhibition) % 'NMM' - (nonlinear second order NMM first-order moments) % 'MFM' - (nonlinear second order NMM second-order moments) % 'DEM' - (functional architecture based on a DEM scheme) try model = DCM.options.model; catch model = get(handles.model,'String'); model = model{get(handles.model,'Value')}; DCM.options.model = model; end switch model case{'ERP'}, set(handles.model,'Value',1); case{'SEP'}, set(handles.model,'Value',2); case{'CMC'}, set(handles.model,'Value',3); case{'LFP'}, set(handles.model,'Value',4); case{'NMM'}, set(handles.model,'Value',5); case{'MFM'}, set(handles.model,'Value',6); otherwise end % Type of model (spatial) %-------------------------------------------------------------------------- % 'ECD' - Equivalent current dipole % 'IMG' - Imaging % 'LFP' - Local field potentials try model = DCM.options.spatial; catch model = get(handles.Spatial,'String'); model = model{get(handles.Spatial,'Value')}; DCM.options.spatial = model; end if ismember(DCM.options.analysis, {'IND', 'PHA'}) switch model case{'IMG'}, set(handles.Spatial,'Value',1); case{'ECD'}, set(handles.Spatial,'Value',1); case{'LFP'}, set(handles.Spatial,'Value',2); otherwise end else switch model case{'IMG'}, set(handles.Spatial,'Value',1); case{'ECD'}, set(handles.Spatial,'Value',2); case{'LFP'}, set(handles.Spatial,'Value',3); otherwise end end % Filename %-------------------------------------------------------------------------- try, set(handles.name,'String',f); end % Source location %-------------------------------------------------------------------------- try, DCM.Lpos = DCM.M.dipfit.Lpos; end % enter options from saved options and execute data_ok and spatial_ok %-------------------------------------------------------------------------- try, set(handles.Y1, 'String', num2str(DCM.options.trials,'%7.0f')); end try, set(handles.T1, 'String', num2str(DCM.options.Tdcm(1))); end try, set(handles.T2, 'String', num2str(DCM.options.Tdcm(2))); end try, set(handles.Hz1,'String', num2str(DCM.options.Fdcm(1))); end try, set(handles.Hz2,'String', num2str(DCM.options.Fdcm(2))); end try, set(handles.Rft,'String', num2str(DCM.options.Rft)); end try, set(handles.Nmodes, 'Value', DCM.options.Nmodes); end try, set(handles.h, 'Value', ... find(str2double(get(handles.h,'String')) == DCM.options.h)); end try, set(handles.han, 'Value', DCM.options.han); end try, set(handles.D, 'Value', DCM.options.D); end try, set(handles.lock, 'Value', DCM.options.lock); end try, set(handles.location, 'Value', DCM.options.location); end try, set(handles.symmetry, 'Value', DCM.options.symmetry); end try, set(handles.design, 'String',num2str(DCM.xU.X','%7.2f')); end try, set(handles.Uname, 'String',DCM.xU.name); end try, set(handles.Sname, 'String',DCM.Sname); end try, set(handles.onset, 'String',num2str(DCM.options.onset)); end try, set(handles.dur, 'String',num2str(DCM.options.dur)); end try, set(handles.Slocation, 'String',num2str(DCM.Lpos','%4.0f')); end % Imaging %-------------------------------------------------------------------------- switch DCM.options.spatial case{'IMG'} set(handles.Imaging,'Enable','on' ) otherwise set(handles.Imaging,'Enable','off' ) end handles.DCM = DCM; guidata(hObject, handles); % estimation and results %-------------------------------------------------------------------------- try handles.DCM.F; set(handles.results, 'Enable','on'); switch handles.DCM.options.spatial case{'IMG'} set(handles.Imaging,'Enable','on'); otherwise set(handles.Imaging,'Enable','off'); end catch set(handles.results, 'Enable','off'); end guidata(hObject, handles); % data & design specification %-------------------------------------------------------------------------- try handles = data_ok_Callback(hObject, eventdata, handles); guidata(hObject, handles); catch return end % spatial model specification %-------------------------------------------------------------------------- try handles = spatial_ok_Callback(hObject, eventdata, handles); guidata(hObject, handles); catch return end % connections specification %-------------------------------------------------------------------------- try connections_Callback(hObject, eventdata, handles); set(handles.estimate, 'Enable', 'on'); set(handles.initialise, 'Enable', 'on'); guidata(hObject, handles); catch return end % --- Executes on button press in save. % ------------------------------------------------------------------------- function handles = save_Callback(hObject, eventdata, handles) handles = reset_Callback(hObject, eventdata, handles); try [p,file] = fileparts(handles.DCM.name); catch try [p,file] = fileparts(handles.DCM.xY.Dfile); file = ['DCM_' file]; catch file = ['DCM' date]; end end [file,fpath] = uiputfile(['DCM*.mat'],'DCM file to save',file); if fpath handles.DCM.name = fullfile(fpath,file); set(handles.name,'String',file); DCM = handles.DCM; save(DCM.name,'DCM') set(handles.estimate, 'Enable', 'on') set(handles.initialise, 'Enable', 'on'); cd(fpath) end % assign in base %-------------------------------------------------------------------------- assignin('base','DCM',handles.DCM) guidata(hObject,handles); % store selections in DCM % ------------------------------------------------------------------------- function handles = reset_Callback(hObject, eventdata, handles) % analysis type %-------------------------------------------------------------------------- model = get(handles.ERP, 'String'); model = model{get(handles.ERP, 'Value')}; handles.DCM.options.analysis = model; if isequal(model, 'ERP') set(handles.han, 'Enable', 'on'); else set(handles.han, 'Value', 0); set(handles.han, 'Enable', 'off'); end if isequal(model, 'PHA') set(handles.text20, 'String', 'sub-trials'); else set(handles.text20, 'String', 'modes'); end % model type %-------------------------------------------------------------------------- model = get(handles.model, 'String'); model = model{get(handles.model, 'Value')}; handles.DCM.options.model = model; % spatial type %-------------------------------------------------------------------------- model = get(handles.Spatial, 'String'); model = model{get(handles.Spatial, 'Value')}; handles.DCM.options.spatial = model; handles.DCM.options.trials = str2num(get(handles.Y1, 'String')); handles.DCM.options.Tdcm(1) = str2num(get(handles.T1, 'String')); handles.DCM.options.Tdcm(2) = str2num(get(handles.T2, 'String')); handles.DCM.options.Fdcm(1) = str2num(get(handles.Hz1, 'String')); handles.DCM.options.Fdcm(2) = str2num(get(handles.Hz2, 'String')); handles.DCM.options.Rft = str2num(get(handles.Rft, 'String')); handles.DCM.options.onset = str2num(get(handles.onset, 'String')); handles.DCM.options.dur = str2num(get(handles.dur, 'String')); handles.DCM.options.Nmodes = get(handles.Nmodes, 'Value'); detrend_val = str2double(get(handles.h, 'String')); handles.DCM.options.h = detrend_val(get(handles.h, 'Value')); handles.DCM.options.han = get(handles.han, 'Value'); handles.DCM.options.D = get(handles.D, 'Value'); handles.DCM.options.lock = get(handles.lock, 'Value'); handles.DCM.options.location = get(handles.location, 'Value'); handles.DCM.options.symmetry = get(handles.symmetry, 'Value'); guidata(hObject,handles); % Data selection and design %========================================================================== % --- Executes on button press in Datafile. %-------------------------------------------------------------------------- function Datafile_Callback(hObject, eventdata, handles) %-Get trials and data %-------------------------------------------------------------------------- try trials = str2num(get(handles.Y1,'String')); handles.DCM.options.trials = trials; set(handles.Y1,'String',num2str(trials,'%7.0f')) m = length(handles.DCM.options.trials); catch m = 1; set(handles.Y1,'String','1') end if isempty(m) || m == 0 m = 1; set(handles.Y1,'String','1'); end handles = Xdefault(hObject,handles,m); %-Get new trial data from file %-------------------------------------------------------------------------- [f,p] = uigetfile({'*.mat'}, 'please select data file'); if f == 0, return; end handles.DCM.xY = []; handles.DCM.xY.Dfile = fullfile(p,f); D = spm_eeg_load(handles.DCM.xY.Dfile); [ok, D] = check(D,'dcm'); if ~ok if check(D, 'basic') warndlg(['The requested file is not ready for DCM.'... 'Use prep to specify sensors and fiducials or LFP channels.']); else warndlg('The meeg file is corrupt or incomplete'); end handles.DCM.xY.Dfile = []; set(handles.data_ok, 'enable', 'off'); guidata(hObject,handles); return end [mod, list] = modality(D, 0, 1); if isequal(mod, 'Multimodal') qstr = 'Only one modality can be modelled at a time. Please select.'; if numel(list) < 4 % Nice looking dialog. Will usually be OK options = []; options.Default = list{1}; options.Interpreter = 'none'; handles.DCM.xY.modality = questdlg(qstr, 'Select modality', list{:}, options); else % Ugly but can accomodate more buttons ind = menu(qstr, list); handles.DCM.xY.modality = list{ind}; end else handles.DCM.xY.modality = mod; end if isequal(handles.DCM.xY.modality, 'LFP') set(handles.Spatial, 'Value', strmatch('LFP', get(handles.Spatial, 'String'))); end % Assemble and display data %-------------------------------------------------------------------------- handles = reset_Callback(hObject, eventdata, handles); try handles.DCM = spm_dcm_erp_data(handles.DCM,handles.DCM.options.h); if isfield(handles.DCM.xY, 'xy') spm_dcm_erp_results(handles.DCM, 'Data'); else spm_dcm_ind_results(handles.DCM, 'Wavelet'); end set(handles.dt, 'String',sprintf('bins: %.1fms', handles.DCM.xY.dt*1000)) set(handles.dt, 'Visible','on') set(handles.data_ok, 'enable', 'on'); guidata(hObject,handles); catch errordlg({'please ensure trial selection and data are consistent'; 'data have not been changed'}); set(handles.data_ok, 'enable', 'off'); end set(handles.design,'enable', 'on') set(handles.Uname, 'enable', 'on') set(handles.Y, 'enable', 'on') guidata(hObject,handles); % --- Executes on button press in Y to display data %-------------------------------------------------------------------------- function Y_Callback(hObject, eventdata, handles) handles = reset_Callback(hObject, eventdata, handles); try DCM = spm_dcm_erp_data(handles.DCM,handles.DCM.options.h); if isfield(DCM.xY, 'xy') spm_dcm_erp_results(DCM, 'Data'); else spm_dcm_ind_results(DCM, 'Wavelet'); end set(handles.dt, 'String',sprintf('bins: %.1fms', DCM.xY.dt*1000)) set(handles.dt, 'Visible','on') set(handles.data_ok, 'enable', 'on'); guidata(hObject,handles); catch errordlg({'please ensure trial selection and data are consistent'; 'data have not been changed'}); set(handles.data_ok, 'enable', 'off'); end % --- Executes on button press in Uname. %-------------------------------------------------------------------------- function Uname_Callback(hObject, eventdata, handles) handles = reset_Callback(hObject, eventdata, handles); try m = length(handles.DCM.options.trials); catch warndlg('please select trials') handles = Xdefault(hObject,handles,1); return end Str = cellstr(get(handles.Uname,'String')); n = size(handles.DCM.xU.X,2); for i = 1:n try Uname{i} = Str{i}; catch Uname{i} = sprintf('effect %i',i); end end set(handles.Uname,'string',Uname) handles.DCM.xU.name = Uname; guidata(hObject,handles); % --- Executes on button press in design. %-------------------------------------------------------------------------- function design_Callback(hObject, eventdata, handles) handles = reset_Callback(hObject, eventdata, handles); try m = length(handles.DCM.options.trials); catch handles = Xdefault(hObject,handles,1); warndlg('please select trials') return end try X = str2num(get(handles.design,'String'))'; if isempty(X) X = sparse(m,0); end handles.DCM.xU.X = X(1:m,:); set(handles.design, 'String',num2str(handles.DCM.xU.X','%7.2f')); catch handles = Xdefault(hObject,handles,m); end n = size(handles.DCM.xU.X,2); Uname = {}; for i = 1:n try Uname{i} = handles.DCM.xU.name{i}; catch Uname{i} = sprintf('effect %i',i); end end set(handles.Uname,'string',Uname) handles.DCM.xU.name = Uname; guidata(hObject,handles); %-Executes on button press in data_ok. %-------------------------------------------------------------------------- function handles = data_ok_Callback(hObject, eventdata, handles) %-assemble and display trials. %-------------------------------------------------------------------------- Y_Callback(hObject, eventdata, handles); handles = guidata(hObject); switch get(handles.data_ok,'enable') case{'off'} return end %-check trial-specific effects %-------------------------------------------------------------------------- design_Callback(hObject, eventdata, handles) handles = guidata(hObject); % enable next stage, disable data specification %-------------------------------------------------------------------------- set(handles.ERP, 'Enable', 'off'); set(handles.model, 'Enable', 'off'); set(handles.Datafile, 'Enable', 'off'); set(handles.Y1, 'Enable', 'off'); set(handles.T1, 'Enable', 'off'); set(handles.T2, 'Enable', 'off'); set(handles.Nmodes, 'Enable', 'off'); set(handles.h, 'Enable', 'off'); set(handles.D, 'Enable', 'off'); set(handles.design, 'Enable', 'off'); set(handles.Uname, 'Enable', 'off'); set(handles.data_ok, 'Enable', 'off'); set(handles.Spatial, 'Enable', 'on'); set(handles.plot_dipoles, 'Enable', 'on'); set(handles.Sname, 'Enable', 'on'); set(handles.Slocation, 'Enable', 'on'); set(handles.spatial_back, 'Enable', 'on'); set(handles.spatial_ok, 'Enable', 'on'); switch handles.DCM.options.analysis case{'SSR','CSD'} set(handles.onset, 'Enable', 'off'); set(handles.dur, 'Enable', 'off'); otherwise set(handles.onset, 'Enable', 'on'); set(handles.dur, 'Enable', 'on'); end guidata(hObject, handles); % spatial model specification %========================================================================== function handles = spatial_ok_Callback(hObject, eventdata, handles) handles = reset_Callback(hObject, eventdata, handles); % spatial model - source names %-------------------------------------------------------------------------- Sname = cellstr(get(handles.Sname,'String')); Nareas = length(Sname); Nmodes = get(handles.Nmodes,'Value'); Nchannels = length(handles.DCM.xY.Ic); % switch for spatial forward model (for EEG or MEG) %-------------------------------------------------------------------------- DCM = handles.DCM; DCM.Sname = Sname; switch DCM.options.spatial case {'ECD','IMG'} % read location coordinates %------------------------------------------------------------------ Slocation = zeros(Nareas, 3); tmp = get(handles.Slocation, 'String'); if ~isempty(tmp) && size(tmp,1) == Nareas for i = 1:Nareas tmp2 = str2num(char(tmp(i, :))); if length(tmp2) ~= 3 errordlg(sprintf('coordinates of source %d invalid',i)); return; else Slocation(i, :) = tmp2; end end if size(Slocation, 1) ~= Nareas errordlg('Number of sources and locations must correspond'); return; end else errordlg(sprintf('Please specify %d source locations.', Nareas)); return end % set prior expectations on location %------------------------------------------------------------------ DCM.Lpos = Slocation'; % forward model (spatial) %------------------------------------------------------------------ DCM = spm_dcm_erp_dipfit(DCM); set(handles.plot_dipoles,'enable','on') case{'LFP'} if ~isdeployed, addpath(fullfile(spm('Dir'),'toolbox','Neural_Models')); end % for LFP %------------------------------------------------------------------ DCM.Lpos = zeros(3,0); try set(handles.Slocation, 'String', Sname(1:Nchannels)); set(handles.plot_dipoles,'enable','off') catch warndlg('There are more LFP channels than sources') return end otherwise warndlg('Unknown data modality') return end handles.DCM = DCM; set(handles.Spatial, 'Enable', 'off'); set(handles.data_ok, 'Enable', 'off'); set(handles.spatial_ok, 'Enable', 'off'); set(handles.onset, 'Enable', 'off'); set(handles.dur, 'Enable', 'off'); set(handles.Sname, 'Enable', 'off'); set(handles.Slocation, 'Enable', 'off'); set(handles.spatial_back, 'Enable', 'off'); set(handles.con_reset, 'Enable', 'on'); set(handles.priors, 'Enable', 'on'); set(handles.connectivity_back,'Enable', 'on'); set(handles.Hz1, 'Enable', 'on'); set(handles.Hz2, 'Enable', 'on'); set(handles.Rft, 'Enable', 'on'); % [re]-set connections %-------------------------------------------------------------------------- handles = connections_Callback(hObject, eventdata, handles); guidata(hObject,handles); % --- Executes on button press in pos. %-------------------------------------------------------------------------- function pos_Callback(hObject, eventdata, handles) [f,p] = uigetfile('*.mat','source (n x 3) location file'); Slocation = load(fullfile(p,f)); name = fieldnames(Slocation); Slocation = getfield(Slocation, name{1}); set(handles.Slocation,'String',num2str(Slocation,'%4.0f')); % --- Executes on button press in spatial_back. %---------------------------------------------------------------------- function spatial_back_Callback(hObject, eventdata, handles) set(handles.Spatial, 'Enable', 'off'); set(handles.spatial_ok, 'Enable', 'off'); set(handles.onset, 'Enable', 'off'); set(handles.dur, 'Enable', 'off'); set(handles.Sname, 'Enable', 'off'); set(handles.Slocation, 'Enable', 'off'); set(handles.spatial_back, 'Enable', 'off'); set(handles.Y, 'Enable', 'on'); set(handles.Y1, 'Enable', 'on'); set(handles.T1, 'Enable', 'on'); set(handles.T2, 'Enable', 'on'); set(handles.Nmodes, 'Enable', 'on'); set(handles.h, 'Enable', 'on'); set(handles.D, 'Enable', 'on'); set(handles.design, 'Enable', 'on'); set(handles.Uname, 'Enable', 'on'); set(handles.data_ok, 'Enable', 'on'); set(handles.ERP, 'Enable', 'on'); set(handles.Datafile, 'Enable', 'on'); guidata(hObject, handles); ERP_Callback(hObject, eventdata, handles); % --- Executes on button press in plot_dipoles. %-------------------------------------------------------------------------- function plot_dipoles_Callback(hObject, eventdata, handles) % read location coordinates %-------------------------------------------------------------------------- tmp = get(handles.Slocation, 'String'); Slocation = []; if ~isempty(tmp) for i = 1:size(tmp, 1) tmp2 = str2num(char(tmp(i, :)))'; if length(tmp2) == 3 Slocation = [Slocation tmp2]; end end end Nlocations = size(Slocation, 2); sdip.n_seeds = 1; sdip.n_dip = Nlocations; sdip.Mtb = 1; sdip.j{1} = zeros(3*Nlocations, 1); sdip.loc{1} = Slocation; spm_eeg_inv_ecd_DrawDip('Init', sdip) %-Connectivity %========================================================================== % Draw buttons %-------------------------------------------------------------------------- function handles = connections_Callback(hObject, eventdata, handles) handles = reset_Callback(hObject, eventdata, handles); DCM = handles.DCM; % numbers of buttons %-------------------------------------------------------------------------- n = length(DCM.Sname); % number of sources m = size(DCM.xU.X,2); % number of experimental inputs switch DCM.options.analysis case{'SSR','CSD'} % for Steady-state responses l = n; % number of endogenous inputs otherwise l = length(DCM.options.onset); % number of peristimulus inputs end switch DCM.options.model case{'DEM'} try nk = 1; % number of levels nj = 16; % number of states per level l = 0; catch return end otherwise nk = 3; % number of connection types nj = ones(nk,1)*n; % number of sources end % remove previous objects %-------------------------------------------------------------------------- h = get(handles.SPM,'Children'); for i = 1:length(h) if strcmp(get(h(i),'Tag'),'tmp') delete(h(i)); end end % no changes in coupling %-------------------------------------------------------------------------- if ~m, B = {}; DCM.B = {}; end if ~l, C = {}; DCM.C = {}; end % check DCM.A, DCM.B, ... %-------------------------------------------------------------------------- try, if size(DCM.A{1},1) ~= n, DCM = rmfield(DCM,'A'); end, end try, if size(DCM.B{1},1) ~= n, DCM = rmfield(DCM,'B'); end, end try, if numel(DCM.B) ~= m, DCM = rmfield(DCM,'B'); end, end try, if size(DCM.C,1) ~= n, DCM = rmfield(DCM,'C'); end, end try, if size(DCM.C,2) ~= l, DCM = rmfield(DCM,'C'); end, end % connection buttons (A) %-------------------------------------------------------------------------- set(handles.con_reset,'Units','Normalized') p = get(handles.con_reset,'Position'); x0 = 0.1; y0 = 0.425; sx = 1/36; sy = 1/72; for i = 1:n for k = 1:nk for j = 1:nj(k) x = x0 + (j - 1)*sx + (sum(nj(1:(k - 1))) + k - 1)*sx; y = y0 - (i + 4)*sy; str = sprintf('data.DCM.A{%i}(%i,%i)',k,i,j); str = ['data=guidata(gcbo);' str '=get(gcbo,''Value'');guidata(gcbo,data)']; A{k}(i,j) = uicontrol(handles.SPM,... 'Units','Normalized',... 'Position',[x y sx sy],... 'Style','radiobutton',... 'Tag','tmp',... 'Callback',str); % within region, between frequency coupling for 'Induced' %-------------------------------------------------------------- if i == j set(A{k}(i,j),'Enable','off') end % allow nonlinear self-connections (induced responses) %-------------------------------------------------------------- if strcmpi(DCM.options.analysis,'IND') && k == 2 set(A{k}(i,j),'Enable','on') end if strcmpi(DCM.options.model,'DEM') set(A{k}(i,j),'Enable','on') end try set(A{k}(i,j),'Value',DCM.A{k}(i,j)); catch DCM.A{k}(i,j) = get(A{k}(i,j),'Value'); end end end end % connection buttons (B) %-------------------------------------------------------------------------- for i = 1:n for k = 1:m for j = 1:n x = x0 + (j - 1)*sx + ((k - 1)*n + k - 1)*sx; y = y0 - (i + 4)*sy - (n + 1)*sy; str = sprintf('data.DCM.B{%i}(%i,%i)',k,i,j); str = ['data=guidata(gcbo);' str '=get(gcbo,''Value'');guidata(gcbo,data)']; B{k}(i,j) = uicontrol(handles.SPM,... 'Units','Normalized',... 'Position',[x y sx sy],... 'Style','radiobutton',... 'Tag','tmp',... 'Callback',str); % intrinsic modulation of H_e %-------------------------------------------------------------- if i == j set(B{k}(i,j),'Enable','on') end try set(B{k}(i,j),'Value',DCM.B{k}(i,j)); catch DCM.B{k}(i,j) = get(B{k}(i,j),'Value'); end end end end % connection buttons (C) %-------------------------------------------------------------------------- for i = 1:n for j = 1:l x = x0 + (4 - 1)*(n + 1)*sx +(j - 1)*sx; y = y0 - (i + 4)*sy; str = sprintf('data.DCM.C(%i,%i)',i,j); str = ['data=guidata(gcbo);' str '=get(gcbo,''Value'');guidata(gcbo,data)']; C(i,j) = uicontrol(handles.SPM,... 'Units','Normalized',... 'Position',[x y sx sy],... 'Style','radiobutton',... 'Tag','tmp',... 'Callback',str); try set(C(i,j),'Value',DCM.C(i,j)); catch DCM.C(i,j) = get(C(i,j),'Value'); end end end % string labels %-------------------------------------------------------------------------- switch DCM.options.model case{'NMM','MFM'} constr = {'Excit.' 'Inhib.' 'Mixed' 'input'}; case{'DEM'} constr = {'States' ' ' ' ' ' '}; otherwise constr = {'forward' 'back' 'lateral' 'input'}; end switch DCM.options.analysis case{'IND'} constr = {'linear' 'nonlinear' '(not used)' 'input'}; case{'PHA'} constr = {'endog' '(not used)' '(not used)' '(not used)' }; otherwise end nsx = (n + 1)*sx; nsy = 2*sy; for k = 1:4 x = x0 + (k - 1)*nsx; y = y0 - 4*sy; str = constr{k}; S(k) = uicontrol(handles.SPM,... 'Units','Normalized',... 'Position',[x y nsx nsy],... 'HorizontalAlignment','left',... 'Style','text',... 'String',str,... 'Tag','tmp',... 'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end constr = DCM.xU.name; for k = 1:m x = x0 + (k - 1)*nsx; y = y0 - 6*sy - 2*(n + 1)*sy; str = ['B ' constr{k}]; S(4 + k) = uicontrol(handles.SPM,... 'Units','Normalized',... 'Position',[x y nsx nsy],... 'HorizontalAlignment','left',... 'Style','text',... 'String',str,... 'Tag','tmp',... 'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end handles.S = S; handles.A = A; handles.B = B; handles.C = C; handles.DCM = DCM; set(handles.estimate, 'Enable','on'); set(handles.initialise, 'Enable','on'); guidata(hObject,handles) % remove existing buttons and set DCM.A,.. to zero %-------------------------------------------------------------------------- function con_reset_Callback(hObject, eventdata, handles) h = get(handles.SPM,'Children'); for i = 1:length(h) if strcmp(get(h(i),'Tag'),'tmp') delete(h(i)); end end try for i = 1:length(handles.DCM.A) handles.DCM.A{i}(:) = 0; end for i = 1:length(handles.DCM.B) handles.DCM.B{i}(:) = 0; end handles.DCM.C(:) = 0; end handles = connections_Callback(hObject, eventdata, handles); guidata(hObject,handles) % --- Executes on button press in connectivity_back. %-------------------------------------------------------------------------- function connectivity_back_Callback(hObject, eventdata, handles) set(handles.con_reset, 'Enable', 'off'); set(handles.connectivity_back, 'Enable', 'off'); set(handles.Hz1, 'Enable', 'off'); set(handles.Hz2, 'Enable', 'off'); set(handles.Rft, 'Enable', 'off'); set(handles.Spatial, 'Enable', 'on'); set(handles.spatial_ok, 'Enable', 'on'); set(handles.onset, 'Enable', 'on'); set(handles.dur, 'Enable', 'on'); set(handles.Sname, 'Enable', 'on'); set(handles.Slocation, 'Enable', 'on'); set(handles.spatial_back, 'Enable', 'on'); switch handles.DCM.options.analysis case{'SSR','CSD'} set(handles.onset, 'Enable', 'off'); set(handles.dur, 'Enable', 'off'); otherwise set(handles.onset, 'Enable', 'on'); set(handles.dur, 'Enable', 'on'); end % connection buttons %-------------------------------------------------------------------------- try for i = 1:length(handles.A) for j = 1:length(handles.A{i}) for k = 1:length(handles.A{i}) set(handles.A{i}(j,k), 'Enable', 'off'); end end end for i = 1:length(handles.B) for j = 1:length(handles.B{i}) for k = 1:length(handles.B{i}) set(handles.B{i}(j,k), 'Enable', 'off'); end end end for i = 1:length(handles.C) set(handles.C(i), 'Enable', 'off'); end end %-Estimate, initialise and review %========================================================================== % --- Executes on button press in estimate. % ------------------------------------------------------------------------- function varargout = estimate_Callback(hObject, eventdata, handles, varargin) set(handles.estimate,'String','Estimating','Foregroundcolor',[1 0 0]) handles = reset_Callback(hObject, eventdata, handles); % initialise with posteriors if required % ------------------------------------------------------------------------- try Ep = handles.DCM.Ep; Str = questdlg('use previous posteriors'); if strcmp(Str,'Yes') handles.DCM.M.P = Ep; elseif strcmp(Str,'No') handles.DCM.M.P = []; elseif strcmp(Str,'Cancel') return end end % initialise with posteriors if required % ------------------------------------------------------------------------- try handles.DCM.M.pE; Str = questdlg('use previous priors'); if strcmp(Str,'No') handles.DCM.M = rmfield(handles.DCM.M,{'pE','pC'}); elseif strcmp(Str,'Cancel') return end end % invert and save %-------------------------------------------------------------------------- switch handles.DCM.options.analysis % conventional neural-mass and mean-field models %---------------------------------------------------------------------- case{'ERP'} switch handles.DCM.options.model % DEM %---------------------------------------------------------------------- case{'DEM'} handles.DCM = spm_dcm_dem(handles.DCM); otherwise handles.DCM = spm_dcm_erp(handles.DCM); end % cross-spectral density model (complex) %---------------------------------------------------------------------- case{'CSD'} handles.DCM = spm_dcm_csd(handles.DCM); % cross-spectral density model (steady-state responses) %---------------------------------------------------------------------- case{'SSR'} handles.DCM = spm_dcm_ssr(handles.DCM); % induced responses %---------------------------------------------------------------------- case{'IND'} handles.DCM = spm_dcm_ind(handles.DCM); % phase coupling %---------------------------------------------------------------------- case{'PHA'} handles.DCM = spm_dcm_phase(handles.DCM); otherwise warndlg('unknown analysis type') return end handles = ERP_Callback(hObject, eventdata, handles); set(handles.results, 'Enable','on' ) set(handles.save, 'Enable','on') set(handles.estimate, 'String','Estimated','Foregroundcolor',[0 0 0]) if get(handles.Spatial, 'Value') == 1 set(handles.Imaging,'Enable','on' ) end guidata(hObject, handles); % --- Executes on button press in results. % ------------------------------------------------------------------------- function varargout = results_Callback(hObject, eventdata, handles, varargin) Action = get(handles.results, 'String'); Action = Action{get(handles.results, 'Value')}; switch handles.DCM.options.analysis % conventional neural-mass and mean-field models %---------------------------------------------------------------------- case{'ERP'} spm_dcm_erp_results(handles.DCM, Action); % Cross-spectral density model (complex) %---------------------------------------------------------------------- case{'CSD'} spm_dcm_csd_results(handles.DCM, Action); % Cross-spectral density model (steady-state responses) %---------------------------------------------------------------------- case{'SSR'} spm_dcm_ssr_results(handles.DCM, Action); % Induced responses %---------------------------------------------------------------------- case{'IND'} spm_dcm_ind_results(handles.DCM, Action); % phase coupling %---------------------------------------------------------------------- case{'PHA'} spm_dcm_phase_results(handles.DCM, Action); otherwise warndlg('unknown analysis type') return end % --- Executes on button press in initialise. % ------------------------------------------------------------------------- function initialise_Callback(hObject, eventdata, handles) [f,p] = uigetfile('DCM*.mat','please select estimated DCM'); DCM = load(fullfile(p,f), '-mat'); handles.DCM.M.P = DCM.DCM.Ep; guidata(hObject, handles); % --- Executes on button press in Imaging. % ------------------------------------------------------------------------- function Imaging_Callback(hObject, eventdata, handles) spm_eeg_inv_imag_api(handles.DCM.xY.Dfile) % default design matrix %========================================================================== function handles = Xdefault(hObject,handles,m) % m - number of trials X = eye(m); X(:,1) = []; name = {}; for i = 1:size(X,2) name{i,1} = sprintf('effect %i',i); end handles.DCM.xU.X = X; handles.DCM.xU.name = name; set(handles.design,'String',num2str(handles.DCM.xU.X','%7.2f')); set(handles.Uname, 'String',handles.DCM.xU.name); return % --- Executes on button press in BMC. %-------------------------------------------------------------------------- function BMS_Callback(hObject, eventdata, handles) %spm_api_bmc spm_jobman('Interactive','','spm.stats.bms.bms_dcm') % --- Executes on selection change in ERP. %-------------------------------------------------------------------------- function handles = ERP_Callback(hObject, eventdata, handles) % get analysis type %-------------------------------------------------------------------------- handles = reset_Callback(hObject, eventdata, handles); switch handles.DCM.options.analysis % conventional neural-mass and mean-field models %---------------------------------------------------------------------- case{'ERP'} Action = { 'ERPs (mode)', 'ERPs (sources)', 'coupling (A)', 'coupling (B)', 'coupling (C)', 'trial-specific effects', 'Input', 'Response', 'Response (image)', 'Scalp maps', 'Dipoles'}; try set(handles.Nmodes, 'Value', handles.DCM.options.Nmodes); catch set(handles.Nmodes, 'Value', 8); end set(handles.text20, 'String', 'modes'); set(handles.model, 'Enable','on'); set(handles.Spatial, 'String',{'IMG','ECD','LFP'}); set(handles.Wavelet, 'Enable','off','String','-'); set(handles.onset, 'Enable','on'); set(handles.dur, 'Enable','on'); % Cross-spectral density model (complex) %---------------------------------------------------------------------- case{'CSD'} Action = { 'spectral data',... 'Coupling (A)',... 'Coupling (B)',... 'Coupling (C)',... 'trial-specific effects',... 'Input',... 'Transfer functions',... 'Cross-spectra (sources)',... 'Cross-spectra (channels)',... 'Coherence (sources)',... 'Coherence (channels)',... 'Covariance (sources)',... 'Covariance (channels)',... 'Dipoles'}; try set(handles.Nmodes, 'Value', handles.DCM.options.Nmodes); catch set(handles.Nmodes, 'Value', 4); end set(handles.text20, 'String', 'modes'); set(handles.model, 'Enable','on'); set(handles.Spatial,'String',{'IMG','ECD','LFP'}); set(handles.Wavelet,'Enable','on','String','Spectral density'); set(handles.onset, 'Enable','off'); set(handles.dur, 'Enable','off'); % Cross-spectral density model (steady-state responses) %---------------------------------------------------------------------- case{'SSR'} Action = { 'spectral data', 'coupling (A)', 'coupling (B)', 'coupling (C)', 'trial-specific effects', 'Input', 'Cross-spectral density', 'Dipoles'}; try set(handles.Nmodes, 'Value', handles.DCM.options.Nmodes); catch set(handles.Nmodes, 'Value', 4); end set(handles.text20, 'String', 'modes'); set(handles.model, 'Enable','on'); set(handles.Spatial, 'String',{'IMG','ECD','LFP'}); set(handles.Wavelet, 'Enable','on','String','Spectral density'); set(handles.onset, 'Enable','off'); set(handles.dur, 'Enable','off'); % induced responses %---------------------------------------------------------------------- case{'IND'} Action = { 'Frequency modes' 'Time-modes' 'Time-frequency' 'Coupling (A - Hz)' 'Coupling (B - Hz)' 'Coupling (A - modes)' 'Coupling (B - modes)' 'Input (C - Hz)' 'Input (u - ms)' 'Input (C x u)' 'Dipoles' 'Save results as img'}; try set(handles.Nmodes, 'Value', handles.DCM.options.Nmodes); catch set(handles.Nmodes, 'Value', 4); end set(handles.text20, 'String', 'modes'); set(handles.model, 'Enable','off'); if get(handles.Spatial, 'Value') > 2 set(handles.Spatial, 'Value', 2); end set(handles.Spatial, 'String',{'ECD','LFP'}); set(handles.Wavelet, 'Enable','on','String','Wavelet transform'); set(handles.Imaging, 'Enable','off' ) set(handles.onset, 'Enable','on'); set(handles.dur, 'Enable','on'); case{'PHA'} Action = { 'Sin(Data) - Region 1' 'Sin(Data) - Region 2' 'Sin(Data) - Region 3' 'Sin(Data) - Region 4' 'Coupling (As)' 'Coupling (Bs)'}; try set(handles.Nmodes, 'Value', handles.DCM.options.Nmodes); catch set(handles.Nmodes, 'Value', 1); end set(handles.text20, 'String', 'sub-trials'); set(handles.model, 'Enable','off'); if get(handles.Spatial, 'Value')>2 set(handles.Spatial, 'Value', 2); end set(handles.Spatial, 'String',{'ECD','LFP'}); set(handles.Wavelet, 'Enable','on','String','Hilbert transform'); set(handles.Imaging, 'Enable','off' ) set(handles.onset, 'Enable','off'); set(handles.dur, 'Enable','off'); otherwise warndlg('unknown analysis type') return end set(handles.results,'Value',1); set(handles.results,'String',Action); handles = reset_Callback(hObject, eventdata, handles); guidata(hObject,handles); % --- Executes on button press in Wavelet. function Wavelet_Callback(hObject, eventdata, handles) % get transform %-------------------------------------------------------------------------- handles = reset_Callback(hObject, eventdata, handles); handles.DCM = spm_dcm_erp_dipfit(handles.DCM, 1); switch handles.DCM.options.analysis case{'CSD'} % cross-spectral density (if DCM.M.U (eigen-space) exists %------------------------------------------------------------------ try handles.DCM = spm_dcm_csd_data(handles.DCM); end % and display %------------------------------------------------------------------ spm_dcm_csd_results(handles.DCM,'spectral data'); case{'SSR'} % cross-spectral density (if DCM.M.U (eigen-space) exists %------------------------------------------------------------------ try handles.DCM = spm_dcm_ssr_data(handles.DCM); end % and display %------------------------------------------------------------------ spm_dcm_ssr_results(handles.DCM,'spectral data'); case{'IND'} % wavelet tranform %------------------------------------------------------------------ handles.DCM = spm_dcm_ind_data(handles.DCM); % and display %------------------------------------------------------------------ spm_dcm_ind_results(handles.DCM,'Wavelet'); case{'PHA'} handles.DCM = spm_dcm_phase_data(handles.DCM); end guidata(hObject,handles); % --- Executes on button press in priors. function priors_Callback(hObject, eventdata, handles) handles = reset_Callback(hObject, eventdata, handles); spm_api_nmm(handles.DCM)
github
philippboehmsturm/antx-master
spm_dcm_erp_viewspatial.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/dcm_meeg/spm_dcm_erp_viewspatial.m
10,619
utf_8
3273ab19ea6a3906d4a70cf5c22b98c8
function varargout = spm_dcm_erp_viewspatial(varargin) % SPM_DCM_ERP_VIEWSPATIAL M-file for spm_dcm_erp_viewspatial.fig % SPM_DCM_ERP_VIEWSPATIAL, by itself, creates a new SPM_DCM_ERP_VIEWSPATIAL or raises the existing % singleton*. % % H = SPM_DCM_ERP_VIEWSPATIAL returns the handle to a new SPM_DCM_ERP_VIEWSPATIAL or the handle to % the existing singleton*. % % SPM_DCM_ERP_VIEWSPATIAL('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in SPM_DCM_ERP_VIEWSPATIAL.M with the given input arguments. % % SPM_DCM_ERP_VIEWSPATIAL('Property','Value',...) creates a new SPM_DCM_ERP_VIEWSPATIAL or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before spm_dcm_erp_viewspatial_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to spm_dcm_erp_viewspatial_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help spm_dcm_erp_viewspatial % Last Modified by GUIDE v2.5 12-Jul-2006 11:06:13 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @spm_dcm_erp_viewspatial_OpeningFcn, ... 'gui_OutputFcn', @spm_dcm_erp_viewspatial_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before spm_dcm_erp_viewspatial is made visible. function spm_dcm_erp_viewspatial_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to spm_dcm_erp_viewspatial (see VARARGIN) % Choose default command line output for spm_dcm_erp_viewspatial handles.output = hObject; DCM = varargin{1}; handles.DCM = DCM; handles.ms = DCM.xY.pst; handles.T = 1; M = DCM.M; load(DCM.xY.Dfile); % ----> returns SPM/EEG struct D handles.D = D; % locations for plotting CTF = load(fullfile(spm('dir'), 'EEGtemplates', D.channels.ctf)); CTF.Cpos = CTF.Cpos(:, D.channels.order(D.channels.eeg)); handles.x = min(CTF.Cpos(1,:)):0.01:max(CTF.Cpos(1,:)); handles.y = min(CTF.Cpos(2,:)):0.01:max(CTF.Cpos(2,:)); [handles.x1, handles.y1] = meshgrid(handles.x, handles.y); handles.xp = CTF.Cpos(1,:)'; handles.yp = CTF.Cpos(2,:)'; Nchannels = size(CTF.Cpos, 2); handles.Nchannels = Nchannels; handles.y_proj = spm_cat(DCM.xY.y)*DCM.M.E; handles.CLim1_yp = min(min(handles.y_proj)); handles.CLim2_yp = max(max(handles.y_proj)); handles.Nt = size(handles.y_proj, 1); % data and model fit handles.yd = NaN*ones(handles.Nt, Nchannels); handles.ym = NaN*ones(handles.Nt, Nchannels); handles.yd(:, DCM.M.dipfit.Ic) = handles.y_proj*DCM.M.E'; % data (back-projected to channel space) handles.ym(:, DCM.M.dipfit.Ic) = cat(1,DCM.H{:})*DCM.M.E'; % model fit handles.CLim1 = min(min([handles.yd handles.ym])); handles.CLim2 = max(max([handles.yd handles.ym])); % set slider's range and initial value set(handles.slider1, 'min', 1); set(handles.slider1, 'max', handles.Nt); set(handles.slider1, 'Value', 1); set(handles.slider1, 'Sliderstep', [1/(handles.Nt-1) 10/(handles.Nt-1)]); % moves slider in dt and 10*dt steps plot_images(hObject, handles); plot_modes(hObject, handles); plot_dipoles(hObject, handles); plot_components_space(hObject, handles); try plot_components_time(hObject, handles); end % Update handles structure guidata(hObject, handles); % UIWAIT makes spm_dcm_erp_viewspatial wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = spm_dcm_erp_viewspatial_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on slider movement. function slider1_Callback(hObject, eventdata, handles) % hObject handle to slider1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider handles.T = round(get(handles.slider1, 'Value')); plot_images(hObject, handles); plot_modes(hObject, handles); guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function slider1_CreateFcn(hObject, eventdata, handles) % hObject handle to slider1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end %-------------------------------------------------------------------- function plot_images(hObject, handles) T = handles.T; axes(handles.axes1); cla z = griddata(handles.xp, handles.yp, handles.yd(T,:), handles.x1, handles.y1); surface(handles.x, handles.y, z); axis off axis square shading('interp') hold on plot3(handles.xp, handles.yp, handles.yd, 'k.'); set(handles.axes1, 'CLim', [handles.CLim1 handles.CLim2]) title('data', 'FontSize', 16); axes(handles.axes2); cla z = griddata(handles.xp, handles.yp, handles.ym(T,:), handles.x1, handles.y1); surface(handles.x, handles.y, z); axis off axis square shading('interp') hold on plot3(handles.xp, handles.yp, handles.ym, 'k.'); set(handles.axes2, 'CLim', [handles.CLim1 handles.CLim2]) title('model', 'FontSize', 16); guidata(hObject, handles); drawnow %-------------------------------------------------------------------- function plot_modes(hObject, handles) % plot temporal expression of modes DCM = handles.DCM; Nt = size(DCM.xY.xy{1}, 1); Ntrials = length(DCM.H); ms_all = kron(ones(1, Ntrials), handles.ms); % data and model prediction, cond 1 axes(handles.axes3); cla plot(ms_all, handles.y_proj); hold on plot(ms_all, cat(1, DCM.H{:}), '--'); plot([ms_all(handles.T) ms_all(handles.T)], [handles.CLim1_yp handles.CLim2_yp], 'k', 'LineWidth', 3); % set(handles.axes3, 'XLim', [0 handles.ms(end)]); set(handles.axes3, 'YLim', [handles.CLim1_yp handles.CLim2_yp]); xlabel('ms'); title('Temporal expressions of modes', 'FontSize', 16); grid on %-------------------------------------------------------------------- function plot_dipoles(hObject, handles) DCM = handles.DCM; Nsources = length(DCM.M.pE.A{1}); % ECD %-------------------------------------------------------------------- try Lpos = handles.DCM.Eg.Lpos; Lmom = handles.DCM.Eg.L; Lmom = spm_cat(Lmom); % Imaging %-------------------------------------------------------------------- catch Lpos = handles.DCM.M.dipfit.Lpos; Lmom = Lpos*0; end try elc = handles.DCM.M.dipfit.elc; % transform sensor locations to MNI-space iMt = inv(DCM.M.dipfit.Mmni2polsphere); elc = iMt*[elc'; ones(1, size(elc, 1))]; elc = elc(1:3, :)'; catch elc = sparse(0,3); end axes(handles.axes5); for j = 1:Nsources % plot dipoles using small ellipsoids [x, y, z] = ellipsoid(handles.axes5,Lpos(1,j), Lpos(2,j), Lpos(3,j), 4, 4,4); surf(x, y, z, 'EdgeColor', 'none', 'FaceColor', 'g'); hold on % plot dipole moments plot3([Lpos(1, j) Lpos(1, j) + 5*Lmom(1, j)],... [Lpos(2, j) Lpos(2, j) + 5*Lmom(2, j)],... [Lpos(3, j) Lpos(3, j) + 5*Lmom(3, j)], 'b', 'LineWidth', 4); plot3(elc(:,1), elc(:,2), elc(:,3), 'r.','MarkerSize',18); end xlabel('x'); ylabel('y'); rotate3d(handles.axes5); axis equal %-------------------------------------------------------------------- function plot_components_space(hObject, handles) % plots spatial expression of each dipole DCM = handles.DCM; Nsources = length(DCM.M.pE.A{1}); lf = NaN*ones(handles.Nchannels, Nsources); lfo = NaN*ones(handles.Nchannels, Nsources); x = [0 kron([zeros(1, 8) 1], ones(1, Nsources))]; % unprojected and projected leadfield %-------------------------------------------------------------------- lfo(DCM.M.dipfit.Ic,:) = spm_erp_L(DCM.Eg,DCM.M); lf = DCM.M.E*DCM.M.E'*lfo; % use subplots in new figure h = figure; set(h, 'Name', 'Spatial expression of sources'); for j = 1:2 for i = 1:Nsources if j == 1 % projected handles.hcomponents{i} = subplot(2,Nsources, i); z = griddata(handles.xp, handles.yp, lf(:, i), handles.x1, handles.y1); title(DCM.Sname{i}, 'FontSize', 16); else % not projected handles.hcomponents{i} = subplot(2,Nsources, i+Nsources); z = griddata(handles.xp, handles.yp, lfo(:, i), handles.x1, handles.y1); end surface(handles.x, handles.y, z); axis off axis square shading('interp') % set(handles.axes1, 'CLim', [handles.CLim1 handles.CLim2]) end end drawnow function plot_components_time(hObject, handles) DCM = handles.DCM; Lmom = sqrt(sum(spm_cat(DCM.Eg.L)).^2); Nsources = length(DCM.M.pE.A{1}); h = figure; set(h, 'Name', 'Effective source amplitudes'); % multiply with dipole amplitudes for i = 1:Nsources handles.hcomponents_time{2*(i-1)+1} = subplot(Nsources, 2, 2*(i-1)+1); plot(handles.ms, Lmom(i)*DCM.K{1}(:, i)); title([handles.DCM.Sname{i} ', ERP 1'], 'FontSize', 16); try handles.hcomponents_time{2*(i-1)+2} = subplot(Nsources, 2, 2*(i-1)+2); plot(handles.ms, Lmom(i)*DCM.K{2}(:, i)); title([handles.DCM.Sname{i} ', ERP 2'], 'FontSize', 16); end end
github
philippboehmsturm/antx-master
spm_api_nmm.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/dcm_meeg/spm_api_nmm.m
16,055
utf_8
4144c4d41da26bb528f4d79e58415ee9
function varargout = spm_api_nmm(varargin) % SPM_API_NMM M-file for spm_api_nmm.fig % SPM_API_NMM, by itself, creates a new SPM_API_NMM or raises the existing % singleton*. % % H = SPM_API_NMM returns the handle to a new SPM_API_NMM or the handle to % the existing singleton*. % % SPM_API_NMM('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in SPM_API_NMM.M with the given input arguments. % % SPM_API_NMM('Property','Value',...) creates a new SPM_API_NMM or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before spm_api_nmm_OpeningFunction gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to spm_api_nmm_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help spm_api_nmm % Last Modified by GUIDE v2.5 17-Oct-2008 16:14:27 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @spm_api_nmm_OpeningFcn, ... 'gui_OutputFcn', @spm_api_nmm_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before spm_api_nmm is made visible. %-------------------------------------------------------------------------- function spm_api_nmm_OpeningFcn(hObject, eventdata, handles, varargin) set(gcf,'name','Neural mass modelling: review of priors'); try handles.DCM = varargin{1}; unpack_Callback(hObject, eventdata, handles); end % Choose default command line output for spm_api_nmm handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes spm_api_nmm wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = spm_api_nmm_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; %========================================================================== % --- Executes on button press in load. %-------------------------------------------------------------------------- function load_Callback(hObject, eventdata, handles) [f,p] = uigetfile('*.mat','please select DCM file'); cd(p) name = fullfile(p,f); DCM = load(name,'-mat'); DCM = DCM.DCM; DCM.name = name; handles.DCM = DCM; set(handles.name,'String',f); % display priors %-------------------------------------------------------------------------- unpack_Callback(hObject, eventdata, handles); guidata(hObject,handles); % --- Executes on button press in save. %-------------------------------------------------------------------------- function save_Callback(hObject, eventdata, handles) try [p,file] = fileparts(handles.DCM.name); catch try [p,file] = fileparts(handles.DCM.xY.Dfile); file = ['DCM_' file]; catch file = ['DCM' date]; end end [file,fpath] = uiputfile(['DCM*.mat'],'DCM file to save',file); if fpath handles.DCM.name = fullfile(fpath,file); set(handles.name,'String',file); DCM = handles.DCM; save(DCM.name,'DCM') cd(fpath) end % assign in base %-------------------------------------------------------------------------- assignin('base','DCM',handles.DCM) guidata(hObject,handles); % --- Executes on button press in kernels. %-------------------------------------------------------------------------- function kernels_Callback(hObject, eventdata, handles) clear spm_erp_L spm_gen_erp DCM = handles.DCM; pst = str2num(get(handles.pst,'String')); Hz = str2num(get(handles.Hz, 'String')); % initialise states %-------------------------------------------------------------------------- M = DCM.M; model = DCM.options.model; [x f] = spm_dcm_x_neural(M.pE,model); M.x = x; M.f = f; M.m = size(M.pE.C,2); M.g = {}; M.ons = 32*ones(M.m,1); % Volterra Kernels %========================================================================== % augment and bi-linearise %-------------------------------------------------------------------------- [M0,M1,L1,L2] = spm_bireduce(M,M.pE); % compute kernels (over 64 ms) %-------------------------------------------------------------------------- M.ns = 128; U.dt = pst/M.ns/1000; t = [1:M.ns]*U.dt*1000; [K0,K1] = spm_kernels(M0,M1,L1,L2,M.ns,U.dt); axes(handles.kernel) plot(t,K1(:,:,1)) set(gca,'XLim',[min(t) max(t)]) ylabel('1st-order Volterra kernel') xlabel('time (ms)') % transfer function (source space) %-------------------------------------------------------------------------- for i = 1:size(K1,2) g(:,i) = fft(K1(:,i)); g(:,i) = abs(g(:,i).*conj(g(:,i))); end i = [1:M.ns/2]; g = g(i + 1,:); w = i/(M.ns*U.dt); axes(handles.transfer) plot(w,g) set(gca,'XLim',[1 Hz]) xlabel('frequency time (Hz)') ylabel('spectral density') % prediction (source space) %-------------------------------------------------------------------------- x = spm_gen_erp(M.pE,M,U); x = x{1}; axes(handles.erp) plot(t,x) set(gca,'XLim',[min(t) max(t)]) xlabel('peristimulus time (ms)') ylabel('voltage and conductance') % fft (source space) %-------------------------------------------------------------------------- clear g for i = 1:size(x,2) g(:,i) = fft(x(:,i)); g(:,i) = abs(g(:,i).*conj(g(:,i))); end i = [1:M.ns/2]; g = g(i + 1,:); w = i/(M.ns*U.dt); axes(handles.fft) plot(w,g) set(gca,'XLim',[1 Hz]) xlabel('frequency time (Hz)') ylabel('spectral density') % unpack priors and display %========================================================================== function unpack_Callback(hObject, eventdata, handles); % clear previous objects %-------------------------------------------------------------------------- h = get(gcf,'Children'); for i = 1:length(h) if strcmp(get(h(i),'Tag'),'tmp') delete(h(i)); end end % Type of model (neuronal) %-------------------------------------------------------------------------- % 'ERP' - (linear second order NMM slow) % 'SEP' - (linear second order NMM fast) % 'CMC' - (linear second order NMM Canonical microcircuit) % 'LFP' - (linear second order NMM self-inhibition) % 'NMM' - (nonlinear second order NMM first-order moments) % 'MFM' - (nonlinear second order NMM second-order moments) try model = handles.DCM.options.model; catch model = get(handles.model,'String'); model = model{get(handles.model,'Value')}; DCM.options.model = model; end switch model case{'ERP'}, set(handles.model,'Value',1); case{'SEP'}, set(handles.model,'Value',2); case{'CMC'}, set(handles.model,'Value',3); case{'LFP'}, set(handles.model,'Value',4); case{'NMM'}, set(handles.model,'Value',5); case{'MFM'}, set(handles.model,'Value',6); otherwise end % get priors %-------------------------------------------------------------------------- try handles.DCM.M.pE; catch handles = reset_Callback(hObject, eventdata, handles); end pE = handles.DCM.M.pE; pC = handles.DCM.M.pC; try pC = spm_unvec(diag(pC),pE); end % display connection switches later %-------------------------------------------------------------------------- try, pE = rmfield(pE,'B');, end try, pE = rmfield(pE,'SA');, end try, pE = rmfield(pE,'GE');, end try, pE = rmfield(pE,'GI');, end % do not display spatial and spectral priors %-------------------------------------------------------------------------- try, pE = rmfield(pE,{'Lpos','L','J'});, end try, pE = rmfield(pE,{'a','b','c','d'});, end % display fields %-------------------------------------------------------------------------- color = {[1 1 1],get(handles.name,'BackgroundColor')}; x0 = 1/8; y0 = 1 - 1/8; sx = 1/24; sy = 1/48; dx = 1/256 + sx; dy = 1/256 + sy; F = fieldnames(pE); for f = 1:length(F) P = getfield(pE,F{f}); if iscell(P) % cell %------------------------------------------------------------------ for k = 1:length(P) for i = 1:size(P{k},1); for j = 1:size(P{k},2) x = x0 + j*dx + (size(P{k},2) + 1)*dx*(k - 1); y = y0 - (i - 1)*dy; str = sprintf('handles.DCM.M.pE.%s{%i}(%i,%i)',F{f},k,i,j); str = ['handles=guidata(gcbo);' str '=str2num(get(gcbo,''String''));guidata(gcbo,handles);']; h = uicontrol(gcf,... 'Units','Normalized',... 'Position',[x y sx sy],... 'Style','edit',... 'String',sprintf('%-4.2f',P{k}(i,j)),... 'enable','on',... 'Tag','tmp',... 'BackgroundColor',color{1 + ~eval(sprintf('pC.%s{%i}(%i,%i)',F{f},k,i,j))},... 'Callback',str); end end end elseif isvector(P) % vector %------------------------------------------------------------------ for i = 1:length(P); x = x0 + i*dx; y = y0; str = sprintf('handles.DCM.M.pE.%s(%i)',F{f},i); str = ['handles=guidata(gcbo);' str '=str2num(get(gcbo,''String''));guidata(gcbo,handles);']; uicontrol(gcf,... 'Units','Normalized',... 'Position',[x y sx sy],... 'Style','edit',... 'String',sprintf('%-4.2f',full(P(i))),... 'enable','on',... 'Tag','tmp',... 'BackgroundColor',color{1 + ~eval(sprintf('pC.%s(%i)',F{f},i))},... 'Callback',str); end else % matrix %------------------------------------------------------------------ for i = 1:size(P,1); for j = 1:size(P,2) x = x0 + j*dx; y = y0 - (i - 1)*dy; str = sprintf('handles.DCM.M.pE.%s(%i,%i)',F{f},i,j); str = ['handles=guidata(gcbo);' str '=str2num(get(gcbo,''String''));guidata(gcbo,handles);']; uicontrol(gcf,... 'Units','Normalized',... 'Position',[x y sx sy],... 'Style','edit',... 'String',sprintf('%-4.2f',full(P(i,j))),... 'enable','on',... 'Tag','tmp',... 'BackgroundColor',color{1 + ~eval(sprintf('pC.%s(%i,%i)',F{f},i,j))},... 'Callback',str); end end end % label %---------------------------------------------------------------------- uicontrol(gcf,... 'Units','Normalized',... 'Position',[x0 - dx y0 2*sx sy],... 'Style','text',... 'String',sprintf('pE.%s',F{f}),... 'ForegroundColor',[1 0 0],... 'HorizontalAlignment','left',... 'FontSize',12,... 'Tag','tmp'); y0 = y - dy - dy/2; end % connectivity matrices %========================================================================== pE = handles.DCM.M.pE; try, SA = pE.SA; catch SA = []; end try, GE = pE.GE; catch GE = []; end try, GI = pE.GI; catch GI = []; end % SA matrix %-------------------------------------------------------------------------- x0 = 0.7; y0 = 0.3; for i = 1:size(SA,1); for j = 1:size(SA,2) x = x0 + j*dx; y = y0 - (i - 1)*dy; str = sprintf('handles.DCM.M.pE.SA(%i,%i)',i,j); str = ['handles=guidata(gcbo);' str '=str2num(get(gcbo,''String''));guidata(gcbo,handles);']; uicontrol(gcf,... 'Units','Normalized',... 'Position',[x y sx sy],... 'Style','edit',... 'String',sprintf('%-4.2f',SA(i,j)),... 'enable','on',... 'Tag','tmp',... 'Callback',str); end end % GE matrix %-------------------------------------------------------------------------- x0 = 0.7; y0 = 0.2; for i = 1:size(GE,1); for j = 1:size(GE,2) x = x0 + j*dx; y = y0 - (i - 1)*dy; str = sprintf('handles.DCM.M.pE.GE(%i,%i)',i,j); str = ['handles=guidata(gcbo);' str '=str2num(get(gcbo,''String''));guidata(gcbo,handles);']; uicontrol(gcf,... 'Units','Normalized',... 'Position',[x y sx sy],... 'Style','edit',... 'String',sprintf('%-4.2f',GE(i,j)),... 'enable','on',... 'Tag','tmp',... 'Callback',str); end end % GI matrix %-------------------------------------------------------------------------- x0 = 0.7; y0 = 0.1; for i = 1:size(GI,1); for j = 1:size(GI,2) x = x0 + j*dx; y = y0 - (i - 1)*dy; str = sprintf('handles.DCM.M.pE.GI(%i,%i)',i,j); str = ['handles=guidata(gcbo);' str '=str2num(get(gcbo,''String''));guidata(gcbo,handles);']; uicontrol(gcf,... 'Units','Normalized',... 'Position',[x y sx sy],... 'Style','edit',... 'String',sprintf('%-4.2f',GI(i,j)),... 'enable','on',... 'Tag','tmp',... 'Callback',str); end end % onset time %========================================================================== try ons = handles.DCM.M.ons; catch ons = 32; handles.DCM.M.ons = ons; end str = 'handles.DCM.M.ons'; str = ['handles=guidata(gcbo);' str '=str2num(get(gcbo,''String''));guidata(gcbo,handles);']; uicontrol(gcf,... 'Units','Normalized',... 'Position',[0.848 0.341 0.071 0.022],... 'Style','edit',... 'String',sprintf('%-4.0f',ons),... 'enable','on',... 'Tag','tmp',... 'Callback',str); guidata(hObject,handles); % --- Executes on button press in reset. %-------------------------------------------------------------------------- function handles = reset_Callback(hObject, eventdata, handles) try DCM = handles.DCM; catch load_Callback(hObject, eventdata, handles) return end model = DCM.options.model; [pE,pC] = spm_dcm_neural_priors(DCM.A,DCM.B,DCM.C,model); handles.DCM.M.pE = pE; handles.DCM.M.pC = pC; guidata(hObject,handles); unpack_Callback(hObject, eventdata, handles); % --- Executes on button press in conditional. %-------------------------------------------------------------------------- function conditional_Callback(hObject, eventdata, handles) % conditional moments on parameters %-------------------------------------------------------------------------- try handles.DCM.M.pE = handles.DCM.Ep; unpack_Callback(hObject, eventdata, handles); catch warndlg('please invert and load a DCM to obtain conditional estimates') end % --- Executes on selection change in model. function model_Callback(hObject, eventdata, handles) % model type %-------------------------------------------------------------------------- model = get(handles.model, 'String'); model = model{get(handles.model, 'Value')}; handles.DCM.options.model = model; try reset_Callback(hObject, eventdata, handles); catch load_Callback(hObject, eventdata, handles) return end
github
philippboehmsturm/antx-master
spm_erp_L.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/dcm_meeg/spm_erp_L.m
3,838
utf_8
d272a989f0e0a3b8dd3f98a941016faa
function [L] = spm_erp_L(P,M) % returns [projected] lead field L as a function of position and moments % FORMAT [L] = spm_erp_L(P,M) % P - model parameters % M - model specification % L - lead field %__________________________________________________________________________ % % The lead field (L) is constructed using the specific parameters in P and, % where necessary information in the dipole structure M.dipfit. For ECD % models P.Lpos and P.L encode the position and moments of the ECD. The % field M.dipfit.type: % % 'ECD', 'LFP' or 'IMG' % % determines whether the model is ECD or not. For imaging reconstructions % the paramters P.L are a (m x n) matrix of coefficients that scale the % contrition of n sources to m = M.dipfit.Nm modes encoded in M.dipfit.G. % % For LFP models (the default) P.L simply encodes the electrode gain for % each source contributing a LFP. % % see; Kiebel et al. (2006) NeuroImage %__________________________________________________________________________ % Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging % Karl Friston % $Id: spm_erp_L.m 4336 2011-05-31 16:49:34Z rosalyn $ % Create a persient variable that rembers the last locations %-------------------------------------------------------------------------- persistent LastLpos LastL % type of spatial model and modality %========================================================================== try, type = M.dipfit.type; catch, type = 'LFP'; end switch type % parameterised lead field - ECD %---------------------------------------------------------------------- case{'ECD'} % number of sources - n %------------------------------------------------------------------ n = size(P.L,2); % re-compute lead field only if any dipoles changed %---------------------------------------------------------- try Id = find(any(LastLpos ~= P.Lpos)); catch Id = 1:n; end % record new spatial parameters %---------------------------------------------------------- LastLpos = P.Lpos; for i = Id if any(P.Lpos(:,i)>=200) Lf = zeros(M.dipfit.Nc, 3); else Lf = ft_compute_leadfield(transform_points(M.dipfit.datareg.fromMNI, P.Lpos(:,i)'), M.dipfit.sens, M.dipfit.vol); end LastL(:,:,i) = Lf; end G = spm_cond_units(LastL); for i = 1:n L(:,i) = G(:,:,i)*P.L(:,i); end % Imaging solution {specified in M.dipfit.G} %---------------------------------------------------------------------- case{'IMG'} % number of sources - n %------------------------------------------------------------------ n = size(P.L,2); % re-compute lead field only if any coeficients have changed %------------------------------------------------------------------ try Id = find(any(LastLpos ~= P.L)); catch Id = 1:n; end for i = Id LastL(:,i) = M.dipfit.G{i}*P.L(:,i); end % record new spatial parameters %------------------------------------------------------------------ LastLpos = P.L; L = LastL; % LFP electrode gain %---------------------------------------------------------------------- case{'LFP'} m = length(P.L); try n = M.dipfit.Ns; catch n = m; end L = sparse(1:m,1:m,P.L,m,n); otherwise warndlg('unknown spatial model') end % ------------------------------------------------------------------------- function new = transform_points(M, old) old(:,4) = 1; new = old * M'; new = new(:,1:3);
github
philippboehmsturm/antx-master
spm_eeg_megheadloc.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/MEEGtools/spm_eeg_megheadloc.m
15,281
utf_8
9bee3f89fa1da54831f841f36e7315b5
function D = spm_eeg_megheadloc(S) % Use head localization of CTF to select/reject trials based on head % position and (optionally) correct the sensor coordinates to correspond to % the selected trials. The function can be used on a single dataset as well % as several datasets together. Most of the functionality requires the % original CTF header (read with CTF toolbox) to be present (set % S.saveorigheader = 1 at conversion). % % FORMAT D = spm_eeg_megheadloc(S) % % S - struct (optional) % (optional) fields of S: % S.D - meeg object, filename or a list of filenames of SPM EEG files % S.rejectbetween - reject trials based on their difference from other % trials (1 - yes, 0- no). % S.threshold - distance threshold for rejection (in meters), default % 0.01 (1 cm) % S.rejectwithin - reject trials based on excessive movement within trial % S.trialthresh - distance threshold for rejection (in meters), default % 0.005 (0.5 cm) % S.losttrack - how to handle segments where the system lost track of % one of the coils. % 'reject' - reject the trial % 'preserve' - try to preserve the trials. The exact % behavior depends on 'rejectbetween' and 'rejectwithin' % settings % % S.correctsens - calculate corrected sensor representation and put it in % the dataset. % S.trialind - only look at a subset of trials specified. Can be used % to work trial-by trial with a single file. % S.save - save the header files (otherwise just return the headers). % S.toplot - plot feedback information (default 1, yes). % % Output: % D - MEEG data struct or cell array of MEEG objects with the % rejected trials set to bad and sensors corrected (if % requested). % % Disclaimer: this code is provided as an example and is not guaranteed to work % with data on which it was not tested. If it does not work for you, feel % free to improve it and contribute your improvements to the MEEGtools toolbox % in SPM (http://www.fil.ion.ucl.ac.uk/spm) % % _______________________________________________________________________ % Copyright (C) 2008 Institute of Neurology, UCL % Vladimir Litvak, Robert Oostenveld % $Id: spm_eeg_megheadloc.m 4358 2011-06-14 15:57:15Z vladimir $ [Finter,Fgraph,CmdLine] = spm('FnUIsetup','MEG head locations',0); if nargin == 0 S = []; end try D = S.D; catch D = spm_select([1 inf], '\.mat$', 'Select M/EEG mat file(s)'); S.D = D; end iswork = 1; if ~isa(D, 'meeg') try for i = 1:size(D, 1) F{i} = spm_eeg_load(deblank(D(i, :))); if ~ft_senstype(chanlabels(F{i}), 'ctf') warning('Head localization is not supported for this data') iswork =0; end end D = F; catch error('Trouble reading files'); end else D = {D}; end if ~iswork return; end if ~isfield(S, 'rejectbetween') S.rejectbetween = spm_input('Reject for intertrial difference?','+1','yes|no',[1 0], 1); end if ~isfield(S, 'threshold') && S.rejectbetween S.threshold = spm_input('Threshold (cm):', '+1', 'r', '1', 1)/100; end if ~isfield(S, 'rejectwithin') S.rejectwithin = spm_input('Reject for intrial differences?','+1','yes|no',[1 0], 1); end if ~isfield(S, 'trialthresh') && S.rejectwithin S.trialthresh = spm_input('Threshold (cm):', '+1', 'r', '0.5', 1)/100; end if ~isfield(S, 'correctsens') S.correctsens = spm_input('Correct sensors?', '+1','yes|no',[1 0], 1); end if ~isfield(S, 'losttrack') S.losttrack = spm_input('How to handle losses of tracking?','+1','reject|preserve', strvcat('reject', 'preserve')); end if ~isfield(S, 'save') S.save = spm_input('Save file(s)?', '+1','yes|no',[1 0], 0); end if ~isfield(S, 'toplot'), S.toplot = 1; end %read HLC-channels %HLC0011 HLC0012 HLC0013 x, y, z coordinates of nasion-coil in m. %HLC0021 HLC0022 HLC0023 x, y, z coordinates of lpa-coil in m. %HLC0031 HLC0032 HLC0033 x, y, z coordinates of rpa-coil in m. hlc_chan_label = {'HLC0011' 'HLC0012' 'HLC0013'... 'HLC0021' 'HLC0022' 'HLC0023'... 'HLC0031' 'HLC0032' 'HLC0033'}; Ntrls=0; dat = []; trlind = []; fileind=[]; if S.toplot pntfig = spm_figure('GetWin','Graphics'); figure(pntfig); clf colors = {'b', 'g' , 'c', 'm', 'y', 'k'}; end for f=1:numel(D) hlc_chan_ind = spm_match_str(chanlabels(D{f}), hlc_chan_label); Ntrl = D{f}.ntrials; Ntrls=Ntrls+Ntrl; if length(hlc_chan_ind) == 9 if isfield(S, 'trialind') && ~isempty(S.trialind) trlsel = S.trialind; else trlsel = 1:Ntrl; end for k = trlsel tmpdat = D{f}(hlc_chan_ind, :, k); header_fid = 0.01*D{f}.origheader.hc.dewar'; cont_fid = permute(reshape(tmpdat', [], 3, 3), [1 3 2]); dist_dev = [ (squeeze(sqrt(sum((cont_fid(:, 1, :) - cont_fid(:, 2, :)).^2, 3))) - norm(header_fid(1,:) - header_fid(2,:)))';... (squeeze(sqrt(sum((cont_fid(:, 2, :) - cont_fid(:, 3, :)).^2, 3))) - norm(header_fid(2,:) - header_fid(3,:)))';... (squeeze(sqrt(sum((cont_fid(:, 3, :) - cont_fid(:, 1, :)).^2, 3))) - norm(header_fid(3,:) - header_fid(1,:)))']; tracking_lost_ind = find(any(abs(dist_dev) > 0.01)); if ~isempty(tracking_lost_ind) warning(['Tracking loss detected in file ' D{f}.fname ' trial ' num2str(k)]); tracking_lost = 1; if isequal(S.losttrack, 'preserve') tmpdat(:, tracking_lost_ind) = []; if ~isempty(tmpdat) tracking_lost = 0; end end else tracking_lost = 0; end utmpdat = unique(tmpdat', 'rows')'; if S.rejectwithin && ~tracking_lost if size(utmpdat, 2) == 1 dN = 0; dL = 0; dR = 0; else try pdist([0;1]); pdistworks = 1; catch pdistworks = 0; end if pdistworks dN=max(pdist(utmpdat(1:3, :)')); dL=max(pdist(utmpdat(4:6, :)')); dR=max(pdist(utmpdat(7:9, :)')); else dN=max(slowpdist(utmpdat(1:3, :)')); dL=max(slowpdist(utmpdat(4:6, :)')); dR=max(slowpdist(utmpdat(7:9, :)')); end end end if ~tracking_lost && (~S.rejectwithin || (max([dN dL dR])<S.trialthresh)) dat = [dat median(tmpdat, 2)]; trlind = [trlind k]; fileind= [fileind f]; elseif (tracking_lost && isequal(S.losttrack, 'preserve')) dat = [dat nan(9, 1)]; trlind = [trlind k]; fileind= [fileind f]; else D{f} = reject(D{f}, k, 1); end end if S.toplot subplot('position',[0.05 0.65 0.4 0.3]); pltdat = squeeze(mean(reshape(tmpdat', [], 3, 3), 1))'; pltdat = [pltdat; pltdat(1, :)]; if ~reject(D{f}, k) h = plot3(pltdat(:, 1), pltdat(:, 2), pltdat(:, 3), ... [colors{mod(f, length(colors))+1}]); else h = plot3(pltdat(:, 1), pltdat(:, 2), pltdat(:, 3), 'r'); end hold on if isfield(D{f}, 'origheader') pltdat = header_fid; end end else warning(['The 9 headloc channels were not found in dataset ' D{f}.fname '. Using a single location']); % This allows for handling also files without continuous head % localization in a consistent way. The single location is % replicated according to the number of trials in the file if isfield(D{f}, 'origheader') utmpdat = 0.01*D{f}.origheader.hc.dewar(:); else error('Original header is required for this functionality.'); end if S.toplot subplot('position',[0.05 0.65 0.4 0.3]); pltdat = 0.01*D{f}.origheader.hc.dewar'; end dat = [dat repmat(utmpdat, 1, Ntrl)]; trlind = [trlind 1:Ntrl]; fileind= [fileind f*ones(1, Ntrl)]; end if S.toplot h = plot3(pltdat(:, 1), pltdat(:, 2), pltdat(:, 3), ... ['o' colors{mod(f, length(colors))+1}], 'MarkerSize', 10); hold on end end if S.toplot axis auto grid on axis equal axis vis3d end disp(['Accepted ' num2str(length(trlind)) '/' num2str(Ntrls) ' trials.']); captured = []; if length(trlind)>1 && ~all(all(isnan(dat))) % If there was loss of tracking for just some of the trials, reject % them and continue with the rest. nanind = find(any(isnan(dat))); if ~isempty(nanind) if S.rejectbetween for i = length(nanind) D{fileind(nanind(i))} = reject(D{fileind(nanind(i))}, trlind(nanind(i)), 1); end end dat(:, nanind) = []; trlind(nanind) = []; fileind(nanind)= []; end if S.rejectbetween %% % Here the idea is to put a 'sphere' or 'hypercylinder' in the space of trial location whose % radius is 'threshold' and which captures as many trials as possible. For this we first look for the point around which the % density of trials is maximal. We put the cylinder there and then try to % optimize its position further to include more trials if possible. % The density is compute in PCA space of at most 3 dimensions [coeff, score, eigv] = princomp(dat'); %% boundL=min(score); boundU=max(score); dim = max(find(abs(boundU-boundL)>S.threshold)); dim=min(dim,3); %% if ~isempty(dim) disp(['First ' num2str(dim) ' PCs explain ' num2str(100*sum(eigv(1:dim))/sum(eigv)) '% of the variance.']); %% hcubesize=[]; for d=1:dim gridres=(boundU(d)-boundL(d))./(2.^nextpow2((boundU(d)-boundL(d))/S.threshold)); edges{d} = boundL(d):gridres:boundU(d); edges{d}(1)=edges{d}(1)-eps; edges{d}(end)=edges{d}(end)+eps; hcubesize=[hcubesize (length(edges{d})-1)]; end hcube=squeeze(zeros([1 hcubesize])); trlpos=zeros(1, size(score,1)); for i=1:size(score,1) coord=[]; for d=1:dim coord=[coord find(histc(score(i,d), edges{d}))]; end if dim>1 coord=num2cell(coord); trlpos(i)=sub2ind(hcubesize, coord{:}); else trlpos(i)=coord; end hcube(trlpos(i))=hcube(trlpos(i))+1; end %% [junk maxind]=max(hcube(:)); %% center = mean(dat(:, find(trlpos==maxind)), 2); else disp('All trials within threshold borders'); center = mean(dat, 2); end %% % Here the cylinder location is further optimized options = optimset('Display', 'iter', 'TolFun', 1, 'TolX', S.threshold/10); center = fminsearch(@(center) trials_captured(center, dat, S.threshold), center, options); %% % This generates the final list of trials captured in the cylinder [center, captured]= trials_captured(center, dat, S.threshold); %% if S.toplot figure(pntfig); subplot('position',[0.55 0.65 0.4 0.3]); plot3(score(captured,1), score(captured,2), score(captured,3),'r.'); hold on plot3(score(~captured,1), score(~captured,2), score(~captured,3),'.'); axis equal end %% ufileind=unique(fileind(captured)); %% for f = 1:numel(D) origreject = reject(D{f}); D{f} = reject(D{f}, [], 1); if ismember(f, ufileind) && any(captured & (fileind == f)) D{f} = reject(D{f}, trlind(captured & (fileind == f)), 0); if any(origreject) D{f} = reject(D{f}, find(origreject), 1); end end end end end if isempty(captured) captured = ones(1, size(dat, 2)); end %% % This generates the corrected grad structure if S.correctsens && ((length(hlc_chan_ind) == 9) || numel(D)>1) && ~isempty(trlind) && ~all(all(isnan(dat))) newcoils=mean(dat(:, captured), 2); nas = newcoils(1:3); lpa = newcoils(4:6); rpa = newcoils(7:9); %compute transformation matrix from dewar to head coordinates M = spm_eeg_inv_headcoordinates(nas, lpa, rpa); dewar = 0.01*D{1}.origheader.hc.dewar; M1 = spm_eeg_inv_headcoordinates(dewar(:,1)', dewar(:,2)', dewar(:,3)'); grad = sensors(D{1}, 'MEG'); newgrad = ft_transform_sens(M*inv(M1), grad); if S.toplot figure(pntfig); subplot('position',[0.05 0.05 0.9 0.5]); cfg = []; cfg.style = '3d'; cfg.rotate = 0; cfg.grad = grad; lay = ft_prepare_layout(cfg); cfg.grad = newgrad; newlay = ft_prepare_layout(cfg); plot3(newlay.pos(:,1), newlay.pos(:,2), newlay.pos(:,3), '.r', 'MarkerSize', 5); hold on plot3(lay.pos(:,1), lay.pos(:,2), lay.pos(:,3), '.k'); axis equal off end newfid = ft_transform_headshape(M*inv(M1), fiducials(D{1})); for f = 1:numel(D) D{f} = sensors(D{f}, 'MEG', newgrad); D{f} = fiducials(D{f}, newfid); end end for f = 1:numel(D) D{f} = history(D{f}, 'spm_eeg_megheadloc', S); if S.save save(D{f}); end end if numel(D) == 1 D = D{1}; end end function [obj, captured] = trials_captured(center, dat, threshold) nsmp = size(dat,2); dist = max(sqrt([1 1 1 0 0 0 0 0 0; 0 0 0 1 1 1 0 0 0; 0 0 0 0 0 0 1 1 1]*(dat - repmat(center(:), 1, nsmp)).^2)); obj = -sum(dist<threshold); if nargout>1 captured=dist<threshold; end end function Y = slowpdist(X) % Thanks to Guillaume N = size(X,1); Y = zeros(1,N*(N-1)/2); k = 1; for i=1:N-1 Y(k:(k+N-i-1)) = sqrt(sum((repmat(X(i,:),N-i,1) - X((i+1):N,:)).^2,2)); k = k + N - i; end end
github
philippboehmsturm/antx-master
spm_eeg_fix_ctf_headloc.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/MEEGtools/spm_eeg_fix_ctf_headloc.m
18,735
utf_8
59b50ccd4a5352cdbd25ef92faa7c2b4
function D = spm_eeg_fix_ctf_headloc(S) % Fix head localization data in a continuous CTF dataset with continuous % head localization. The tracking has to be valid at least some of the time % % The functionality requires the original CTF header (read with CTF toolbox) % to be present (set S.saveorigheader = 1 at conversion). % % FORMAT D = spm_eeg_fix_ctf_headloc(S) % % S - struct (optional) % (optional) fields of S: % S.D - meeg object or filename % % % Output: % D - MEEG data struct or cell array of MEEG objects with the % rejected trials set to bad and sensors corrected (if % requested). % % Disclaimer: this code is provided as an example and is not guaranteed to work % with data on which it was not tested. If it does not work for you, feel % free to improve it and contribute your improvements to the MEEGtools toolbox % in SPM (http://www.fil.ion.ucl.ac.uk/spm) % % _______________________________________________________________________ % Copyright (C) 2008 Institute of Neurology, UCL % Vladimir Litvak, Robert Oostenveld % $Id: spm_eeg_fix_ctf_headloc.m 4408 2011-07-26 12:13:43Z vladimir $ [Finter,Fgraph,CmdLine] = spm('FnUIsetup','Fix CTF head locations',0); if nargin == 0 S = []; end try D = S.D; catch D = spm_select(1, '\.mat$', 'Select M/EEG mat file'); S.D = D; end D = spm_eeg_load(S.D); %read HLC-channels %HLC0011 HLC0012 HLC0013 x, y, z coordinates of nasion-coil in m. %HLC0021 HLC0022 HLC0023 x, y, z coordinates of lpa-coil in m. %HLC0031 HLC0032 HLC0033 x, y, z coordinates of rpa-coil in m. hlc_chan_label = {'HLC0011' 'HLC0012' 'HLC0013'... 'HLC0021' 'HLC0022' 'HLC0023'... 'HLC0031' 'HLC0032' 'HLC0033'}; if ~all(ismember(hlc_chan_label, D.chanlabels)) error('Head localization is not supported for this data') end if ~isfield(D, 'origheader') error('Original CTF header needs to be present') end if ~isfield(S, 'quickfix') %read HLC-channels %HLC0011 HLC0012 HLC0013 x, y, z coordinates of nasion-coil in m. %HLC0021 HLC0022 HLC0023 x, y, z coordinates of lpa-coil in m. %HLC0031 HLC0032 HLC0033 x, y, z coordinates of rpa-coil in m. hlc_chan_label = {'HLC0011' 'HLC0012' 'HLC0013'... 'HLC0021' 'HLC0022' 'HLC0023'... 'HLC0031' 'HLC0032' 'HLC0033'}; tmpdat = D(D.indchannel(hlc_chan_label), :); tmpind = find(~any(tmpdat==0)); cont_fid = permute(reshape(tmpdat(:, tmpind)', [], 3, 3), [1 3 2]); if isfield(S, 'valid_fid') valid_fid = S.valid_fid; dist_dev = [ (squeeze(sqrt(sum((cont_fid(:, 1, :) - cont_fid(:, 2, :)).^2, 3))) - norm(valid_fid(1,:) - valid_fid(2,:)))';... (squeeze(sqrt(sum((cont_fid(:, 2, :) - cont_fid(:, 3, :)).^2, 3))) - norm(valid_fid(2,:) - valid_fid(3,:)))';... (squeeze(sqrt(sum((cont_fid(:, 3, :) - cont_fid(:, 1, :)).^2, 3))) - norm(valid_fid(3,:) - valid_fid(1,:)))']; W = abs(dist_dev) < 0.01; else %% dist = [ squeeze(sqrt(sum((cont_fid(:, 1, :) - cont_fid(:, 2, :)).^2, 3)))';... squeeze(sqrt(sum((cont_fid(:, 2, :) - cont_fid(:, 3, :)).^2, 3)))';... squeeze(sqrt(sum((cont_fid(:, 3, :) - cont_fid(:, 1, :)).^2, 3)))' ]; %% [y, W]= spm_robust_average(dist, 2, 3); %% W = W>0.9; end % Theoretically one should use 'or' here and not 'and' but I found it % leaves too much rubbish in nasOK = W(1, :) & W(3, :); leOK = W(1, :) & W(2, :); reOK = W(2, :) & W(3, :); OK = [nasOK;nasOK;nasOK; leOK; leOK;leOK; reOK;reOK;reOK]; if min(sum(OK, 2))<2 error('Not enough valid head localization data'); end %% for i = 1:size(tmpdat, 1) if any(~OK(i, :)) || (length(tmpind)<size(tmpdat, 2)) tmpdat(i, :) = interp1(D.time(tmpind(OK(i, :))), tmpdat(i, tmpind(OK(i, :))), D.time, 'linear', 'extrap'); end end D(D.indchannel(hlc_chan_label), :) = tmpdat; dewarfid = 100*reshape(median(tmpdat(:, tmpind), 2), 3, 3); %% D.origheader.hc.dewar = dewarfid; spm_figure('GetWin','Graphics');clf; subplot(2, 1, 1); plot(D.time, tmpdat); subplot(2, 1, 2); else spm_figure('GetWin','Graphics');clf; dewarfid = D.origheader.hc.dewar; end dewargrad = ctf2grad(D.origheader, 1); M = spm_eeg_inv_headcoordinates(dewarfid(:, 1), dewarfid(:, 2), dewarfid(:, 3)); grad = ft_convert_units(ft_transform_sens(M, dewargrad), 'mm'); D = sensors(D, 'MEG', grad); fid = D.fiducials; fid.pnt = []; fid.fid.pnt = dewarfid'; fid.unit = 'cm'; fid = ft_convert_units(ft_transform_headshape(M, fid), 'mm'); D = fiducials(D, fid); save(D); plot3(grad.pnt(:, 1), grad.pnt(:, 2), grad.pnt(:, 3), 'k.'); axis equal off hold on plot3(fid.fid.pnt(:, 1), fid.fid.pnt(:, 2), fid.fid.pnt(:, 3), 'r.', 'MarkerSize', 15); function [grad] = ctf2grad(hdr, dewar) % CTF2GRAD converts a CTF header to a gradiometer structure that can be % understood by FieldTrip and Robert Oostenveld's low-level forward and % inverse routines. The fieldtrip/fileio read_header function can use three % different implementations of the low-level code for CTF data. Each of % these implementations is dealt with here. % % See also READ_HEADER, FIF2GRAD, BTI2GRAD, YOKOGAWA2GRAD % undocumented option: it will return the gradiometer information in dewar % coordinates if second argument is present and non-zero % 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: spm_eeg_fix_ctf_headloc.m 4408 2011-07-26 12:13:43Z vladimir $ % My preferred ordering in the grad structure is: % 1st 151 coils are bottom coils of MEG channels % 2nd 151 are the top coils of MEG channels % following coils belong to reference channels if nargin<2 || isempty(dewar) dewar = 0; end if isfield(hdr, 'orig') hdr = hdr.orig; % use the original CTF header, not the FieldTrip header end % start with empty gradiometer grad = []; grad.pnt = []; grad.ori = []; grad.tra = []; % meg channels are 5, refmag 0, refgrad 1, ADCs 18 % UPPT001 is 11 % UTRG001 is 11 % SCLK01 is 17 % STIM is 11 % SCLK01 is 17 % EEG057 is 9 % ADC06 is 18 % ADC07 is 18 % ADC16 is 18 % V0 is 15 if isfield(hdr, 'res4') && isfield(hdr.res4, 'senres') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the header was read using the CTF p-files, i.e. readCTFds %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% sensType = [hdr.res4.senres.sensorTypeIndex]; selMEG = find(sensType==5); selREF = find(sensType==0 | sensType==1); selMEG = selMEG(:)'; selREF = selREF(:)'; numMEG = length(selMEG); numREF = length(selREF); % determine the number of channels and coils coilcount = 0; coilcount = coilcount + sum([hdr.res4.senres(selREF).numCoils]); coilcount = coilcount + sum([hdr.res4.senres(selMEG).numCoils]); chancount = numMEG + numREF; % preallocate the memory grad.pnt = zeros(coilcount, 3); % this will hold the position of each coil grad.ori = zeros(coilcount, 3); % this will hold the orientation of each coil grad.tra = zeros(chancount, coilcount); % this describes how each coil contributes to each channel % combine the bottom and top coil of each MEG channel for i=1:numMEG n = selMEG(i); % get coil positions and orientations of this channel (max. 8) if dewar pos = hdr.res4.senres(n).pos0'; ori = hdr.res4.senres(n).ori0'; else pos = hdr.res4.senres(n).pos'; ori = hdr.res4.senres(n).ori'; end if hdr.res4.senres(n).numCoils~=2 error('unexpected number of coils in MEG channel'); end % add the coils of this channel to the gradiometer array grad.pnt(i ,:) = pos(1,:); grad.pnt(i+numMEG,:) = pos(2,:); grad.ori(i ,:) = ori(1,:) .* -sign(hdr.res4.senres(n).properGain); grad.ori(i+numMEG,:) = ori(2,:) .* -sign(hdr.res4.senres(n).properGain); grad.tra(i,i ) = 1; grad.tra(i,i+numMEG) = 1; end % the MEG channels always have 2 coils, the reference channels vary in the number of coils chancount = 1*numMEG; coilcount = 2*numMEG; % combine the coils of each reference channel for i=1:numREF n = selREF(i); % get coil positions and orientations of this channel (max. 8) if dewar pos = hdr.res4.senres(n).pos0'; ori = hdr.res4.senres(n).ori0'; else pos = hdr.res4.senres(n).pos'; ori = hdr.res4.senres(n).ori'; end % determine the number of coils for this channel numcoils = hdr.res4.senres(n).numCoils; % add the coils of this channel to the gradiometer array chancount = chancount+1; for j=1:numcoils coilcount = coilcount+1; grad.pnt(coilcount, :) = pos(j,:); grad.ori(coilcount, :) = ori(j,:) .* -sign(hdr.res4.senres(n).properGain); grad.tra(chancount, coilcount) = 1; end end label = cellstr(hdr.res4.chanNames); for i=1:numel(label) % remove the site-specific numbers from each channel name, e.g. 'MZC01-1706' becomes 'MZC01' label{i} = strtok(label{i}, '-'); end grad.label = label([selMEG selREF]); grad.unit = 'cm'; % convert the balancing coefficients into a montage that can be used with the ft_apply_montage function if isfield(hdr.BalanceCoefs, 'G1BR') meglabel = label(hdr.BalanceCoefs.G1BR.MEGlist); reflabel = label(hdr.BalanceCoefs.G1BR.Refindex); nmeg = length(meglabel); nref = length(reflabel); montage.labelorg = cat(1, meglabel, reflabel); montage.labelnew = cat(1, meglabel, reflabel); montage.tra = [eye(nmeg, nmeg), -hdr.BalanceCoefs.G1BR.alphaMEG'; zeros(nref, nmeg), eye(nref, nref)]; grad.balance.G1BR = montage; end if isfield(hdr.BalanceCoefs, 'G2BR') meglabel = label(hdr.BalanceCoefs.G2BR.MEGlist); reflabel = label(hdr.BalanceCoefs.G2BR.Refindex); nmeg = length(meglabel); nref = length(reflabel); montage.labelorg = cat(1, meglabel, reflabel); montage.labelnew = cat(1, meglabel, reflabel); montage.tra = [eye(nmeg, nmeg), -hdr.BalanceCoefs.G2BR.alphaMEG'; zeros(nref, nmeg), eye(nref, nref)]; grad.balance.G2BR = montage; end if isfield(hdr.BalanceCoefs, 'G3BR') meglabel = label(hdr.BalanceCoefs.G3BR.MEGlist); reflabel = label(hdr.BalanceCoefs.G3BR.Refindex); nmeg = length(meglabel); nref = length(reflabel); montage.labelorg = cat(1, meglabel, reflabel); montage.labelnew = cat(1, meglabel, reflabel); montage.tra = [eye(nmeg, nmeg), -hdr.BalanceCoefs.G3BR.alphaMEG'; zeros(nref, nmeg), eye(nref, nref)]; grad.balance.G3BR = montage; end if isfield(hdr.BalanceCoefs, 'G3AR') meglabel = label(hdr.BalanceCoefs.G3AR.MEGlist); reflabel = label(hdr.BalanceCoefs.G3AR.Refindex); nmeg = length(meglabel); nref = length(reflabel); montage.labelorg = cat(1, meglabel, reflabel); montage.labelnew = cat(1, meglabel, reflabel); montage.tra = [eye(nmeg, nmeg), -hdr.BalanceCoefs.G3AR.alphaMEG'; zeros(nref, nmeg), eye(nref, nref)]; grad.balance.G3AR = montage; end if all([hdr.res4.senres(selMEG).grad_order_no]==0) grad.balance.current = 'none'; elseif all([hdr.res4.senres(selMEG).grad_order_no]==1) grad.balance.current = 'G1BR'; elseif all([hdr.res4.senres(selMEG).grad_order_no]==2) grad.balance.current = 'G2BR'; elseif all([hdr.res4.senres(selMEG).grad_order_no]==3) grad.balance.current = 'G3BR'; elseif all([hdr.res4.senres(selMEG).grad_order_no]==13) grad.balance.current = 'G3AR'; else warning('cannot determine balancing of CTF gradiometers'); grad = rmfield(grad, 'balance'); end % sofar the gradiometer definition was the ideal, non-balenced one if isfield(grad, 'balance') && ~strcmp(grad.balance.current, 'none') % apply the current balancing parameters to the gradiometer definition grad = ft_apply_montage(grad, getfield(grad.balance, grad.balance.current)); end elseif isfield(hdr, 'sensType') && isfield(hdr, 'Chan') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the header was read using the open-source matlab code that originates from CTF and that was modified by the FCDC %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% selMEG = find(hdr.sensType==5); selREF = find(hdr.sensType==0 | hdr.sensType==1); selMEG = selMEG(:)'; selREF = selREF(:)'; numMEG = length(selMEG); numREF = length(selREF); % combine the bottom and top coil of each MEG channel for i=1:numMEG n = selMEG(i); % get coil positions and orientations of this channel (max. 8) if dewar pos = cell2mat({hdr.Chan(n).coil.pos}'); ori = cell2mat({hdr.Chan(n).coil.ori}'); else pos = cell2mat({hdr.Chan(n).coilHC.pos}'); ori = cell2mat({hdr.Chan(n).coilHC.ori}'); end % determine the number of coils for this channel numcoils = sum(sum(pos.^2, 2)~=0); if numcoils~=2 error('unexpected number of coils in MEG channel'); end % add the coils of this channel to the gradiometer array grad.pnt(i ,:) = pos(1,:); grad.pnt(i+numMEG,:) = pos(2,:); grad.ori(i ,:) = ori(1,:) .* -sign(hdr.gainV(n)); grad.ori(i+numMEG,:) = ori(2,:) .* -sign(hdr.gainV(n)); grad.tra(i,i ) = 1; grad.tra(i,i+numMEG) = 1; end % combine the coils of each reference channel for i=1:numREF n = selREF(i); % get coil positions and orientations of this channel (max. 8) if dewar pos = cell2mat({hdr.Chan(n).coil.pos}'); ori = cell2mat({hdr.Chan(n).coil.ori}'); else pos = cell2mat({hdr.Chan(n).coilHC.pos}'); ori = cell2mat({hdr.Chan(n).coilHC.ori}'); end % determine the number of coils for this channel numcoils = sum(sum(pos.^2, 2)~=0); % add the coils of this channel to the gradiometer array for j=1:numcoils grad.pnt(numMEG+i, :) = pos(j,:); grad.ori(numMEG+i, :) = ori(j,:) .* -sign(hdr.gainV(n)); grad.tra(numMEG+i, 2*numMEG+i) = 1; end end grad.label = hdr.label([selMEG selREF]); grad.unit = 'cm'; elseif isfield(hdr, 'sensor') && isfield(hdr.sensor, 'info') %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % the header was read using the CTF importer from the NIH and Daren Weber %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if dewar % this does not work for Daren Webers implementation error('cannot return the gradiometer definition in dewar coordinates'); end % only work on the MEG channels if isfield(hdr.sensor.index, 'meg') sel = hdr.sensor.index.meg; else sel = hdr.sensor.index.meg_sens; end for i=1:length(sel) pnt = hdr.sensor.info(sel(i)).location'; ori = hdr.sensor.info(sel(i)).orientation'; numcoils(i) = size(pnt,1); if size(ori,1)==1 && size(pnt,1)==1 % one coil position with one orientation: magnetometer ori = ori; elseif size(ori,1)==1 && size(pnt,1)==2 % two coil positions with one orientation: first order gradiometer % assume that the orientation of the upper coil is opposite to the lower coil ori = [ori; -ori]; else error('do not know how to deal with higher order gradiometer hardware') end % add this channels coil positions and orientations grad.pnt = [grad.pnt; pnt]; grad.ori = [grad.ori; ori]; grad.label{i} = hdr.sensor.info(sel(i)).label; % determine the contribution of each coil to each channel's output signal if size(pnt,1)==1 % one coil, assume that the orientation is correct, i.e. the weight is +1 grad.tra(i,end+1) = 1; elseif size(pnt,1)==2 % two coils, assume that the orientation for each coil is correct, % i.e. the weights are +1 and +1 grad.tra(i,end+1) = 1; grad.tra(i,end+1) = 1; else error('do not know how to deal with higher order gradiometer hardware') end end % prefer to have the labels in a column vector grad.label = grad.label(:); % reorder the coils, such that the bottom coils are at the first N % locations and the top coils at the last N positions. This makes it % easier to use a selection of the coils for topographic plotting if all(numcoils==2) bot = 1:2:sum(numcoils); top = 2:2:sum(numcoils); grad.pnt = grad.pnt([bot top], :); grad.ori = grad.ori([bot top], :); grad.tra = grad.tra(:, [bot top]); end else error('unknown header to contruct gradiometer definition'); end
github
philippboehmsturm/antx-master
spm_eeg_read_bsa.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/MEEGtools/spm_eeg_read_bsa.m
2,723
utf_8
cdc73e063e7cce45ce7704211f74f278
function sconfounds = spm_eeg_read_bsa(bsa) % This function reads a definition of spatial confounds from a BESA % *.bsa file and returns an sconfounds struct with the following fields % .label - labels of channels % .coeff - matrix of coefficients (channels x components) % .bad - logical vector - channels marked as bad. % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Vladimir Litvak sconfounds = []; sconfounds.coeff = []; bsain=fopen(bsa, 'r'); for i=1:3 fgetl(bsain); end i = 1; while ~feof(bsain) line=fgetl(bsain); startind= findstr(line, 'CVecOrig|')+9; endind= findstr(line, 'CVecChanLabels')-1; coeffstr=line(startind:endind); coeffs=sscanf(strrep(coeffstr, '|', ' '), '%f'); coeffs=coeffs(2:end); startind= endind+15; endind= findstr(line, 'CVec|')-1; bsalabel=deblank(tokenize(line(startind:endind), '|')); sconfounds.label = bsalabel; sconfounds.coeff = [sconfounds.coeff coeffs(:)]; i = i+1; end sconfounds.label = sconfounds.label(:); sconfounds.bad = zeros(size(sconfounds.label)); sconfounds.bad(strmatch('*', sconfounds.label)) = 1; badind = find(sconfounds.bad); for i = 1:length(badind) sconfounds.label{badind(i)} = sconfounds.label{badind(i)}(2:end); end fclose(bsain); function [tok] = tokenize(str, sep, rep) % TOKENIZE cuts a string into pieces, returning a cell array % % Use as % t = tokenize(str, sep) % t = tokenize(str, sep, rep) % where str is a string and sep is the separator at which you want % to cut it into pieces. % % Using the optional boolean flag rep you can specify whether repeated % seperator characters should be squeezed together (e.g. multiple % spaces between two words). The default is rep=1, i.e. repeated % seperators are treated as one. % Copyright (C) 2003-2006, Robert Oostenveld % % $Log: tokenize.m,v $ % Revision 1.5 2006/05/10 07:15:22 roboos % allow for squeezing multiple separators into one % % Revision 1.4 2006/01/30 14:56:41 roboos % fixed another stupid bug in previous cvs commit % % Revision 1.3 2006/01/30 14:55:44 roboos % fixed stupid bug in previous cvs commit % % Revision 1.2 2006/01/30 13:38:18 roboos % replaced dependency on strtok by more simple code % changed from dos to unix % % Revision 1.1 2005/05/23 13:47:51 roboos % old implementation, new addition to CVS for fieldtrip release % tok = {}; f = find(str==sep); f = [0, f, length(str)+1]; for i=1:(length(f)-1) tok{i} = str((f(i)+1):(f(i+1)-1)); end if nargin<3 || rep % remove empty cells, which occur if the separator is repeated (e.g. multiple spaces) tok(find(cellfun('isempty', tok)))=[]; end
github
philippboehmsturm/antx-master
spm_eeg_var_measures.m
.m
antx-master/freiburgLight/matlab/spm8/toolbox/MEEGtools/spm_eeg_var_measures.m
8,911
utf_8
ef5d9fc2cf700622f75d4c6fa1c8c0a7
function spm_eeg_var_measures % Function for computing Fourier coherence using Fieldtrip and VAR based directed measures % using SPM's spectral toolbox, developed by Will Penny. % % Disclaimer: this code is provided as an example and is not guaranteed to work % with data on which it was not tested. If it does not work for you, feel % free to improve it and contribute your improvements to the MEEGtools toolbox % in SPM (http://www.fil.ion.ucl.ac.uk/spm) % % _______________________________________________________________________ % Copyright (C) 2008 Institute of Neurology, UCL % Vladimir Litvak % $Id: spm_eeg_var_measures.m 4304 2011-04-12 15:24:23Z vladimir $ [Finter,Fgraph] = spm('FnUIsetup','MEEGtoools VAR measures', 0); if ~isdeployed addpath(fullfile(spm('Dir'),'toolbox','spectral')); addpath(fullfile(spm('Dir'),'toolbox','mixture')); end D = spm_eeg_load; chan = spm_input('What channels?','+1','LFP|EEG|GUI'); if strcmp('GUI', chan) [selection, ok]= listdlg('ListString', D.chanlabels, 'SelectionMode', 'multiple' ,'Name', 'Select channels' , 'ListSize', [400 300]); if ~ok return; end else selection = strmatch(chan, D.chantype); end if length(selection)>1 chan = D.chanlabels(selection); else error('Not enough channels'); end if strcmp(D.type, 'continuous') trldur = spm_input('Input trial length in sec)', '+1', 'r', '2', 1); cfg = []; cfg.dataset = fullfile(D.path, D.fname); cfg.channel= chan; cfg.trl = 1:round(trldur*D.fsample):D.nsamples; cfg.trl = [cfg.trl(1:(end-1))' cfg.trl(2:end)'-1 zeros(length(cfg.trl)-1, 1)]; data = ft_preprocessing(cfg); elseif D.ntrials < 3 || (D.nsamples/D.fsample) < 1 error('Expecting continuous data or epoched files with multiple trials at least 1 sec long'); else % ============ Select the data and convert to Fieldtrip struct clb = D.condlist; if numel(clb) > 1 [selection, ok]= listdlg('ListString', clb, 'SelectionMode', 'multiple' ,'Name', 'Select conditions' , 'ListSize', [400 300]); if ~ok return; end else selection = 1; end ind = D.pickconditions(clb(selection)); if isempty(ind) error('No valid trials found'); end data = D.ftraw(0); data.trial = data.trial(ind); data.time = data.time(ind); end %% data.fsample = round(data.fsample); cfg=[]; cfg.channel = chan; cfg.resamplefs = 250; cfg.detrend = 'yes'; data = ft_resampledata(cfg, data); %% cfg =[]; cfg.channel = chan; cfg.keeptrials = 'yes'; data= ft_timelockanalysis(cfg, data); Ntrials=size(data.trial,1); Ntime=length(data.time); %% cfg = []; cfg.output ='powandcsd'; cfg.keeptrials = 'yes'; cfg.keeptapers='no'; cfg.taper = 'dpss'; cfg.method = 'mtmfft'; cfg.foilim = [0 100]; % Frequency range cfg.tapsmofrq = 1; % Frequency resolution % inp = ft_freqanalysis(cfg, data); cfg1 = []; cfg1.method = 'coh'; coh = ft_connectivityanalysis(cfg1, inp); %% % Defines how trials are shifted for shift-predictors shift=[2:Ntrials 1]; % Compute the shift predictor for coherence scoh=coh; scoh.cohspctrm=zeros(size(scoh.cohspctrm)); for c=1:length(data.label) sdata=data; sdata.trial(:,c,:)=data.trial(shift,c,:); cfg.channelcmb = {data.label{c}, 'all'}; inp = ft_freqanalysis(cfg, sdata); sscoh = ft_connectivityanalysis(cfg1, inp); for i=1:size(sscoh.labelcmb, 1) ind=[intersect(strmatch(sscoh.labelcmb(i,1),scoh.labelcmb(:,1),'exact'), ... strmatch(sscoh.labelcmb(i,2),scoh.labelcmb(:,2),'exact'))... intersect(strmatch(sscoh.labelcmb(i,1),scoh.labelcmb(:,2),'exact'), ... strmatch(sscoh.labelcmb(i,2),scoh.labelcmb(:,1),'exact'))]; scoh.cohspctrm(ind, :)=sscoh.cohspctrm(i, :); end end % Plot power and coherence figure('Name', 'Fourier power and coherence'); for i=1:1:length(data.label) for j=1:1:length(data.label) subplot(length(data.label),length(data.label), sub2ind([length(data.label) length(data.label)], i, j)); if (i~=j) ind=[intersect(strmatch(data.label{i},coh.labelcmb(:,1),'exact'), ... strmatch(data.label{j},coh.labelcmb(:,2),'exact'))... intersect(strmatch(data.label{i},coh.labelcmb(:,2),'exact'), ... strmatch(data.label{j},coh.labelcmb(:,1),'exact'))]; plot(coh.freq, squeeze(coh.cohspctrm(ind,:)), 'b'); hold on plot(coh.freq, squeeze(scoh.cohspctrm(ind,:)), 'r'); ylim([0 1]); xlim([0 100]); title([data.label{i} '->' data.label{j}]); else plot(inp.freq, log(squeeze(mean(inp.powspctrm(:, i, :),1))), 'b'); xlim([0 100]); title(data.label{i}); end end end %% This is the code for determining optimal model order if spm_input('Check model order?','+1','yes|no',[1 0]); F=[]; testdata=squeeze(data.trial(1,:,:))'; max_p=15; % Maximal order to check for p=1:max_p, mar=spm_mar(testdata,p); F(p)=mar.fm; disp(sprintf('Model order p=%d, Evidence = %1.2f',p,F(p))); end Fgraph = spm_figure('GetWin','Graphics'); figure(Fgraph); clf plot([1:max_p],F); title('all regions'); xlabel('Model order,p'); ylabel('Log Evidence'); end %% % Compute the MAR model ns=1/mean(diff(data.time)); % Sample rate p= spm_input('Input model order', '+1', 'r', '', 1); % Order of MAR model freqs=[1:100]; % Frequencies to evaluate spectral quantities at dircoh=[]; sdircoh=[]; % Here the specific directional measure can be selected measure= spm_input('Select VAR measure?','+1','pdc|pve|dtf|C'); for tr=1:Ntrials ctrial=prestd(squeeze(data.trial(tr,:,:))); mar = spm_mar(ctrial,p); mar = spm_mar_spectra(mar,freqs,ns); dircoh(tr, :, :, :)=squeeze(getfield(mar, measure)); strial=prestd(squeeze(data.trial(shift(tr),:,:))); % Compute the shift predictors for each channel separately for c=1:length(data.label) combtrial=ctrial; combtrial(:, c)=strial(:, c); mar = spm_mar (combtrial ,p); mar = spm_mar_spectra (mar,freqs,ns); sdircoh(c, tr, :, :, :)=squeeze(getfield(mar, measure)); end disp(sprintf('Trial %d out of %d',tr,Ntrials)); end %% Put the results back in FieldTrip data structures dummy=[]; % The data dummy.freq=freqs; dummy.dimord='rpt_chan_freq'; dummy.trial=[]; dummy.label={}; sdummy=dummy; % The shift predictor for i=1:length(data.label) for j=1:length(data.label) if(i~=j) dummy.trial=cat(2, dummy.trial, permute(shiftdim((dircoh(:, :, j, i)), -1), [2 1 3])); sdummy.trial=cat(2, sdummy.trial, permute(shiftdim(squeeze(sdircoh(j,:, :, j, i)), -1), [2 1 3])); dummy.label=[dummy.label; {[data.label{i} '->' data.label{j}]}]; sdummy.label=[sdummy.label; {[data.label{i} '->' data.label{j}]}]; end end end %% Run nonparametric comparison between the data and the shift predictor Ntrials1=size(dummy.trial,1); Ntrials2=size(sdummy.trial,1); cfg=[]; cfg.frequency = [1 100]; cfg.method = 'montecarlo'; cfg.statistic = 'indepsamplesT'; cfg.tail = 1; cfg.alpha = 0.05; cfg.numrandomization = 1000; cfg.correctm = spm_input('Choose MC correction', 1, 'm', 'no|max|cluster|bonferoni|holms|fdr'); cfg.clusteralpha = 0.05; cfg.clusterstatistic = 'maxsum'; cfg.clustertail=1; design = zeros(1,Ntrials1+Ntrials2); design(1,1:Ntrials1) = 1; design(1,(Ntrials1+1):end)=2; cfg.design = design; % design matrix cfg.ivar = 1; % number or list with indices, independent variable(s) cfg.neighbours=[]; for c=1:length(dummy.label) cfg.neighbours{c}.label = dummy.label{c}; cfg.neighbours{c}.neighblabel ={}; end cfg.parameter='trial'; %% stats= ft_freqstatistics(cfg, dummy, sdummy); %% Plot the results of the MAR analysis mdircoh=squeeze(mean(dummy.trial,1)); smdircoh=squeeze(mean(sdummy.trial,1)); figure('Name', ['VAR-' upper(measure)]); for i=1:1:length(data.label) for j=1:1:length(data.label) if (i~=j) subplot(length(data.label),length(data.label), sub2ind([length(data.label) length(data.label)], i, j)); maskind=spm_match_str(dummy.label, [data.label{i} '->' data.label{j}]); plot(freqs, squeeze(mdircoh(maskind,:))); sigind=find(squeeze(stats.mask(maskind,:))); hold on plot(freqs(sigind), squeeze(mdircoh(maskind, sigind)), '*'); plot(freqs, squeeze(smdircoh(maskind,:)), 'r'); ylim([0 max(max(max(mdircoh)), max(max(smdircoh)))]); xlim([0 100]); title([data.label{i} '->' data.label{j}]); end end end %% function X=prestd(X) if size(X, 2)>size(X,1) X=X'; end X=X-repmat(mean(X), size(X,1),1); X=X./repmat(std(X), size(X,1),1);
github
philippboehmsturm/antx-master
coor2D.m
.m
antx-master/freiburgLight/matlab/spm8/@meeg/coor2D.m
4,007
utf_8
f94070275bb14e35788e110abf929115
function [res, plotind] = coor2D(this, ind, val, mindist) % returns x and y coordinates of channels in 2D plane % FORMAT coor2D(this) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Vladimir Litvak, Laurence Hunt % $Id: coor2D.m 4372 2011-06-21 21:26:46Z vladimir $ megind = strmatch('MEG', chantype(this)); eegind = strmatch('EEG', chantype(this), 'exact'); otherind = setdiff(1:nchannels(this), [megind; eegind]); if nargin==1 || isempty(ind) if nargin<3 || (size(val, 2)<nchannels(this)) if ~isempty(megind) ind = megind; elseif ~isempty(eegind) ind = eegind; else ind = 1:nchannels(this); end else ind = 1:nchannels(this); end elseif ischar(ind) switch upper(ind) case 'MEG' ind = megind; case 'EEG' ind = eegind; otherwise ind = otherind; end end if nargin < 3 || isempty(val) if ~isempty(intersect(ind, megind)) if ~any(cellfun('isempty', {this.channels(megind).X_plot2D})) meg_xy = [this.channels(megind).X_plot2D; this.channels(megind).Y_plot2D]; elseif all(cellfun('isempty', {this.channels(megind).X_plot2D})) meg_xy = grid(length(megind)); else error('Either all or none of MEG channels should have 2D coordinates defined.'); end end if ~isempty(intersect(ind, eegind)) if ~any(cellfun('isempty', {this.channels(eegind).X_plot2D})) eeg_xy = [this.channels(eegind).X_plot2D; this.channels(eegind).Y_plot2D]; elseif all(cellfun('isempty', {this.channels(eegind).X_plot2D})) eeg_xy = grid(length(eegind)); else error('Either all or none of EEG channels should have 2D coordinates defined.'); end end if ~isempty(intersect(ind, otherind)) other_xy = grid(length(otherind)); end xy = zeros(2, length(ind)); plotind = zeros(1, length(ind)); for i = 1:length(ind) [found, loc] = ismember(ind(i), megind); if found xy(:, i) = meg_xy(:, loc); plotind(i) = 1; else [found, loc] = ismember(ind(i), eegind); if found xy(:, i) = eeg_xy(:, loc); plotind(i) = 2; else [found, loc] = ismember(ind(i), otherind); if found xy(:, i) = other_xy(:, loc); plotind(i) = 3; end end end end if nargin > 3 && ~isempty(mindist) xy = shiftxy(xy,mindist); end res = xy; else this = getset(this, 'channels', 'X_plot2D', ind, val(1, :)); this = getset(this, 'channels', 'Y_plot2D', ind, val(2, :)); res = this; end function xy = grid(n) ncol = ceil(sqrt(n)); x = 0:(1/(ncol+1)):1; x = 0.9*x+0.05; x = x(2:(end-1)); y = fliplr(x); [X, Y] = meshgrid(x, y); xy = [X(1:n); Y(1:n)]; function xy = shiftxy(xy,mindist) x = xy(1,:); y = xy(2,:); l=1; i=1; %filler mindist = mindist/0.999; % limits the number of loops while (~isempty(i) && l<50) xdiff = repmat(x,length(x),1) - repmat(x',1,length(x)); ydiff = repmat(y,length(y),1) - repmat(y',1,length(y)); xydist= sqrt(xdiff.^2 + ydiff.^2); %euclidean distance between all sensor pairs [i,j] = find(xydist<mindist*0.999); rm=(i<=j); i(rm)=[]; j(rm)=[]; %only look at i>j for m = 1:length(i); if (xydist(i(m),j(m)) == 0) diffvec = [mindist./sqrt(2) mindist./sqrt(2)]; else xydiff = [xdiff(i(m),j(m)) ydiff(i(m),j(m))]; diffvec = xydiff.*mindist./xydist(i(m),j(m)) - xydiff; end x(i(m)) = x(i(m)) - diffvec(1)/2; y(i(m)) = y(i(m)) - diffvec(2)/2; x(j(m)) = x(j(m)) + diffvec(1)/2; y(j(m)) = y(j(m)) + diffvec(2)/2; end l = l+1; end xy = [x; y];
github
philippboehmsturm/antx-master
cache.m
.m
antx-master/freiburgLight/matlab/spm8/@meeg/cache.m
754
utf_8
327310c88f9e84a225af302977c46fe6
function res = cache(this, stuff) % Method for retrieving/putting stuff from/into the temporary cache % FORMAT res = cache(obj, name) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: cache.m 1373 2008-04-11 14:24:03Z spm $ if ischar(stuff) % assume this is a retrieval res = getcache(this, stuff); else % assume this is a put name = inputname(2); res = setcache(this, name, stuff); end function res = getcache(this, stuff) if isfield(this.cache, stuff) eval(['res = this.cache.' stuff ';']); else res = []; end function this = setcache(this, name, stuff) eval(['this.cache(1).' name ' = stuff;']);
github
philippboehmsturm/antx-master
path.m
.m
antx-master/freiburgLight/matlab/spm8/@meeg/path.m
558
utf_8
7149045fd0a2ac178f0e2dcaf166b5e0
function res = path(this, name) % Method for getting/setting path % FORMAT res = path(this, name) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: path.m 1373 2008-04-11 14:24:03Z spm $ switch nargin case 1 res = getpath(this); case 2 res = setpath(this, name); otherwise end function res = getpath(this) try res = this.path; catch res = ''; end function this = setpath(this, name) this.path = name;
github
philippboehmsturm/antx-master
fname.m
.m
antx-master/freiburgLight/matlab/spm8/@meeg/fname.m
538
utf_8
00404808a43026efada0ed0cb853d259
function res = fname(this, name) % Method for getting/setting file name % FORMAT res = fname(this, name) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: fname.m 1373 2008-04-11 14:24:03Z spm $ switch nargin case 1 res = getfname(this); case 2 res = setfname(this, name); otherwise end function res = getfname(this) res = this.fname; function this = setfname(this, name) this.fname = name;
github
philippboehmsturm/antx-master
fnamedat.m
.m
antx-master/freiburgLight/matlab/spm8/@meeg/fnamedat.m
589
utf_8
39857f5d9ecf819f3bc1581bde7009cf
function res = fnamedat(this, name) % Method for getting/setting file name of data file % FORMAT res = fnamedat(this, name) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: fnamedat.m 1373 2008-04-11 14:24:03Z spm $ switch nargin case 1 res = getfnamedat(this); case 2 res = setfnamedat(this, name); otherwise end function res = getfnamedat(this) res = this.data.fnamedat; function this = setfnamedat(this, name) this.data.fnamedat = name;
github
philippboehmsturm/antx-master
ftraw.m
.m
antx-master/freiburgLight/matlab/spm8/@meeg/ftraw.m
1,526
utf_8
02c913aa11fd6acae96a98a5268b2789
function raw = ftraw(this, memmap) % Method for converting meeg object to Fieldtrip raw struct % FORMAT raw = ftraw(this, memmap) % memmap - 1 (default) memory map the data with file_array % 0 load the data into memory % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Vladimir Litvak % $Id: ftraw.m 1742 2008-05-28 11:58:04Z vladimir $ if nargin < 2 memmap = 1; end nchans = nchannels(this); ntime = nsamples(this); ntrl = ntrials(this); raw = []; raw.fsample = fsample(this); raw.label = chanlabels(this)'; wsize=wordsize(this.data.datatype); for i=1:ntrl if memmap offset = (i-1)*nchans*ntime*wsize; trialdim = [nchans ntime]; raw.trial{i} = file_array(fullfile(this.path, this.data.fnamedat),trialdim,this.data.datatype,offset,1,0,'ro'); else raw.trial{i} = this.data.y(:, :, i); end end raw.time = repmat({time(this)}, 1, ntrl); function s = wordsize(datatype) datatype = strtok(datatype, '-'); switch datatype case 'int8' s = 1; case 'int16' s = 2; case 'int32' s = 4; case 'uint8' s = 1; case 'uint16' s = 2; case 'uint32' s = 4; case 'float' s = 4; case 'double' s = 8; case 'float32' s = 4; case 'float64' s = 8; otherwise error('unrecognized datatype'); % FIXME, add support for le and be versions end
github
philippboehmsturm/antx-master
subsasgn.m
.m
antx-master/freiburgLight/matlab/spm8/@file_array/subsasgn.m
4,602
utf_8
0b4cd116c71239ee913cdf7c826c838a
function obj = subsasgn(obj,subs,dat) % Overloaded subsasgn function for file_array objects. % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: subsasgn.m 4136 2010-12-09 22:22:28Z guillaume $ if isempty(subs) return; end; if ~strcmp(subs(1).type,'()'), if strcmp(subs(1).type,'.'), %error('Attempt to reference field of non-structure array.'); if numel(struct(obj))~=1, error('Can only change the fields of simple file_array objects.'); end; switch(subs(1).subs) case 'fname', obj = asgn(obj,@fname, subs(2:end),dat); %fname(obj,dat); case 'dtype', obj = asgn(obj,@dtype, subs(2:end),dat); %dtype(obj,dat); case 'offset', obj = asgn(obj,@offset, subs(2:end),dat); %offset(obj,dat); case 'dim', obj = asgn(obj,@dim, subs(2:end),dat); %obj = dim(obj,dat); case 'scl_slope', obj = asgn(obj,@scl_slope, subs(2:end),dat); %scl_slope(obj,dat); case 'scl_inter', obj = asgn(obj,@scl_inter, subs(2:end),dat); %scl_inter(obj,dat); case 'permission', obj = asgn(obj,@permission,subs(2:end),dat); %permission(obj,dat); otherwise, error(['Reference to non-existent field "' subs.subs '".']); end; return; end; if strcmp(subs(1).type,'{}'), error('Cell contents reference from a non-cell array object.'); end; end; if numel(subs)~=1, error('Expression too complicated');end; dm = size(obj); sobj = struct(obj); if length(subs.subs) < length(dm), l = length(subs.subs); dm = [dm(1:(l-1)) prod(dm(l:end))]; if numel(sobj) ~= 1, error('Can only reshape simple file_array objects.'); end; if numel(sobj.scl_slope)>1 || numel(sobj.scl_inter)>1, error('Can not reshape file_array objects with multiple slopes and intercepts.'); end; end; dm = [dm ones(1,16)]; di = ones(1,16); args = {}; for i=1:length(subs.subs), if ischar(subs.subs{i}), if ~strcmp(subs.subs{i},':'), error('This shouldn''t happen....'); end; args{i} = int32(1:dm(i)); else args{i} = int32(subs.subs{i}); end; di(i) = length(args{i}); end; for j=1:length(sobj), if strcmp(sobj(j).permission,'ro'), error('Array is read-only.'); end end if length(sobj)==1 sobj.dim = dm; if numel(dat)~=1, subfun(sobj,double(dat),args{:}); else dat1 = double(dat) + zeros(di); subfun(sobj,dat1,args{:}); end; else for j=1:length(sobj), ps = [sobj(j).pos ones(1,length(args))]; dm = [sobj(j).dim ones(1,length(args))]; siz = ones(1,16); for i=1:length(args), msk = args{i}>=ps(i) & args{i}<(ps(i)+dm(i)); args2{i} = find(msk); args3{i} = int32(double(args{i}(msk))-ps(i)+1); siz(i) = numel(args2{i}); end; if numel(dat)~=1, dat1 = double(subsref(dat,struct('type','()','subs',{args2}))); else dat1 = double(dat) + zeros(siz); end; subfun(sobj(j),dat1,args3{:}); end end return function sobj = subfun(sobj,dat,varargin) va = varargin; dt = datatypes; ind = find(cat(1,dt.code)==sobj.dtype); if isempty(ind), error('Unknown datatype'); end; if dt(ind).isint, dat(~isfinite(dat)) = 0; end; if ~isempty(sobj.scl_inter), inter = sobj.scl_inter; if numel(inter)>1, inter = resize_scales(inter,sobj.dim,varargin); end; dat = double(dat) - inter; end; if ~isempty(sobj.scl_slope), slope = sobj.scl_slope; if numel(slope)>1, slope = resize_scales(slope,sobj.dim,varargin); dat = double(dat)./slope; else dat = double(dat)/slope; end; end; if dt(ind).isint, dat = round(dat); end; % Avoid warning messages in R14 SP3 wrn = warning; warning('off'); dat = feval(dt(ind).conv,dat); warning(wrn); nelem = dt(ind).nelem; if nelem==1, mat2file(sobj,dat,va{:}); elseif nelem==2, sobj1 = sobj; sobj1.dim = [2 sobj.dim]; sobj1.dtype = dt(find(strcmp(dt(ind).prec,{dt.prec}) & (cat(2,dt.nelem)==1))).code; dat = reshape(dat,[1 size(dat)]); dat = [real(dat) ; imag(dat)]; mat2file(sobj1,dat,int32([1 2]),va{:}); else error('Inappropriate number of elements per voxel.'); end; return function obj = asgn(obj,fun,subs,dat) if ~isempty(subs), tmp = feval(fun,obj); tmp = subsasgn(tmp,subs,dat); obj = feval(fun,obj,tmp); else obj = feval(fun,obj,dat); end;
github
philippboehmsturm/antx-master
subsref.m
.m
antx-master/freiburgLight/matlab/spm8/@file_array/subsref.m
5,317
utf_8
64728e33af32c06b26b99b74b700f1f5
function varargout=subsref(obj,subs) % SUBSREF Subscripted reference % An overloaded function... %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: subsref.m 4136 2010-12-09 22:22:28Z guillaume $ if isempty(subs), return; end switch subs(1).type case '{}' error('Cell contents reference from a non-cell array object.'); case '.' varargout = access_fields(obj,subs); return; end if numel(subs)~=1, error('Expression too complicated'); end; dim = [size(obj) ones(1,16)]; nd = find(dim>1,1,'last')-1; sobj = struct(obj); if ~numel(subs.subs) [subs.subs{1:nd+1}] = deal(':'); elseif length(subs.subs) < nd l = length(subs.subs); dim = [dim(1:(l-1)) prod(dim(l:end))]; if numel(sobj) ~= 1 error('Can only reshape simple file_array objects.'); else if numel(sobj.scl_slope)>1 || numel(sobj.scl_inter)>1 error('Can not reshape file_array objects with multiple slopes and intercepts.'); end sobj.dim = dim; end end di = ones(16,1); args = cell(1,length(subs.subs)); for i=1:length(subs.subs) if ischar(subs.subs{i}) if ~strcmp(subs.subs{i},':'), error('This shouldn''t happen....'); end if length(subs.subs) == 1 args{i} = 1:prod(dim); % possible overflow when int32() k = 0; for j=1:length(sobj) sobj(j).dim = [prod(sobj(j).dim) 1]; sobj(j).pos = [k+1 1]; k = k + sobj(j).dim(1); end else args{i} = 1:dim(i); end else args{i} = subs.subs{i}; end di(i) = length(args{i}); end if length(sobj)==1 t = subfun(sobj,args{:}); else dt = datatypes; dt = dt([dt.code]==sobj(1).dtype); % assuming identical datatypes t = zeros(di',func2str(dt.conv)); for j=1:length(sobj) ps = [sobj(j).pos ones(1,length(args))]; dm = [sobj(j).dim ones(1,length(args))]; for i=1:length(args) msk = find(args{i}>=ps(i) & args{i}<(ps(i)+dm(i))); args2{i} = msk; args3{i} = double(args{i}(msk))-ps(i)+1; end t = subsasgn(t,struct('type','()','subs',{args2}),subfun(sobj(j),args3{:})); end end varargout = {t}; %========================================================================== % function t = subfun(sobj,varargin) %========================================================================== function t = subfun(sobj,varargin) %sobj.dim = [sobj.dim ones(1,16)]; try args = cell(size(varargin)); for i=1:length(varargin) args{i} = int32(varargin{i}); end t = file2mat(sobj,args{:}); catch t = multifile2mat(sobj,varargin{:}); end if ~isempty(sobj.scl_slope) || ~isempty(sobj.scl_inter) slope = 1; inter = 0; if ~isempty(sobj.scl_slope), slope = sobj.scl_slope; end if ~isempty(sobj.scl_inter), inter = sobj.scl_inter; end if numel(slope)>1 slope = resize_scales(slope,sobj.dim,varargin); t = double(t).*slope; else t = double(t)*slope; end if numel(inter)>1 inter = resize_scales(inter,sobj.dim,varargin); end; t = t + inter; end %========================================================================== % function c = access_fields(obj,subs) %========================================================================== function c = access_fields(obj,subs) sobj = struct(obj); c = cell(1,numel(sobj)); for i=1:numel(sobj) %obj = class(sobj(i),'file_array'); obj = sobj(i); switch(subs(1).subs) case 'fname', t = fname(obj); case 'dtype', t = dtype(obj); case 'offset', t = offset(obj); case 'dim', t = dim(obj); case 'scl_slope', t = scl_slope(obj); case 'scl_inter', t = scl_inter(obj); case 'permission', t = permission(obj); otherwise error(['Reference to non-existent field "' subs(1).subs '".']); end if numel(subs)>1 t = subsref(t,subs(2:end)); end c{i} = t; end %========================================================================== % function val = multifile2mat(sobj,varargin) %========================================================================== function val = multifile2mat(sobj,varargin) % Convert subscripts into linear index [indx2{1:length(varargin)}] = ndgrid(varargin{:},1); ind = sub2ind(sobj.dim,indx2{:}); % Work out the partition dt = datatypes; dt = dt([dt.code]==sobj.dtype); sz = dt.size; try mem = spm('Memory'); % in bytes, has to be a multiple of 16 (max([dt.size])) catch mem = 200 * 1024 * 1024; end s = ceil(prod(sobj.dim) * sz / mem); % Assign indices to partitions [x,y] = ind2sub([mem/sz s],ind(:)); c = histc(y,1:s); cc = [0 reshape(cumsum(c),1,[])]; % Read data in relevant partitions obj = sobj; val = zeros(length(x),1,func2str(dt.conv)); for i=reshape(find(c),1,[]) obj.offset = sobj.offset + mem*(i-1); obj.dim = [1 min(mem/sz, prod(sobj.dim)-(i-1)*mem/sz)]; val(cc(i)+1:cc(i+1)) = file2mat(obj,int32(1),int32(x(y==i))); end r = cellfun('length',varargin); if numel(r) == 1, r = [r 1]; end val = reshape(val,r);
github
philippboehmsturm/antx-master
disp.m
.m
antx-master/freiburgLight/matlab/spm8/@file_array/disp.m
929
utf_8
d0546a638c254605a9122a095e4a06ff
function disp(obj) % Display a file_array object % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: disp.m 4136 2010-12-09 22:22:28Z guillaume $ if numel(struct(obj))>1, fprintf(' %s object: ', class(obj)); sz = size(obj); if length(sz)>4, fprintf('%d-D\n',length(sz)); else for i=1:(length(sz)-1), fprintf('%d-by-',sz(i)); end; fprintf('%d\n',sz(end)); end; else disp(mystruct(obj)) end; return; %======================================================================= %======================================================================= function t = mystruct(obj) fn = fieldnames(obj); for i=1:length(fn) t.(fn{i}) = subsref(obj,struct('type','.','subs',fn{i})); end; return; %=======================================================================
github
philippboehmsturm/antx-master
offset.m
.m
antx-master/freiburgLight/matlab/spm8/@file_array/private/offset.m
738
utf_8
366c2df9f0b718e446521ec24447d7a8
function varargout = offset(varargin) % Format % For getting the value % dat = offset(obj) % % For setting the value % obj = offset(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: offset.m 1143 2008-02-07 19:33:33Z spm $ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.offset; return; function obj = asgn(obj,dat) if isnumeric(dat) && numel(dat)==1 && dat>=0 && rem(dat,1)==0, obj.offset = double(dat); else error('"offset" must be a positive integer.'); end; return;
github
philippboehmsturm/antx-master
scl_slope.m
.m
antx-master/freiburgLight/matlab/spm8/@file_array/private/scl_slope.m
724
utf_8
3da54efdb2422c907f41b13b577c1e11
function varargout = scl_slope(varargin) % Format % For getting the value % dat = scl_slope(obj) % % For setting the value % obj = scl_slope(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: scl_slope.m 1143 2008-02-07 19:33:33Z spm $ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.scl_slope; return; function obj = asgn(obj,dat) if isnumeric(dat), % && numel(dat)<=1, obj.scl_slope = double(dat); else error('"scl_slope" must be numeric.'); end; return;
github
philippboehmsturm/antx-master
scl_inter.m
.m
antx-master/freiburgLight/matlab/spm8/@file_array/private/scl_inter.m
725
utf_8
8beb5c3767db12faab13c212db9a22ee
function varargout = scl_inter(varargin) % Format % For getting the value % dat = scl_inter(obj) % % For setting the value % obj = scl_inter(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: scl_inter.m 1143 2008-02-07 19:33:33Z spm $ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.scl_inter; return; function obj = asgn(obj,dat) if isnumeric(dat), % && numel(dat)<=1, obj.scl_inter = double(dat); else error('"scl_inter" must be numeric.'); end; return;
github
philippboehmsturm/antx-master
fname.m
.m
antx-master/freiburgLight/matlab/spm8/@file_array/private/fname.m
688
utf_8
a873d5e909b320be0af566b05e301636
function varargout = fname(varargin) % Format % For getting the value % dat = fname(obj) % % For setting the value % obj = fname(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: fname.m 1143 2008-02-07 19:33:33Z spm $ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.fname; return; function obj = asgn(obj,dat) if ischar(dat) obj.fname = deblank(dat(:)'); else error('"fname" must be a character string.'); end; return;
github
philippboehmsturm/antx-master
dim.m
.m
antx-master/freiburgLight/matlab/spm8/@file_array/private/dim.m
800
utf_8
ee81353b13c1dd2f6e5a186f9db0f205
function varargout = dim(varargin) % Format % For getting the value % dat = dim(obj) % % For setting the value % obj = dim(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: dim.m 1143 2008-02-07 19:33:33Z spm $ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.dim; return; function obj = asgn(obj,dat) if isnumeric(dat) && all(dat>=0) && all(rem(dat,1)==0), dat = [double(dat(:)') 1 1]; lim = max([2 find(dat~=1)]); dat = dat(1:lim); obj.dim = dat; else error('"dim" must be a vector of positive integers.'); end; return;
github
philippboehmsturm/antx-master
permission.m
.m
antx-master/freiburgLight/matlab/spm8/@file_array/private/permission.m
873
utf_8
c058329145646bbcd34aaeffb7184ea9
function varargout = permission(varargin) % Format % For getting the value % dat = permission(obj) % % For setting the value % obj = permission(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: permission.m 1340 2008-04-09 17:11:23Z john $ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wrong number of arguments.'); end; return; function dat = ref(obj) dat = obj.permission; return; function obj = asgn(obj,dat) if ischar(dat) tmp = lower(deblank(dat(:)')); switch tmp, case 'ro', case 'rw', otherwise, error('Permission must be either "ro" or "rw"'); end obj.permission = tmp; else error('"permission" must be a character string.'); end; return;
github
philippboehmsturm/antx-master
dtype.m
.m
antx-master/freiburgLight/matlab/spm8/@file_array/private/dtype.m
2,265
utf_8
0298fb2f4de45f2f789a8a855bf62a2c
function varargout = dtype(varargin) % Format % For getting the value % dat = dtype(obj) % % For setting the value % obj = dtype(obj,dat) % _______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % % $Id: dtype.m 1143 2008-02-07 19:33:33Z spm $ if nargin==2, varargout{1} = asgn(varargin{:}); elseif nargin==1, varargout{1} = ref(varargin{:}); else error('Wring number of arguments.'); end; return; function t = ref(obj) d = datatypes; mch = find(cat(1,d.code)==obj.dtype); if isempty(mch), t = 'UNKNOWN'; else t = d(mch).label; end; if obj.be, t = [t '-BE']; else t = [t '-LE']; end; return; function obj = asgn(obj,dat) d = datatypes; if isnumeric(dat) if numel(dat)>=1, mch = find(cat(1,d.code)==dat(1)); if isempty(mch) || mch==0, fprintf('Invalid datatype (%d).', dat(1)); disp('First part of datatype should be of one of the following'); disp(sortrows([num2str(cat(1,d.code)) ... repmat(' ',numel(d),2) strvcat(d.label)])); %error(['Invalid datatype (' num2str(dat(1)) ').']); return; end; obj.dtype = double(dat(1)); end; if numel(dat)>=2, obj.be = double(dat(2)~=0); end; if numel(dat)>2, error('Too many elements in numeric datatype.'); end; elseif ischar(dat), dat1 = lower(dat); sep = find(dat1=='-' | dat1=='/'); sep = sep(sep~=1); if ~isempty(sep), c1 = dat1(1:(sep(1)-1)); c2 = dat1((sep(1)+1):end); else c1 = dat1; c2 = ''; end; mch = find(strcmpi(c1,lower({d.label}))); if isempty(mch), disp('First part of datatype should be of one of the following'); disp(sortrows([num2str(cat(1,d.code)) ... repmat(' ',numel(d),2) strvcat(d.label)])); %error(['Invalid datatype (' c1 ').']); return; else obj.dtype = double(d(mch(1)).code); end; if any(c2=='b'), if any(c2=='l'), error('Cannot be both big and little endian.'); end; obj.be = 1; elseif any(c2=='l'), obj.be = 0; end; else error('Invalid datatype.'); end; return;
github
philippboehmsturm/antx-master
spm_cfg_ppi.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_ppi.m
5,867
utf_8
895e4dae672dbaf9f85422e01a2647f2
function ppis = spm_cfg_ppi % SPM Configuration file for PPIs %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id: spm_cfg_ppi.m 4136 2010-12-09 22:22:28Z guillaume $ % --------------------------------------------------------------------- % spmmat Select SPM.mat % --------------------------------------------------------------------- spmmat = cfg_files; spmmat.tag = 'spmmat'; spmmat.name = 'Select SPM.mat'; spmmat.help = {'Select SPM.mat file'}; spmmat.filter = 'mat'; spmmat.ufilter = '^SPM\.mat$'; spmmat.num = [1 1]; % --------------------------------------------------------------------- % voi1 Select VOI.mat % --------------------------------------------------------------------- voi1 = cfg_files; voi1.tag = 'voi'; voi1.name = 'Select VOI'; voi1.help = {'physiological variable'}; voi1.filter = 'mat'; voi1.ufilter = '^VOI.*\.mat$'; voi1.num = [1 1]; % --------------------------------------------------------------------- % voi2 Select VOI.mat % --------------------------------------------------------------------- voi2 = cfg_files; voi2.tag = 'voi'; voi2.name = 'Select VOI'; voi2.help = {'physiological variables'}; voi2.filter = 'mat'; voi2.ufilter = '^VOI.*\.mat$'; voi2.num = [2 2]; % --------------------------------------------------------------------- % con Matrix of input variables and contrast weights % --------------------------------------------------------------------- con = cfg_entry; con.tag = 'u'; con.name = ' Input variables and contrast weights'; con.help = {['Matrix of input variables and contrast weights.',... 'This is an [n x 3] matrix. The first column indexes SPM.Sess.U(i). ',... 'The second column indexes the name of the input or cause, see ',... 'SPM.Sess.U(i).name{j}. The third column is the contrast weight. ',... ' Unless there are parametric effects the second column will generally ',... 'be a 1.']}; con.strtype = 'e'; con.num = [Inf 3]; % --------------------------------------------------------------------- % sd Simple deconvolution % --------------------------------------------------------------------- sd = cfg_branch; sd.tag = 'sd'; sd.name = 'Simple deconvolution'; sd.val = {voi1}; sd.help = {'Simple deconvolution'}; % --------------------------------------------------------------------- % phipi Physio-Physiologic Interaction % --------------------------------------------------------------------- phipi = cfg_branch; phipi.tag = 'phipi'; phipi.name = 'Physio-Physiologic Interaction'; phipi.val = {voi2}; phipi.help = {'Physio-Physiologic Interaction'}; % --------------------------------------------------------------------- % ppi Psycho-Physiologic Interaction % --------------------------------------------------------------------- ppi = cfg_branch; ppi.tag = 'ppi'; ppi.name = 'Psycho-Physiologic Interaction'; ppi.val = {voi1 con}; ppi.help = {'Psycho-Physiologic Interaction'}; % --------------------------------------------------------------------- % ppiflag Type of analysis % --------------------------------------------------------------------- ppiflag = cfg_choice; ppiflag.tag = 'type'; ppiflag.name = 'Type of analysis'; ppiflag.help = {'Type of analysis'}; ppiflag.values = {sd ppi phipi}; % --------------------------------------------------------------------- % name Name of PPI % --------------------------------------------------------------------- name = cfg_entry; name.tag = 'name'; name.name = 'Name of PPI'; name.help = {['Name of the PPI mat file that will be saved in the ',... 'same directory than the SPM.mat file. A ''PPI_'' prefix will be added.']}; name.strtype = 's'; name.num = [1 Inf]; % --------------------------------------------------------------------- % showGraphics Display results % --------------------------------------------------------------------- showGraphics = cfg_menu; showGraphics.tag = 'disp'; showGraphics.name = 'Display results'; showGraphics.help = {'Display results'}; showGraphics.labels = {'Yes' 'No'}; showGraphics.values = { 1 0 }; showGraphics.val = { 0 }; % --------------------------------------------------------------------- % ppis PPI % --------------------------------------------------------------------- ppis = cfg_exbranch; ppis.tag = 'ppi'; ppis.name = 'Physio/Psycho-Physiologic Interaction'; ppis.val = {spmmat ppiflag name showGraphics}; ppis.help = {['Bold deconvolution to create physio- or '... 'psycho-physiologic interactions.']}; ppis.prog = @run_ppi; ppis.vout = @vout_ppi; %------------------------------------------------------------------------- %------------------------------------------------------------------------- function out = run_ppi(job) switch char(fieldnames(job.type)) case 'sd' PPI = spm_peb_ppi(job.spmmat{1}, 'sd', char(job.type.sd.voi),... [], job.name, job.disp); case 'ppi' PPI = spm_peb_ppi(job.spmmat{1}, 'ppi', char(job.type.ppi.voi),... job.type.ppi.u, job.name, job.disp); case 'phipi' PPI = spm_peb_ppi(job.spmmat{1}, 'phipi', char(job.type.phipi.voi),... [], job.name, job.disp); otherwise error('Unknown type of analysis.'); end [p n] = fileparts(job.name); out.ppimat = cellstr(fullfile(fileparts(job.spmmat{1}),['PPI_' n '.mat'])); %------------------------------------------------------------------------- function dep = vout_ppi(varargin) dep(1) = cfg_dep; dep(1).sname = ' PPI mat File'; dep(1).src_output = substruct('.','ppimat'); dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_preproc.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_preproc.m
30,016
utf_8
b471e8090bf6ae6a44134c195fcdaefb
function preproc = spm_cfg_preproc % SPM Configuration file % automatically generated by the MATLABBATCH utility function GENCODE %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_preproc.m 3124 2009-05-18 08:13:52Z volkmar $ rev = '$Rev: 3124 $'; % --------------------------------------------------------------------- % data Data % --------------------------------------------------------------------- data = cfg_files; data.tag = 'data'; data.name = 'Data'; data.help = {'Select scans for processing. This assumes that there is one scan for each subject. Note that multi-spectral (when there are two or more registered images of different contrasts) processing is not yet implemented for this method.'}; data.filter = 'image'; data.ufilter = '.*'; data.num = [1 Inf]; % --------------------------------------------------------------------- % GM Grey Matter % --------------------------------------------------------------------- GM = cfg_menu; GM.tag = 'GM'; GM.name = 'Grey Matter'; GM.help = {'Options to produce grey matter images: c1*.img, wc1*.img and mwc1*.img.'}; GM.labels = { 'None' 'Native Space' 'Unmodulated Normalised' 'Modulated Normalised' 'Native + Unmodulated Normalised' 'Native + Modulated Normalised' 'Native + Modulated + Unmodulated' 'Modulated + Unmodulated Normalised' }'; GM.values = {[0 0 0] [0 0 1] [0 1 0] [1 0 0] [0 1 1] [1 0 1] [1 1 1]... [1 1 0]}; GM.def = @(val)spm_get_defaults('preproc.output.GM', val{:}); % --------------------------------------------------------------------- % WM White Matter % --------------------------------------------------------------------- WM = cfg_menu; WM.tag = 'WM'; WM.name = 'White Matter'; WM.help = {'Options to produce white matter images: c2*.img, wc2*.img and mwc2*.img.'}; WM.labels = { 'None' 'Native Space' 'Unmodulated Normalised' 'Modulated Normalised' 'Native + Unmodulated Normalised' 'Native + Modulated Normalised' 'Native + Modulated + Unmodulated' 'Modulated + Unmodulated Normalised' }'; WM.values = {[0 0 0] [0 0 1] [0 1 0] [1 0 0] [0 1 1] [1 0 1] [1 1 1]... [1 1 0]}; WM.def = @(val)spm_get_defaults('preproc.output.WM', val{:}); % --------------------------------------------------------------------- % CSF Cerebro-Spinal Fluid % --------------------------------------------------------------------- CSF = cfg_menu; CSF.tag = 'CSF'; CSF.name = 'Cerebro-Spinal Fluid'; CSF.help = {'Options to produce CSF images: c3*.img, wc3*.img and mwc3*.img.'}; CSF.labels = { 'None' 'Native Space' 'Unmodulated Normalised' 'Modulated Normalised' 'Native + Unmodulated Normalised' 'Native + Modulated Normalised' 'Native + Modulated + Unmodulated' 'Modulated + Unmodulated Normalised' }'; CSF.values = {[0 0 0] [0 0 1] [0 1 0] [1 0 0] [0 1 1] [1 0 1] [1 1 1]... [1 1 0]}; CSF.def = @(val)spm_get_defaults('preproc.output.CSF', val{:}); % --------------------------------------------------------------------- % biascor Bias Corrected % --------------------------------------------------------------------- biascor = cfg_menu; biascor.tag = 'biascor'; biascor.name = 'Bias Corrected'; biascor.help = {'This is the option to produce a bias corrected version of your image. MR images are usually corrupted by a smooth, spatially varying artifact that modulates the intensity of the image (bias). These artifacts, although not usually a problem for visual inspection, can impede automated processing of the images. The bias corrected version should have more uniform intensities within the different types of tissues.'}; biascor.labels = { 'Save Bias Corrected' 'Don''t Save Corrected' }'; biascor.values = {1 0}; biascor.def = @(val)spm_get_defaults('preproc.output.biascor', val{:}); % --------------------------------------------------------------------- % cleanup Clean up any partitions % --------------------------------------------------------------------- cleanup = cfg_menu; cleanup.tag = 'cleanup'; cleanup.name = 'Clean up any partitions'; cleanup.help = { 'This uses a crude routine for extracting the brain from segmentedimages. It begins by taking the white matter, and eroding it acouple of times to get rid of any odd voxels. The algorithmcontinues on to do conditional dilations for several iterations,where the condition is based upon gray or white matter being present.This identified region is then used to clean up the grey and whitematter partitions, and has a slight influences on the CSF partition.' '' 'If you find pieces of brain being chopped out in your data, then you may wish to disable or tone down the cleanup procedure.' }'; cleanup.labels = { 'Dont do cleanup' 'Light Clean' 'Thorough Clean' }'; cleanup.values = {0 1 2}; cleanup.def = @(val)spm_get_defaults('preproc.output.cleanup', val{:}); % --------------------------------------------------------------------- % output Output Files % --------------------------------------------------------------------- output = cfg_branch; output.tag = 'output'; output.name = 'Output Files'; output.val = {GM WM CSF biascor cleanup }; output.help = { 'This routine produces spatial normalisation parameters (*_seg_sn.mat files) by default. These can be used for writing spatially normalised versions of your data, via the "Normalise: Write" option. This mechanism may produce superior results than the "Normalise: Estimate" option (but probably not as good as those produced using DARTEL).' '' 'In addition, it also produces files that can be used for doing inverse normalisation. If you have an image of regions defined in the standard space, then the inverse deformations can be used to warp these regions so that it approximately overlay your image. To use this facility, the bounding-box and voxel sizes should be set to non-finite values (e.g. [NaN NaN NaN] for the voxel sizes, and ones(2,3)*NaN for the bounding box. This would be done by the spatial normalisation module, which allows you to select a set of parameters that describe the nonlinear warps, and the images that they should be applied to.' '' 'There are a number of options about what data you would like the routine to produce. The routine can be used for producing images of tissue classes, as well as bias corrected images. The native space option will produce a tissue class image (c*) that is in alignment with the original/* (see Figure \ref{seg1})*/. You can also produce spatially normalised versions - both with (mwc*) and without (wc*) modulation/* (see Figure \ref{seg2})*/. The bounding box and voxel sizes of the spatially normalised versions are the same as that of the tissue probability maps with which they are registered. These can be used for doing voxel-based morphometry with (also see the ``Using DARTEL'' chapter of the manual). All you need to do is smooth them and do the stats (which means no more questions on the mailing list about how to do "optimized VBM").' '' 'Modulation is to compensate for the effect of spatial normalisation. When warping a series of images to match a template, it is inevitable that volumetric differences will be introduced into the warped images. For example, if one subject''s temporal lobe has half the volume of that of the template, then its volume will be doubled during spatial normalisation. This will also result in a doubling of the voxels labelled grey matter. In order to remove this confound, the spatially normalised grey matter (or other tissue class) is adjusted by multiplying by its relative volume before and after warping. If warping results in a region doubling its volume, then the correction will halve the intensity of the tissue label. This whole procedure has the effect of preserving the total amount of grey matter signal in the normalised partitions.' '/*\begin{figure} \begin{center} \includegraphics[width=140mm]{images/seg1} \end{center} \caption{Segmentation results. These are the results that can be obtained in the original space of the image (i.e. the results that are not spatially normalised). Top left: original image (X.img). Top right: bias corrected image (mX.img). Middle and bottom rows: segmented grey matter (c1X.img), white matter (c2X.img) and CSF (c3X.img). \label{seg1}} \end{figure} */' '/*\begin{figure} \begin{center} \includegraphics[width=140mm]{images/seg2} \end{center} \caption{Segmentation results. These are the spatially normalised results that can be obtained (note that CSF data is not shown). Top row: The tissue probability maps used to guide the segmentation. Middle row: Spatially normalised tissue maps of grey and white matter (wc1X.img and wc2X.img). Bottom row: Modulated spatially normalised tissue maps of grey and white matter (mwc1X.img and mwc2X.img). \label{seg2}} \end{figure} */' 'A deformation field is a vector field, where three values are associated with each location in the field. The field maps from co-ordinates in the normalised image back to co-ordinates in the original image. The value of the field at co-ordinate [x y z] in the normalised space will be the co-ordinate [x'' y'' z''] in the original volume. The gradient of the deformation field at a co-ordinate is its Jacobian matrix, and it consists of a 3x3 matrix:' '' '% / \' '% | dx''/dx dx''/dy dx''/dz |' '% | |' '% | dy''/dx dy''/dy dy''/dz |' '% | |' '% | dz''/dx dz''/dy dz''/dz |' '% \ /' '/* \begin{eqnarray*}\begin{pmatrix}\frac{dx''}{dx} & \frac{dx''}{dy} & \frac{dx''}{dz}\cr\frac{dy''}{dx} & \frac{dy''}{dy} & \frac{dy''}{dz}\cr\frac{dz''}{dx} & \frac{dz''}{dy} & \frac{dz''}{dz}\cr\end{pmatrix}\end{eqnarray*}*/' 'The value of dx''/dy is a measure of how much x'' changes if y is changed by a tiny amount. The determinant of the Jacobian is the measure of relative volumes of warped and unwarped structures. The modulation step simply involves multiplying by the relative volumes /*(see Figure \ref{seg2})*/.' }'; % --------------------------------------------------------------------- % tpm Tissue probability maps % --------------------------------------------------------------------- tpm = cfg_files; tpm.tag = 'tpm'; tpm.name = 'Tissue probability maps'; tpm.help = { 'Select the tissue probability images. These should be maps of grey matter, white matter and cerebro-spinal fluid probability. A nonlinear deformation field is estimated that best overlays the tissue probability maps on the individual subjects'' image. The default tissue probability maps are modified versions of the ICBM Tissue Probabilistic Atlases.These tissue probability maps are kindly provided by the International Consortium for Brain Mapping, John C. Mazziotta and Arthur W. Toga. http://www.loni.ucla.edu/ICBM/ICBM_TissueProb.html. The original data are derived from 452 T1-weighted scans, which were aligned with an atlas space, corrected for scan inhomogeneities, and classified into grey matter, white matter and cerebrospinal fluid. These data were then affine registered to the MNI space and downsampled to 2mm resolution.' '' 'Rather than assuming stationary prior probabilities based upon mixing proportions, additional information is used, based on other subjects'' brain images. Priors are usually generated by registering a large number of subjects together, assigning voxels to different tissue types and averaging tissue classes over subjects. Three tissue classes are used: grey matter, white matter and cerebro-spinal fluid. A fourth class is also used, which is simply one minus the sum of the first three. These maps give the prior probability of any voxel in a registered image being of any of the tissue classes - irrespective of its intensity.' '' 'The model is refined further by allowing the tissue probability maps to be deformed according to a set of estimated parameters. This allows spatial normalisation and segmentation to be combined into the same model. This implementation uses a low-dimensional approach, which parameterises the deformations by a linear combination of about a thousand cosine transform bases. This is not an especially precise way of encoding deformations, but it can model the variability of overall brain shape. Evaluations by Hellier et al have shown that this simple model can achieve a registration accuracy comparable to other fully automated methods with many more parameters.' }'; tpm.filter = 'image'; tpm.dir = fullfile(spm('dir'),'tpm'); tpm.ufilter = '.*'; tpm.num = [3 3]; tpm.def = @(val)spm_get_defaults('preproc.tpm', val{:}); % --------------------------------------------------------------------- % ngaus Gaussians per class % --------------------------------------------------------------------- ngaus = cfg_entry; ngaus.tag = 'ngaus'; ngaus.name = 'Gaussians per class'; ngaus.help = {'The number of Gaussians used to represent the intensity distribution for each tissue class can be greater than one. In other words, a tissue probability map may be shared by several clusters. The assumption of a single Gaussian distribution for each class does not hold for a number of reasons. In particular, a voxel may not be purely of one tissue type, and instead contain signal from a number of different tissues (partial volume effects). Some partial volume voxels could fall at the interface between different classes, or they may fall in the middle of structures such as the thalamus, which may be considered as being either grey or white matter. Various other image segmentation approaches use additional clusters to model such partial volume effects. These generally assume that a pure tissue class has a Gaussian intensity distribution, whereas intensity distributions for partial volume voxels are broader, falling between the intensities of the pure classes. Unlike these partial volume segmentation approaches, the model adopted here simply assumes that the intensity distribution of each class may not be Gaussian, and assigns belonging probabilities according to these non-Gaussian distributions. Typical numbers of Gaussians could be two for grey matter, two for white matter, two for CSF, and four for everything else.'}; ngaus.strtype = 'n'; ngaus.num = [4 1]; ngaus.def = @(val)spm_get_defaults('preproc.ngaus', val{:}); % --------------------------------------------------------------------- % regtype Affine Regularisation % --------------------------------------------------------------------- regtype = cfg_menu; regtype.tag = 'regtype'; regtype.name = 'Affine Regularisation'; regtype.help = { 'The procedure is a local optimisation, so it needs reasonable initial starting estimates. Images should be placed in approximate alignment using the Display function of SPM before beginning. A Mutual Information affine registration with the tissue probability maps (D''Agostino et al, 2004) is used to achieve approximate alignment. Note that this step does not include any model for intensity non-uniformity. This means that if the procedure is to be initialised with the affine registration, then the data should not be too corrupted with this artifact.If there is a lot of intensity non-uniformity, then manually position your image in order to achieve closer starting estimates, and turn off the affine registration.' '' 'Affine registration into a standard space can be made more robust by regularisation (penalising excessive stretching or shrinking). The best solutions can be obtained by knowing the approximate amount of stretching that is needed (e.g. ICBM templates are slightly bigger than typical brains, so greater zooms are likely to be needed). For example, if registering to an image in ICBM/MNI space, then choose this option. If registering to a template that is close in size, then select the appropriate option for this.' }'; regtype.labels = { 'No Affine Registration' 'ICBM space template - European brains' 'ICBM space template - East Asian brains' 'Average sized template' 'No regularisation' }'; regtype.values = { '' 'mni' 'eastern' 'subj' 'none' }'; regtype.def = @(val)spm_get_defaults('preproc.regtype', val{:}); % --------------------------------------------------------------------- % warpreg Warping Regularisation % --------------------------------------------------------------------- warpreg = cfg_entry; warpreg.tag = 'warpreg'; warpreg.name = 'Warping Regularisation'; warpreg.help = {'The objective function for registering the tissue probability maps to the image to process, involves minimising the sum of two terms. One term gives a function of how probable the data is given the warping parameters. The other is a function of how probable the parameters are, and provides a penalty for unlikely deformations. Smoother deformations are deemed to be more probable. The amount of regularisation determines the tradeoff between the terms. Pick a value around one. However, if your normalised images appear distorted, then it may be an idea to increase the amount of regularisation (by an order of magnitude). More regularisation gives smoother deformations, where the smoothness measure is determined by the bending energy of the deformations. '}; warpreg.strtype = 'e'; warpreg.num = [1 1]; warpreg.def = @(val)spm_get_defaults('preproc.warpreg', val{:}); % --------------------------------------------------------------------- % warpco Warp Frequency Cutoff % --------------------------------------------------------------------- warpco = cfg_entry; warpco.tag = 'warpco'; warpco.name = 'Warp Frequency Cutoff'; warpco.help = {'Cutoff of DCT bases. Only DCT bases of periods longer than the cutoff are used to describe the warps. The number actually used will depend on the cutoff and the field of view of your image. A smaller cutoff frequency will allow more detailed deformations to be modelled, but unfortunately comes at a cost of greatly increasing the amount of memory needed, and the time taken.'}; warpco.strtype = 'e'; warpco.num = [1 1]; warpco.def = @(val)spm_get_defaults('preproc.warpco', val{:}); % --------------------------------------------------------------------- % biasreg Bias regularisation % --------------------------------------------------------------------- biasreg = cfg_menu; biasreg.tag = 'biasreg'; biasreg.name = 'Bias regularisation'; biasreg.help = { 'MR images are usually corrupted by a smooth, spatially varying artifact that modulates the intensity of the image (bias). These artifacts, although not usually a problem for visual inspection, can impede automated processing of the images.' '' 'An important issue relates to the distinction between intensity variations that arise because of bias artifact due to the physics of MR scanning, and those that arise due to different tissue properties. The objective is to model the latter by different tissue classes, while modelling the former with a bias field. We know a priori that intensity variations due to MR physics tend to be spatially smooth, whereas those due to different tissue types tend to contain more high frequency information. A more accurate estimate of a bias field can be obtained by including prior knowledge about the distribution of the fields likely to be encountered by the correction algorithm. For example, if it is known that there is little or no intensity non-uniformity, then it would be wise to penalise large values for the intensity non-uniformity parameters. This regularisation can be placed within a Bayesian context, whereby the penalty incurred is the negative logarithm of a prior probability for any particular pattern of non-uniformity.' }'; biasreg.labels = { 'no regularisation (0)' 'extremely light regularisation (0.00001)' 'very light regularisation (0.0001)' 'light regularisation (0.001)' 'medium regularisation (0.01)' 'heavy regularisation (0.1)' 'very heavy regularisation (1)' 'extremely heavy regularisation (10)' }'; biasreg.values = {0 1e-5 .0001 .001 .01 .1 1 10}; biasreg.def = @(val)spm_get_defaults('preproc.biasreg', val{:}); % --------------------------------------------------------------------- % biasfwhm Bias FWHM % --------------------------------------------------------------------- biasfwhm = cfg_menu; biasfwhm.tag = 'biasfwhm'; biasfwhm.name = 'Bias FWHM'; biasfwhm.help = {'FWHM of Gaussian smoothness of bias. If your intensity non-uniformity is very smooth, then choose a large FWHM. This will prevent the algorithm from trying to model out intensity variation due to different tissue types. The model for intensity non-uniformity is one of i.i.d. Gaussian noise that has been smoothed by some amount, before taking the exponential. Note also that smoother bias fields need fewer parameters to describe them. This means that the algorithm is faster for smoother intensity non-uniformities.'}; biasfwhm.labels = { '30mm cutoff' '40mm cutoff' '50mm cutoff' '60mm cutoff' '70mm cutoff' '80mm cutoff' '90mm cutoff' '100mm cutoff' '110mm cutoff' '120mm cutoff' '130mm cutoff' '140mm cutoff' '150mm cutoff' 'No correction' }'; biasfwhm.values = {30 40 50 60 70 80 90 100 110 120 130 140 150 Inf}; biasfwhm.def = @(val)spm_get_defaults('preproc.biasfwhm', val{:}); % --------------------------------------------------------------------- % samp Sampling distance % --------------------------------------------------------------------- samp = cfg_entry; samp.tag = 'samp'; samp.name = 'Sampling distance'; samp.help = {'The approximate distance between sampled points when estimating the model parameters. Smaller values use more of the data, but the procedure is slower.'}; samp.strtype = 'e'; samp.num = [1 1]; samp.def = @(val)spm_get_defaults('preproc.samp', val{:}); % --------------------------------------------------------------------- % msk Masking image % --------------------------------------------------------------------- msk = cfg_files; msk.tag = 'msk'; msk.name = 'Masking image'; msk.val{1} = {''}; msk.help = {'The segmentation can be masked by an image that conforms to the same space as the images to be segmented. If an image is selected, then it must match the image(s) voxel-for voxel, and have the same voxel-to-world mapping. Regions containing a value of zero in this image do not contribute when estimating the various parameters. '}; msk.filter = 'image'; msk.ufilter = '.*'; msk.num = [0 1]; % --------------------------------------------------------------------- % opts Custom % --------------------------------------------------------------------- opts = cfg_branch; opts.tag = 'opts'; opts.name = 'Custom'; opts.val = {tpm ngaus regtype warpreg warpco biasreg biasfwhm samp msk }; opts.help = {'Various options can be adjusted in order to improve the performance of the algorithm with your data. Knowing what works best should be a matter of empirical exploration. For example, if your data has very little intensity non-uniformity artifact, then the bias regularisation should be increased. This effectively tells the algorithm that there is very little bias in your data, so it does not try to model it.'}; % --------------------------------------------------------------------- % preproc Segment % --------------------------------------------------------------------- preproc = cfg_exbranch; preproc.tag = 'preproc'; preproc.name = 'Segment'; preproc.val = {data output opts }; preproc.help = { 'Segment, bias correct and spatially normalise - all in the same model/* \cite{ashburner05}*/. This function can be used for bias correcting, spatially normalising or segmenting your data. Note that this module needs the images to be roughly aligned with the tissue probability maps before you begin. If strange results are obtained, then this is usually because the images were poorly aligned beforehand. The Display option can be used to manually reposition the images so that the AC is close to coordinate 0,0,0 (within a couple of cm) and the orientation is within a few degrees of the tissue probability map data.' '' 'Many investigators use tools within older versions of SPM for a technique that has become known as "optimised" voxel-based morphometry (VBM). VBM performs region-wise volumetric comparisons among populations of subjects. It requires the images to be spatially normalised, segmented into different tissue classes, and smoothed, prior to performing statistical tests/* \cite{wright_vbm,am_vbmreview,ashburner00b,john_should}*/. The "optimised" pre-processing strategy involved spatially normalising subjects'' brain images to a standard space, by matching grey matter in these images, to a grey matter reference. The historical motivation behind this approach was to reduce the confounding effects of non-brain (e.g. scalp) structural variability on the registration. Tissue classification in older versions of SPM required the images to be registered with tissue probability maps. After registration, these maps represented the prior probability of different tissue classes being found at each location in an image. Bayes rule can then be used to combine these priors with tissue type probabilities derived from voxel intensities, to provide the posterior probability.' '' 'This procedure was inherently circular, because the registration required an initial tissue classification, and the tissue classification requires an initial registration. This circularity is resolved here by combining both components into a single generative model. This model also includes parameters that account for image intensity non-uniformity. Estimating the model parameters (for a maximum a posteriori solution) involves alternating among classification, bias correction and registration steps. This approach provides better results than simple serial applications of each component.' '' 'Note that multi-spectral segmentation (e.g. from a registered T1 and T2 image) is not yet implemented, but is planned for a future SPM version.' }'; preproc.prog = @spm_run_preproc; preproc.vout = @vout; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function dep = vout(job) opts = job.output; cdep(1) = cfg_dep; cdep(1).sname = 'Norm Params Subj->MNI'; cdep(1).src_output = substruct('()',{1}, '.','snfile','()',{':'}); cdep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); cdep(2) = cfg_dep; cdep(2).sname = 'Norm Params MNI->Subj'; cdep(2).src_output = substruct('()',{1}, '.','isnfile','()',{':'}); cdep(2).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); if opts.biascor, cdep(end+1) = cfg_dep; cdep(end).sname = 'Bias Corr Images'; cdep(end).src_output = substruct('()',{1}, '.','biascorr','()',{':'}); cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end; sonames = {'GM','WM','CSF'}; for k1=1:3, if ~strcmp(opts.(sonames{k1}),'<UNDEFINED>') if opts.(sonames{k1})(3), cdep(end+1) = cfg_dep; cdep(end).sname = sprintf('c%d Images',k1); cdep(end).src_output = substruct('()',{1}, '.',sprintf('c%d',k1),'()',{':'}); cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end; if opts.(sonames{k1})(2), cdep(end+1) = cfg_dep; cdep(end).sname = sprintf('wc%d Images',k1); cdep(end).src_output = substruct('()',{1}, '.',sprintf('wc%d',k1),'()',{':'}); cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end; if opts.(sonames{k1})(1), cdep(end+1) = cfg_dep; cdep(end).sname = sprintf('mwc%d Images',k1); cdep(end).src_output = substruct('()',{1}, '.',sprintf('mwc%d',k1),'()',{':'}); cdep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end; end end; dep = cdep;
github
philippboehmsturm/antx-master
spm_run_fmri_design.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_run_fmri_design.m
11,410
utf_8
966cf5ef726bcdbf52473fdcdd3d3525
function out = spm_run_fmri_design(job) % Set up the design matrix and run a design. % SPM job execution function % takes a harvested job data structure and call SPM functions to perform % computations on the data. % Input: % job - harvested job data structure (see matlabbatch help) % Output: % out - computation results, usually a struct variable. %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_run_fmri_design.m 4185 2011-02-01 18:46:18Z guillaume $ original_dir = pwd; my_cd(job.dir); %-Ask about overwriting files from previous analyses... %------------------------------------------------------------------- if exist(fullfile(job.dir{1},'SPM.mat'),'file') str = { 'Current directory contains existing SPM file:',... 'Continuing will overwrite existing file!'}; if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename); fprintf('%-40s: %30s\n\n',... 'Abort... (existing SPM file)',spm('time')); return end end % If we've gotten to this point we're committed to overwriting files. % Delete them so we don't get stuck in spm_spm %------------------------------------------------------------------------ files = {'^mask\..{3}$','^ResMS\..{3}$','^RPV\..{3}$',... '^beta_.{4}\..{3}$','^con_.{4}\..{3}$','^ResI_.{4}\..{3}$',... '^ess_.{4}\..{3}$', '^spm\w{1}_.{4}\..{3}$'}; for i=1:length(files) j = spm_select('List',pwd,files{i}); for k=1:size(j,1) spm_unlink(deblank(j(k,:))); end end % Variables %------------------------------------------------------------- SPM.xY.RT = job.timing.RT; % Slice timing %------------------------------------------------------------- % The following lines have the side effect of modifying the global % defaults variable. This is necessary to pass job.timing.fmri_t to % spm_hrf.m. The original values are saved here and restored at the end % of this function, after the design has been specified. The original % values may not be restored if this function crashes. olddefs.stats.fmri.fmri_t = spm_get_defaults('stats.fmri.fmri_t'); olddefs.stats.fmri.fmri_t0 = spm_get_defaults('stats.fmri.fmri_t0'); spm_get_defaults('stats.fmri.t', job.timing.fmri_t); spm_get_defaults('stats.fmri.t0', job.timing.fmri_t0); % Basis function variables %------------------------------------------------------------- SPM.xBF.UNITS = job.timing.units; SPM.xBF.dt = job.timing.RT/job.timing.fmri_t; SPM.xBF.T = job.timing.fmri_t; SPM.xBF.T0 = job.timing.fmri_t0; % Basis functions %------------------------------------------------------------- if strcmp(fieldnames(job.bases),'hrf') if all(job.bases.hrf.derivs == [0 0]) SPM.xBF.name = 'hrf'; elseif all(job.bases.hrf.derivs == [1 0]) SPM.xBF.name = 'hrf (with time derivative)'; elseif all(job.bases.hrf.derivs == [1 1]) SPM.xBF.name = 'hrf (with time and dispersion derivatives)'; else error('Unrecognized hrf derivative choices.') end else nambase = fieldnames(job.bases); if ischar(nambase) nam=nambase; else nam=nambase{1}; end switch nam, case 'fourier', SPM.xBF.name = 'Fourier set'; case 'fourier_han', SPM.xBF.name = 'Fourier set (Hanning)'; case 'gamma', SPM.xBF.name = 'Gamma functions'; case 'fir', SPM.xBF.name = 'Finite Impulse Response'; otherwise error('Unrecognized hrf derivative choices.') end SPM.xBF.length = job.bases.(nam).length; SPM.xBF.order = job.bases.(nam).order; end SPM.xBF = spm_get_bf(SPM.xBF); if isempty(job.sess), SPM.xBF.Volterra = false; else SPM.xBF.Volterra = job.volt; end; for i = 1:numel(job.sess), sess = job.sess(i); % Image filenames %------------------------------------------------------------- SPM.nscan(i) = sess.nscan; U = []; % Augment the singly-specified conditions with the multiple conditions % specified in a .mat file provided by the user %------------------------------------------------------------ if ~isempty(sess.multi{1}) try multicond = load(sess.multi{1}); catch error('Cannot load %s',sess.multi{1}); end if ~(isfield(multicond,'names')&&isfield(multicond,'onsets')&&... isfield(multicond,'durations')) || ... ~all([numel(multicond.names),numel(multicond.onsets), ... numel(multicond.durations)]==numel(multicond.names)) error(['Multiple conditions MAT-file ''%s'' is invalid.\n',... 'File must contain names, onsets, and durations '... 'cell arrays of equal length.\n'],sess.multi{1}); end %-contains three cell arrays: names, onsets and durations for j=1:length(multicond.onsets) cond.name = multicond.names{j}; cond.onset = multicond.onsets{j}; cond.duration = multicond.durations{j}; % ADDED BY DGITELMAN % Mutiple Conditions Time Modulation %------------------------------------------------------ % initialize the variable. cond.tmod = 0; if isfield(multicond,'tmod'); try cond.tmod = multicond.tmod{j}; catch error('Error specifying time modulation.'); end end % Mutiple Conditions Parametric Modulation %------------------------------------------------------ % initialize the parametric modulation variable. cond.pmod = []; if isfield(multicond,'pmod') % only access existing modulators try % check if there is a parametric modulator. this allows % pmod structures with fewer entries than conditions. % then check whether any cells are filled in. if (j <= numel(multicond.pmod)) && ... ~isempty(multicond.pmod(j).name) % we assume that the number of cells in each % field of pmod is the same (or should be). for ii = 1:numel(multicond.pmod(j).name) cond.pmod(ii).name = multicond.pmod(j).name{ii}; cond.pmod(ii).param = multicond.pmod(j).param{ii}; cond.pmod(ii).poly = multicond.pmod(j).poly{ii}; end end; catch error('Error specifying parametric modulation.'); end end sess.cond(end+1) = cond; end end % Configure the input structure array %------------------------------------------------------------- for j = 1:length(sess.cond), cond = sess.cond(j); U(j).name = {cond.name}; U(j).ons = cond.onset(:); U(j).dur = cond.duration(:); if length(U(j).dur) == 1 U(j).dur = U(j).dur*ones(size(U(j).ons)); elseif length(U(j).dur) ~= length(U(j).ons) error('Mismatch between number of onset and number of durations.') end P = []; q1 = 0; if cond.tmod>0, % time effects P(1).name = 'time'; P(1).P = U(j).ons*job.timing.RT/60; P(1).h = cond.tmod; q1 = 1; end; if ~isempty(cond.pmod) for q = 1:numel(cond.pmod), % Parametric effects q1 = q1 + 1; P(q1).name = cond.pmod(q).name; P(q1).P = cond.pmod(q).param(:); P(q1).h = cond.pmod(q).poly; end; end if isempty(P) P.name = 'none'; P.h = 0; end U(j).P = P; end SPM.Sess(i).U = U; % User specified regressors %------------------------------------------------------------- C = []; Cname = cell(1,numel(sess.regress)); for q = 1:numel(sess.regress), Cname{q} = sess.regress(q).name; C = [C, sess.regress(q).val(:)]; end % Augment the singly-specified regressors with the multiple regressors % specified in the regressors.mat file %------------------------------------------------------------ if ~strcmp(sess.multi_reg,'') tmp=load(char(sess.multi_reg{:})); if isstruct(tmp) && isfield(tmp,'R') R = tmp.R; elseif isnumeric(tmp) % load from e.g. text file R = tmp; else warning('Can''t load user specified regressors in %s', ... char(sess.multi_reg{:})); R = []; end C=[C, R]; nr=size(R,2); nq=length(Cname); for inr=1:nr, Cname{inr+nq}=['R',int2str(inr)]; end end SPM.Sess(i).C.C = C; SPM.Sess(i).C.name = Cname; end % Factorial design %------------------------------------------------------------- if isfield(job,'fact') if ~isempty(job.fact) NC=length(SPM.Sess(1).U); % Number of conditions CheckNC=1; for i=1:length(job.fact) SPM.factor(i).name=job.fact(i).name; SPM.factor(i).levels=job.fact(i).levels; CheckNC=CheckNC*SPM.factor(i).levels; end if ~(CheckNC==NC) disp('Error in fmri_spec job: factors do not match conditions'); return end end else SPM.factor=[]; end % Globals %------------------------------------------------------------- SPM.xGX.iGXcalc = job.global; SPM.xGX.sGXcalc = 'mean voxel value'; SPM.xGX.sGMsca = 'session specific'; % High Pass filter %------------------------------------------------------------- for i = 1:numel(job.sess), SPM.xX.K(i).HParam = job.sess(i).hpf; end % Autocorrelation %------------------------------------------------------------- SPM.xVi.form = job.cvi; % Let SPM configure the design %------------------------------------------------------------- SPM = spm_fMRI_design(SPM); %-Save SPM.mat %------------------------------------------------------------------------- fprintf('%-40s: ','Saving SPM configuration') %-# if spm_check_version('matlab','7') >= 0 save('SPM.mat','-V6','SPM'); else save('SPM.mat','SPM'); end fprintf('%30s\n','...SPM.mat saved') %-# out.spmmat{1} = fullfile(pwd, 'SPM.mat'); my_cd(original_dir); % Change back dir spm_get_defaults('stats.fmri.fmri_t',olddefs.stats.fmri.fmri_t); % Restore old timing spm_get_defaults('stats.fmri.fmri_t0',olddefs.stats.fmri.fmri_t0); % parameters fprintf('Done\n') return %------------------------------------------------------------------------- %------------------------------------------------------------------------- function my_cd(varargin) % jobDir must be the actual directory to change to, NOT the job structure. jobDir = varargin{1}; if ~isempty(jobDir) try cd(char(jobDir)); fprintf('Changing directory to: %s\n',char(jobDir)); catch error('Failed to change directory. Aborting run.') end end return;
github
philippboehmsturm/antx-master
spm_cfg_eeg_grandmean.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_grandmean.m
2,570
utf_8
41cefba7c2387be2142bfcd23931e054
function S = spm_cfg_eeg_grandmean % configuration file for averaging evoked responses %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: spm_cfg_eeg_grandmean.m 3881 2010-05-07 21:02:57Z vladimir $ % ------------------------------------------------------------------------- % weighted Weighted average % ------------------------------------------------------------------------- weighted = cfg_menu; weighted.tag = 'weighted'; weighted.name = 'Weighted average?'; weighted.help = {'Average weighted by number of replications in input.'}; weighted.labels = {'Yes' 'No'}; weighted.values = {1 0}; %-------------------------------------------------------------------------- % D File Names %-------------------------------------------------------------------------- D = cfg_files; D.tag = 'D'; D.name = 'File Names'; D.filter = 'mat'; D.num = [1 inf]; D.help = {'Select the M/EEG mat file.'}; %-------------------------------------------------------------------------- % Dout Output filename %-------------------------------------------------------------------------- Dout = cfg_entry; Dout.tag = 'Dout'; Dout.name = 'Output filename'; Dout.strtype = 's'; Dout.num = [1 inf]; Dout.help = {'Choose filename'}; %-------------------------------------------------------------------------- % S Grandmean %-------------------------------------------------------------------------- S = cfg_exbranch; S.tag = 'grandmean'; S.name = 'M/EEG Grandmean'; S.val = {D Dout weighted}; S.help = {'Average multiple evoked responses'}; S.prog = @eeg_grandmean; S.vout = @vout_eeg_grandmean; S.modality = {'EEG'}; %========================================================================== function out = eeg_grandmean(job) % construct the S struct S.D = strvcat(job.D); S.Dout = job.Dout; S.weighted = job.weighted; out.D = spm_eeg_grandmean(S); out.Dfname = {fullfile(out.D.path, out.D.fname)}; %========================================================================== function dep = vout_eeg_grandmean(job) dep(1) = cfg_dep; dep(1).sname = 'Grandmean Data'; dep(1).src_output = substruct('.','D'); dep(1).tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Grandmean Datafile'; dep(2).src_output = substruct('.','Dfname'); dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_cfg_dicom.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_dicom.m
5,587
utf_8
bf4d49bb102e084fbe7722b3589b8ea9
function dicom = spm_cfg_dicom % SPM Configuration file for DICOM Import %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_dicom.m 4012 2010-07-22 12:45:53Z volkmar $ % --------------------------------------------------------------------- % data DICOM files % --------------------------------------------------------------------- data = cfg_files; data.tag = 'data'; data.name = 'DICOM files'; data.help = {'Select the DICOM files to convert.'}; data.filter = 'any'; data.ufilter = '.*'; data.num = [1 Inf]; % --------------------------------------------------------------------- % root Directory structure for converted files % --------------------------------------------------------------------- root = cfg_menu; root.tag = 'root'; root.name = 'Directory structure for converted files'; root.help = {'Choose root directory of converted file tree. The options are:' '' '* Output directory: ./<StudyDate-StudyTime>: Automatically determine the project name and try to convert into the output directory, starting with a StudyDate-StudyTime subdirectory. This option is useful if automatic project recognition fails and one wants to convert data into a project directory.' '' '* Output directory: ./<PatientID>: Convert into the output directory, starting with a PatientID subdirectory.' '' '* Output directory: ./<PatientName>: Convert into the output directory, starting with a PatientName subdirectory.' '* No directory hierarchy: Convert all files into the output directory, without sequence/series subdirectories'}'; root.labels = {'Output directory: ./<StudyDate-StudyTime>/<ProtocolName>' 'Output directory: ./<PatientID>/<ProtocolName>' 'Output directory: ./<PatientID>/<StudyDate-StudyTime>/<ProtocolName>' 'Output directory: ./<PatientName>/<ProtocolName>' 'Output directory: ./<ProtocolName>' 'No directory hierarchy'}'; root.values = {'date_time' 'patid' 'patid_date' 'patname' 'series' 'flat'}'; root.def = @(val)spm_get_defaults('dicom.root', val{:}); % --------------------------------------------------------------------- % outdir Output directory % --------------------------------------------------------------------- outdir = cfg_files; outdir.tag = 'outdir'; outdir.name = 'Output directory'; outdir.help = {'Select a directory where files are written.'}; outdir.filter = 'dir'; outdir.ufilter = '.*'; outdir.num = [1 1]; % --------------------------------------------------------------------- % format Output image format % --------------------------------------------------------------------- format = cfg_menu; format.tag = 'format'; format.name = 'Output image format'; format.help = {'DICOM conversion can create separate img and hdr files or combine them in one file. The single file option will help you save space on your hard disk, but may be incompatible with programs that are not NIfTI-aware.' 'In any case, only 3D image files will be produced.'}'; format.labels = {'Two file (img+hdr) NIfTI' 'Single file (nii) NIfTI'}'; format.values = {'img' 'nii'}; format.def = @(val)spm_get_defaults('images.format', val{:}); % --------------------------------------------------------------------- % icedims Use ICEDims in filename % --------------------------------------------------------------------- icedims = cfg_menu; icedims.tag = 'icedims'; icedims.name = 'Use ICEDims in filename'; icedims.help = {'If image sorting fails, one can try using the additional SIEMENS ICEDims information to create unique filenames. Use this only if there would be multiple volumes with exactly the same file names.'}; icedims.labels = {'No' 'Yes'}; icedims.values = {0 1}; icedims.val = {0}; % --------------------------------------------------------------------- % convopts Conversion options % --------------------------------------------------------------------- convopts = cfg_branch; convopts.tag = 'convopts'; convopts.name = 'Conversion options'; convopts.val = {format icedims}; convopts.help = {''}; % --------------------------------------------------------------------- % dicom DICOM Import % --------------------------------------------------------------------- dicom = cfg_exbranch; dicom.tag = 'dicom'; dicom.name = 'DICOM Import'; dicom.val = {data root outdir convopts}; dicom.help = {'DICOM Conversion. Most scanners produce data in DICOM format. This routine attempts to convert DICOM files into SPM compatible image volumes, which are written into the current directory by default. Note that not all flavours of DICOM can be handled, as DICOM is a very complicated format, and some scanner manufacturers use their own fields, which are not in the official documentation at http://medical.nema.org/'}; dicom.prog = @spm_run_dicom; dicom.vout = @vout; % --------------------------------------------------------------------- % --------------------------------------------------------------------- function dep = vout(job) dep = cfg_dep; dep.sname = 'Converted Images'; dep.src_output = substruct('.','files'); dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_mfx.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_mfx.m
7,440
utf_8
a686fb62a68adf0ecfec1bc72c9e10de
function mfx = spm_cfg_mfx % SPM Configuration file for MFX %______________________________________________________________________ % Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id: spm_cfg_mfx.m 4023 2010-07-28 18:41:36Z guillaume $ % --------------------------------------------------------------------- % dir Directory % --------------------------------------------------------------------- dir = cfg_files; dir.tag = 'dir'; dir.name = 'Directory'; dir.help = {'Select a directory where the SPM.mat file containing the specified design matrix will be written.'}; dir.filter = 'dir'; dir.ufilter = '.*'; dir.num = [1 1]; % --------------------------------------------------------------------- % spmmat Select SPM.mat % --------------------------------------------------------------------- spmmat = cfg_files; spmmat.tag = 'spmmat'; spmmat.name = 'Select SPM.mat files'; spmmat.help = {... 'Select the SPM.mat files that contains first-level designs.' 'They must have the same number of parameters for each session.' ['These are assumed to represent session-specific realisations of ' ... '2nd-level effects.']}; spmmat.filter = 'mat'; spmmat.ufilter = '^SPM\.mat$'; spmmat.num = [1 Inf]; % --------------------------------------------------------------------- % ffx Create first-level design % --------------------------------------------------------------------- ffx = cfg_exbranch; ffx.tag = 'ffx'; ffx.name = 'Create repeated-measure design'; ffx.val = {dir spmmat}; ffx.help = {'Create repeated-measure multi-session first-level design'}; ffx.prog = @spm_local_ffx; ffx.vout = @vout_ffx; % --------------------------------------------------------------------- % spmmat Select SPM.mat % --------------------------------------------------------------------- spmmat = cfg_files; spmmat.tag = 'spmmat'; spmmat.name = 'Select SPM.mat'; spmmat.help = {... 'Design and estimation structure after a 1st-level analysis'}; spmmat.filter = 'mat'; spmmat.ufilter = '^SPM\.mat$'; spmmat.num = [1 1]; % --------------------------------------------------------------------- % spec MFX Specification % --------------------------------------------------------------------- spec = cfg_exbranch; spec.tag = 'spec'; spec.name = 'MFX Specification'; spec.val = {spmmat}; spec.help = {'MFX Specification'}; spec.prog = @spm_local_mfx; spec.vout = @vout_mfx; % --------------------------------------------------------------------- % mfx Mixed-effects (MFX) analysis % --------------------------------------------------------------------- mfx = cfg_choice; mfx.tag = 'mfx'; mfx.name = 'Mixed-effects (MFX) analysis'; mfx.help = {'Mixed-effects (MFX) analysis'}; mfx.values = {ffx spec}; % ===================================================================== function out = spm_local_ffx(job) spmmat = job.spmmat; SPMS = cell(size(spmmat)); for i=1:numel(spmmat) load(spmmat{i},'SPM'); SPMS{i} = SPM; end matlabbatch{1}.spm.stats.fmri_spec.dir = cellstr(job.dir); matlabbatch{1}.spm.stats.fmri_spec.timing.units = SPMS{1}.xBF.UNITS; matlabbatch{1}.spm.stats.fmri_spec.timing.RT = SPMS{1}.xY.RT; matlabbatch{1}.spm.stats.fmri_spec.timing.fmri_t = SPMS{1}.xBF.T; matlabbatch{1}.spm.stats.fmri_spec.timing.fmri_t0 = SPMS{1}.xBF.T0; switch SPMS{1}.xBF.name case 'hrf' matlabbatch{1}.spm.stats.fmri_spec.hrf.derivs = [0 0]; case 'hrf (with time derivative)' matlabbatch{1}.spm.stats.fmri_spec.hrf.derivs = [1 0]; case 'hrf (with time and dispersion derivatives)' matlabbatch{1}.spm.stats.fmri_spec.hrf.derivs = [1 1]; case 'Fourier set' matlabbatch{1}.spm.stats.fmri_spec.bases.fourier.length = SPMS{1}.xBF.length; matlabbatch{1}.spm.stats.fmri_spec.bases.fourier.order = SPMS{1}.xBF.order; case 'Fourier set (Hanning)' matlabbatch{1}.spm.stats.fmri_spec.bases.fourier_han.length = SPMS{1}.xBF.length; matlabbatch{1}.spm.stats.fmri_spec.bases.fourier_han.order = SPMS{1}.xBF.order; case 'Gamma functions' matlabbatch{1}.spm.stats.fmri_spec.bases.gamma.length = SPMS{1}.xBF.length; matlabbatch{1}.spm.stats.fmri_spec.bases.gamma.order = SPMS{1}.xBF.order; case 'Finite Impulse Response' matlabbatch{1}.spm.stats.fmri_spec.bases.fir.length = SPMS{1}.xBF.length; matlabbatch{1}.spm.stats.fmri_spec.bases.fir.order = SPMS{1}.xBF.order; end matlabbatch{1}.spm.stats.fmri_spec.volt = SPMS{1}.xBF.Volterra; matlabbatch{1}.spm.stats.fmri_spec.global = SPMS{1}.xGX.iGXcalc; if ~isempty(SPMS{1}.xM.VM) matlabbatch{1}.spm.stats.fmri_spec.mask = cellstr(SPMS{1}.xM.VM.fname); % can be intersection end if strncmp('AR',SPMS{1}.xVi.form,2) matlabbatch{1}.spm.stats.fmri_spec.cvi = 'AR(1)'; else matlabbatch{1}.spm.stats.fmri_spec.cvi = 'none'; end k = 1; for i=1:numel(SPMS) n = cumsum([1 SPMS{i}.nscan]); for j=1:numel(SPMS{i}.Sess) matlabbatch{1}.spm.stats.fmri_spec.sess(k).scans = cellstr(SPMS{i}.xY.P(n(j):n(j+1)-1,:)); for l=1:numel(SPMS{i}.Sess(j).U) matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).name = SPMS{i}.Sess(j).U(l).name{1}; matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).onset = SPMS{i}.Sess(j).U(l).ons; matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).duration = SPMS{i}.Sess(j).U(l).dur; o = 1; for m=1:numel(SPMS{i}.Sess(j).U(l).P) switch SPMS{i}.Sess(j).U(l).P(m).name case 'time' matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).tmod = SPMS{i}.Sess(j).U(l).P(m).h; case 'none' otherwise matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).pmod(o).name = SPMS{i}.Sess(j).U(l).P(m).name; matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).pmod(o).param = SPMS{i}.Sess(j).U(l).P(m).P; matlabbatch{1}.spm.stats.fmri_spec.sess(k).cond(l).pmod(o).poly = SPMS{i}.Sess(j).U(l).P(m).h; o = o + 1; end end end for l=1:numel(SPMS{i}.Sess(j).C.name) matlabbatch{1}.spm.stats.fmri_spec.sess(k).regress(l).name = SPMS{i}.Sess(j).C.name{l}; matlabbatch{1}.spm.stats.fmri_spec.sess(k).regress(l).val = SPMS{i}.Sess(j).C.C(:,l); end matlabbatch{1}.spm.stats.fmri_spec.sess(k).hpf = SPMS{i}.xX.K(j).HParam; k = k + 1; end end spm_jobman('run',matlabbatch); out.spmmat{1} = fullfile(job.dir{1},'SPM.mat'); % ===================================================================== function dep = vout_ffx(job) dep = cfg_dep; dep.sname = 'SPM.mat File'; dep.src_output = substruct('.','spmmat'); dep.tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); % ===================================================================== function out = spm_local_mfx(job) load(job.spmmat{1},'SPM'); spm_mfx(SPM); out.spmmat{1} = fullfile(fileparts(job.spmmat{1}),'mfx','SPM.mat'); % ===================================================================== function dep = vout_mfx(job) dep = cfg_dep; dep.sname = 'SPM.mat File'; dep.src_output = substruct('.','spmmat'); dep.tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_factorial_design.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_factorial_design.m
50,375
utf_8
ecbb87ccd5528ba75b6b9a85758a9c3b
function factorial_design = spm_cfg_factorial_design % SPM Configuration file for 2nd-level models %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Will Penny % $Id: spm_cfg_factorial_design.m 3900 2010-05-25 16:17:13Z guillaume $ % --------------------------------------------------------------------- % dir Directory % --------------------------------------------------------------------- dir = cfg_files; dir.tag = 'dir'; dir.name = 'Directory'; dir.help = {'Select a directory where the SPM.mat file containing the specified design matrix will be written.'}; dir.filter = 'dir'; dir.ufilter = '.*'; dir.num = [1 1]; % --------------------------------------------------------------------- % scans Scans % --------------------------------------------------------------------- scans = cfg_files; scans.tag = 'scans'; scans.name = 'Scans'; scans.help = {'Select the images. They must all have the same image dimensions, orientation, voxel size etc.'}; scans.filter = 'image'; scans.ufilter = '.*'; scans.num = [1 Inf]; % --------------------------------------------------------------------- % t1 One-sample t-test % --------------------------------------------------------------------- t1 = cfg_branch; t1.tag = 't1'; t1.name = 'One-sample t-test'; t1.val = {scans }; t1.help = {''}; % --------------------------------------------------------------------- % scans1 Group 1 scans % --------------------------------------------------------------------- scans1 = cfg_files; scans1.tag = 'scans1'; scans1.name = 'Group 1 scans'; scans1.help = {'Select the images from sample 1. They must all have the same image dimensions, orientation, voxel size etc.'}; scans1.filter = 'image'; scans1.ufilter = '.*'; scans1.num = [1 Inf]; % --------------------------------------------------------------------- % scans2 Group 2 scans % --------------------------------------------------------------------- scans2 = cfg_files; scans2.tag = 'scans2'; scans2.name = 'Group 2 scans'; scans2.help = {'Select the images from sample 2. They must all have the same image dimensions, orientation, voxel size etc.'}; scans2.filter = 'image'; scans2.ufilter = '.*'; scans2.num = [1 Inf]; % --------------------------------------------------------------------- % dept Independence % --------------------------------------------------------------------- dept = cfg_menu; dept.tag = 'dept'; dept.name = 'Independence'; dept.help = { 'By default, the measurements are assumed to be independent between levels. ' '' 'If you change this option to allow for dependencies, this will violate the assumption of sphericity. It would therefore be an example of non-sphericity. One such example would be where you had repeated measurements from the same subjects - it may then be the case that, over subjects, measure 1 is correlated to measure 2. ' '' 'Restricted Maximum Likelihood (REML): The ensuing covariance components will be estimated using ReML in spm_spm (assuming the same for all responsive voxels) and used to adjust the statistics and degrees of freedom during inference. By default spm_spm will use weighted least squares to produce Gauss-Markov or Maximum likelihood estimators using the non-sphericity structure specified at this stage. The components will be found in SPM.xVi and enter the estimation procedure exactly as the serial correlations in fMRI models.' '' }'; dept.labels = { 'Yes' 'No' }'; dept.values = {0 1}; dept.val = {0}; % --------------------------------------------------------------------- % deptn Independence (default is 'No') % --------------------------------------------------------------------- deptn = cfg_menu; deptn.tag = 'dept'; deptn.name = 'Independence'; deptn.help = { 'By default, the measurements are assumed to be dependent between levels. ' '' 'If you change this option to allow for dependencies, this will violate the assumption of sphericity. It would therefore be an example of non-sphericity. One such example would be where you had repeated measurements from the same subjects - it may then be the case that, over subjects, measure 1 is correlated to measure 2. ' '' 'Restricted Maximum Likelihood (REML): The ensuing covariance components will be estimated using ReML in spm_spm (assuming the same for all responsive voxels) and used to adjust the statistics and degrees of freedom during inference. By default spm_spm will use weighted least squares to produce Gauss-Markov or Maximum likelihood estimators using the non-sphericity structure specified at this stage. The components will be found in SPM.xVi and enter the estimation procedure exactly as the serial correlations in fMRI models.' '' }'; deptn.labels = { 'Yes' 'No' }'; deptn.values = {0 1}; deptn.val = {1}; % --------------------------------------------------------------------- % variance Variance % --------------------------------------------------------------------- variance = cfg_menu; variance.tag = 'variance'; variance.name = 'Variance'; variance.help = { 'By default, the measurements in each level are assumed to have unequal variance. ' '' 'This violates the assumption of ''sphericity'' and is therefore an example of ''non-sphericity''.' '' 'This can occur, for example, in a 2nd-level analysis of variance, one contrast may be scaled differently from another. Another example would be the comparison of qualitatively different dependent variables (e.g. normals vs. patients). Different variances (heteroscedasticy) induce different error covariance components that are estimated using restricted maximum likelihood (see below).' '' 'Restricted Maximum Likelihood (REML): The ensuing covariance components will be estimated using ReML in spm_spm (assuming the same for all responsive voxels) and used to adjust the statistics and degrees of freedom during inference. By default spm_spm will use weighted least squares to produce Gauss-Markov or Maximum likelihood estimators using the non-sphericity structure specified at this stage. The components will be found in SPM.xVi and enter the estimation procedure exactly as the serial correlations in fMRI models.' '' }'; variance.labels = { 'Equal' 'Unequal' }'; variance.values = {0 1}; variance.val = {1}; % --------------------------------------------------------------------- % gmsca Grand mean scaling % --------------------------------------------------------------------- gmsca = cfg_menu; gmsca.tag = 'gmsca'; gmsca.name = 'Grand mean scaling'; gmsca.help = { 'This option is only used for PET data.' '' 'Selecting YES will specify ''grand mean scaling by factor'' which could be eg. ''grand mean scaling by subject'' if the factor is ''subject''. ' '' 'Since differences between subjects may be due to gain and sensitivity effects, AnCova by subject could be combined with "grand mean scaling by subject" to obtain a combination of between subject proportional scaling and within subject AnCova. ' '' }'; gmsca.labels = { 'No' 'Yes' }'; gmsca.values = {0 1}; gmsca.val = {0}; % --------------------------------------------------------------------- % ancova ANCOVA % --------------------------------------------------------------------- ancova = cfg_menu; ancova.tag = 'ancova'; ancova.name = 'ANCOVA'; ancova.help = { 'This option is only used for PET data.' '' 'Selecting YES will specify ''ANCOVA-by-factor'' regressors. This includes eg. ''Ancova by subject'' or ''Ancova by effect''. These options allow eg. different subjects to have different relationships between local and global measurements. ' '' }'; ancova.labels = { 'No' 'Yes' }'; ancova.values = {0 1}; ancova.val = {0}; % --------------------------------------------------------------------- % t2 Two-sample t-test % --------------------------------------------------------------------- t2 = cfg_branch; t2.tag = 't2'; t2.name = 'Two-sample t-test'; t2.val = {scans1 scans2 dept variance gmsca ancova }; t2.help = {''}; % --------------------------------------------------------------------- % scans Scans [1,2] % --------------------------------------------------------------------- scans = cfg_files; scans.tag = 'scans'; scans.name = 'Scans [1,2]'; scans.help = {'Select the pair of images. '}; scans.filter = 'image'; scans.ufilter = '.*'; scans.num = [2 2]; % --------------------------------------------------------------------- % pair Pair % --------------------------------------------------------------------- pair = cfg_branch; pair.tag = 'pair'; pair.name = 'Pair'; pair.val = {scans }; pair.help = {'Add a new pair of scans to your experimental design'}; % --------------------------------------------------------------------- % generic Pairs % --------------------------------------------------------------------- generic = cfg_repeat; generic.tag = 'generic'; generic.name = 'Pairs'; generic.help = {''}; generic.values = {pair}; generic.num = [1 Inf]; % --------------------------------------------------------------------- % pt Paired t-test % --------------------------------------------------------------------- pt = cfg_branch; pt.tag = 'pt'; pt.name = 'Paired t-test'; pt.val = {generic gmsca ancova}; pt.help = {''}; % --------------------------------------------------------------------- % scans Scans % --------------------------------------------------------------------- scans = cfg_files; scans.tag = 'scans'; scans.name = 'Scans'; scans.help = {'Select the images. They must all have the same image dimensions, orientation, voxel size etc.'}; scans.filter = 'image'; scans.ufilter = '.*'; scans.num = [1 Inf]; % --------------------------------------------------------------------- % c Vector % --------------------------------------------------------------------- c = cfg_entry; c.tag = 'c'; c.name = 'Vector'; c.help = {'Vector of covariate values'}; c.strtype = 'e'; c.num = [Inf 1]; % --------------------------------------------------------------------- % cname Name % --------------------------------------------------------------------- cname = cfg_entry; cname.tag = 'cname'; cname.name = 'Name'; cname.help = {'Name of covariate'}; cname.strtype = 's'; cname.num = [1 Inf]; % --------------------------------------------------------------------- % iCC Centering % --------------------------------------------------------------------- iCC = cfg_menu; iCC.tag = 'iCC'; iCC.name = 'Centering'; iCC.help = {''}; iCC.labels = { 'Overall mean' 'No centering' }'; iCC.values = {1 5}; iCC.val = {1}; % --------------------------------------------------------------------- % mcov Covariate % --------------------------------------------------------------------- mcov = cfg_branch; mcov.tag = 'mcov'; mcov.name = 'Covariate'; mcov.val = {c cname iCC }; mcov.help = {'Add a new covariate to your experimental design'}; % --------------------------------------------------------------------- % generic Covariates % --------------------------------------------------------------------- generic = cfg_repeat; generic.tag = 'generic'; generic.name = 'Covariates'; generic.help = {'Covariates'}; generic.values = {mcov }; generic.num = [0 Inf]; % --------------------------------------------------------------------- % incint Intercept % --------------------------------------------------------------------- incint = cfg_menu; incint.tag = 'incint'; incint.name = 'Intercept'; incint.help = {['By default, an intercept is always added to the model. If the ',... 'covariates supplied by the user include a constant effect, the ',... 'intercept may be omitted.']}; incint.labels = {'Include Intercept','Omit Intercept'}; incint.values = {1,0}; incint.val = {1}; % --------------------------------------------------------------------- % mreg Multiple regression % --------------------------------------------------------------------- mreg = cfg_branch; mreg.tag = 'mreg'; mreg.name = 'Multiple regression'; mreg.val = {scans generic incint}; mreg.help = {''}; % --------------------------------------------------------------------- % name Name % --------------------------------------------------------------------- name = cfg_entry; name.tag = 'name'; name.name = 'Name'; name.help = {'Name of factor, eg. ''Repetition'' '}; name.strtype = 's'; name.num = [1 Inf]; % --------------------------------------------------------------------- % levels Levels % --------------------------------------------------------------------- levels = cfg_entry; levels.tag = 'levels'; levels.name = 'Levels'; levels.help = {'Enter number of levels for this factor, eg. 2'}; levels.strtype = 'e'; levels.num = [Inf 1]; % --------------------------------------------------------------------- % fact Factor % --------------------------------------------------------------------- fact = cfg_branch; fact.tag = 'fact'; fact.name = 'Factor'; fact.val = {name levels dept variance gmsca ancova }; fact.help = {'Add a new factor to your experimental design'}; % --------------------------------------------------------------------- % generic Factors % --------------------------------------------------------------------- generic = cfg_repeat; generic.tag = 'generic'; generic.name = 'Factors'; generic.help = { 'Specify your design a factor at a time. ' '' }'; generic.values = {fact }; generic.num = [1 Inf]; % --------------------------------------------------------------------- % levels Levels % --------------------------------------------------------------------- levels = cfg_entry; levels.tag = 'levels'; levels.name = 'Levels'; levels.help = { 'Enter a vector or scalar that specifies which cell in the factorial design these images belong to. The length of this vector should correspond to the number of factors in the design' '' 'For example, length 2 vectors should be used for two-factor designs eg. the vector [2 3] specifies the cell corresponding to the 2nd-level of the first factor and the 3rd level of the 2nd factor.' '' }'; levels.strtype = 'e'; levels.num = [Inf 1]; % --------------------------------------------------------------------- % scans Scans % --------------------------------------------------------------------- scans = cfg_files; scans.tag = 'scans'; scans.name = 'Scans'; scans.help = {'Select the images for this cell. They must all have the same image dimensions, orientation, voxel size etc.'}; scans.filter = 'image'; scans.ufilter = '.*'; scans.num = [1 Inf]; % --------------------------------------------------------------------- % icell Cell % --------------------------------------------------------------------- icell = cfg_branch; icell.tag = 'icell'; icell.name = 'Cell'; icell.val = {levels scans }; icell.help = {'Enter data for a cell in your design'}; % --------------------------------------------------------------------- % scell Cell % --------------------------------------------------------------------- scell = cfg_branch; scell.tag = 'icell'; scell.name = 'Cell'; scell.val = {scans }; scell.help = {'Enter data for a cell in your design'}; % --------------------------------------------------------------------- % generic Specify cells % --------------------------------------------------------------------- generic1 = cfg_repeat; generic1.tag = 'generic'; generic1.name = 'Specify cells'; generic1.help = { 'Enter the scans a cell at a time' '' }'; generic1.values = {icell }; generic1.num = [1 Inf]; % --------------------------------------------------------------------- % generic Specify cells % --------------------------------------------------------------------- generic2 = cfg_repeat; generic2.tag = 'generic'; generic2.name = 'Specify cells'; generic2.help = { 'Enter the scans a cell at a time' '' }'; generic2.values = {scell }; generic2.num = [1 Inf]; % --------------------------------------------------------------------- % anova ANOVA % --------------------------------------------------------------------- anova = cfg_branch; anova.tag = 'anova'; anova.name = 'One-way ANOVA'; anova.val = {generic2 dept variance gmsca ancova}; anova.help = { 'One-way Analysis of Variance (ANOVA)' }'; % --------------------------------------------------------------------- % fd Full factorial % --------------------------------------------------------------------- fd = cfg_branch; fd.tag = 'fd'; fd.name = 'Full factorial'; fd.val = {generic generic1 }; fd.help = { 'This option is best used when you wish to test for all main effects and interactions in one-way, two-way or three-way ANOVAs. Design specification proceeds in 2 stages. Firstly, by creating new factors and specifying the number of levels and name for each. Nonsphericity, ANOVA-by-factor and scaling options can also be specified at this stage. Secondly, scans are assigned separately to each cell. This accomodates unbalanced designs.' '' 'For example, if you wish to test for a main effect in the population from which your subjects are drawn and have modelled that effect at the first level using K basis functions (eg. K=3 informed basis functions) you can use a one-way ANOVA with K-levels. Create a single factor with K levels and then assign the data to each cell eg. canonical, temporal derivative and dispersion derivative cells, where each cell is assigned scans from multiple subjects.' '' 'SPM will also automatically generate the contrasts necessary to test for all main effects and interactions. ' '' }'; % --------------------------------------------------------------------- % name Name % --------------------------------------------------------------------- name = cfg_entry; name.tag = 'name'; name.name = 'Name'; name.help = {'Name of factor, eg. ''Repetition'' '}; name.strtype = 's'; name.num = [1 Inf]; % --------------------------------------------------------------------- % fac Factor % --------------------------------------------------------------------- fac = cfg_branch; fac.tag = 'fac'; fac.name = 'Factor'; fac.val = {name dept variance gmsca ancova }; fac.help = { 'Add a new factor to your design.' '' 'If you are using the ''Subjects'' option to specify your scans and conditions, you may wish to make use of the following facility. There are two reserved words for the names of factors. These are ''subject'' and ''repl'' (standing for replication). If you use these factor names then SPM can automatically create replication and/or subject factors without you having to type in an extra entry in the condition vector.' '' 'For example, if you wish to model Subject and Task effects (two factors), under Subjects->Subject->Conditions you can type in simply [1 2 1 2] to specify eg. just the ''Task'' factor level. You do not need to eg. for the 4th subject enter the matrix [1 4; 2 4; 1 4; 2 4]. ' '' }'; % --------------------------------------------------------------------- % generic Factors % --------------------------------------------------------------------- generic = cfg_repeat; generic.tag = 'generic'; generic.name = 'Factors'; generic.help = { 'Specify your design a factor at a time.' '' }'; generic.values = {fac }; generic.num = [1 Inf]; % --------------------------------------------------------------------- % scans Scans % --------------------------------------------------------------------- scans = cfg_files; scans.tag = 'scans'; scans.name = 'Scans'; scans.help = {'Select the images to be analysed. They must all have the same image dimensions, orientation, voxel size etc.'}; scans.filter = 'image'; scans.ufilter = '.*'; scans.num = [1 Inf]; % --------------------------------------------------------------------- % conds Conditions % --------------------------------------------------------------------- conds = cfg_entry; conds.tag = 'conds'; conds.name = 'Conditions'; conds.help = {''}; conds.strtype = 'e'; conds.num = [Inf Inf]; % --------------------------------------------------------------------- % fsubject Subject % --------------------------------------------------------------------- fsubject = cfg_branch; fsubject.tag = 'fsubject'; fsubject.name = 'Subject'; fsubject.val = {scans conds }; fsubject.help = {'Enter data and conditions for a new subject'}; % --------------------------------------------------------------------- % generic Subjects % --------------------------------------------------------------------- generic1 = cfg_repeat; generic1.tag = 'generic'; generic1.name = 'Subjects'; generic1.help = {''}; generic1.values = {fsubject }; generic1.num = [1 Inf]; % --------------------------------------------------------------------- % scans Scans % --------------------------------------------------------------------- scans = cfg_files; scans.tag = 'scans'; scans.name = 'Scans'; scans.help = {'Select the images to be analysed. They must all have the same image dimensions, orientation, voxel size etc.'}; scans.filter = 'image'; scans.ufilter = '.*'; scans.num = [1 Inf]; % --------------------------------------------------------------------- % imatrix Factor matrix % --------------------------------------------------------------------- imatrix = cfg_entry; imatrix.tag = 'imatrix'; imatrix.name = 'Factor matrix'; imatrix.help = {'Specify factor/level matrix as a nscan-by-4 matrix. Note that the first column of I is reserved for the internal replication factor and must not be used for experimental factors.'}; imatrix.strtype = 'e'; imatrix.num = [Inf Inf]; % --------------------------------------------------------------------- % specall Specify all % --------------------------------------------------------------------- specall = cfg_branch; specall.tag = 'specall'; specall.name = 'Specify all'; specall.val = {scans imatrix }; specall.help = { 'Specify (i) all scans in one go and (ii) all conditions using a factor matrix, I. This option is for ''power users''. The matrix I must have four columns and as as many rows as scans. It has the same format as SPM''s internal variable SPM.xX.I. ' '' 'The first column of I denotes the replication number and entries in the other columns denote the levels of each experimental factor.' '' 'So, for eg. a two-factor design the first column denotes the replication number and columns two and three have entries like 2 3 denoting the 2nd level of the first factor and 3rd level of the second factor. The 4th column in I would contain all 1s.' }'; % --------------------------------------------------------------------- % fsuball Specify Subjects or all Scans & Factors % --------------------------------------------------------------------- fsuball = cfg_choice; fsuball.tag = 'fsuball'; fsuball.name = 'Specify Subjects or all Scans & Factors'; fsuball.val = {generic1 }; fsuball.help = {''}; fsuball.values = {generic1 specall }; % --------------------------------------------------------------------- % fnum Factor number % --------------------------------------------------------------------- fnum = cfg_entry; fnum.tag = 'fnum'; fnum.name = 'Factor number'; fnum.help = {'Enter the number of the factor.'}; fnum.strtype = 'e'; fnum.num = [1 1]; % --------------------------------------------------------------------- % fmain Main effect % --------------------------------------------------------------------- fmain = cfg_branch; fmain.tag = 'fmain'; fmain.name = 'Main effect'; fmain.val = {fnum }; fmain.help = {'Add a main effect to your design matrix'}; % --------------------------------------------------------------------- % fnums Factor numbers % --------------------------------------------------------------------- fnums = cfg_entry; fnums.tag = 'fnums'; fnums.name = 'Factor numbers'; fnums.help = {'Enter the numbers of the factors of this (two-way) interaction.'}; fnums.strtype = 'e'; fnums.num = [2 1]; % --------------------------------------------------------------------- % inter Interaction % --------------------------------------------------------------------- inter = cfg_branch; inter.tag = 'inter'; inter.name = 'Interaction'; inter.val = {fnums }; inter.help = {'Add an interaction to your design matrix'}; % --------------------------------------------------------------------- % maininters Main effects & Interactions % --------------------------------------------------------------------- maininters = cfg_repeat; maininters.tag = 'maininters'; maininters.name = 'Main effects & Interactions'; maininters.help = {''}; maininters.values = {fmain inter }; maininters.num = [1 Inf]; % --------------------------------------------------------------------- % anovaw ANOVA within subject % --------------------------------------------------------------------- anovaw = cfg_branch; anovaw.tag = 'anovaw'; anovaw.name = 'One-way ANOVA - within subject'; anovaw.val = {generic1 deptn variance gmsca ancova}; anovaw.help = { 'One-way Analysis of Variance (ANOVA) - within subject' }'; % --------------------------------------------------------------------- % fblock Flexible factorial % --------------------------------------------------------------------- fblock = cfg_branch; fblock.tag = 'fblock'; fblock.name = 'Flexible factorial'; fblock.val = {generic fsuball maininters }; fblock.help = { 'Create a design matrix a block at a time by specifying which main effects and interactions you wish to be included.' '' 'This option is best used for one-way, two-way or three-way ANOVAs but where you do not wish to test for all possible main effects and interactions. This is perhaps most useful for PET where there is usually not enough data to test for all possible effects. Or for 3-way ANOVAs where you do not wish to test for all of the two-way interactions. A typical example here would be a group-by-drug-by-task analysis where, perhaps, only (i) group-by-drug or (ii) group-by-task interactions are of interest. In this case it is only necessary to have two-blocks in the design matrix - one for each interaction. The three-way interaction can then be tested for using a contrast that computes the difference between (i) and (ii).' '' 'Design specification then proceeds in 3 stages. Firstly, factors are created and names specified for each. Nonsphericity, ANOVA-by-factor and scaling options can also be specified at this stage.' '' 'Secondly, a list of scans is produced along with a factor matrix, I. This is an nscan x 4 matrix of factor level indicators (see xX.I below). The first factor must be ''replication'' but the other factors can be anything. Specification of I and the scan list can be achieved in one of two ways (a) the ''Specify All'' option allows I to be typed in at the user interface or (more likely) loaded in from the matlab workspace. All of the scans are then selected in one go. (b) the ''Subjects'' option allows you to enter scans a subject at a time. The corresponding experimental conditions (ie. levels of factors) are entered at the same time. SPM will then create the factor matrix I. This style of interface is similar to that available in SPM2.' '' 'Thirdly, the design matrix is built up a block at a time. Each block can be a main effect or a (two-way) interaction. ' '' }'; % --------------------------------------------------------------------- % des Design % --------------------------------------------------------------------- des = cfg_choice; des.tag = 'des'; des.name = 'Design'; des.val = {t1 }; des.help = {''}; des.values = {t1 t2 pt mreg anova anovaw fd fblock }; % --------------------------------------------------------------------- % c Vector % --------------------------------------------------------------------- c = cfg_entry; c.tag = 'c'; c.name = 'Vector'; c.help = { 'Vector of covariate values.' 'Enter the covariate values ''''per subject'''' (i.e. all for subject 1, then all for subject 2, etc). Importantly, the ordering of the cells of a factorial design has to be the same for all subjects in order to be consistent with the ordering of the covariate values.' }'; c.strtype = 'e'; c.num = [Inf 1]; % --------------------------------------------------------------------- % cname Name % --------------------------------------------------------------------- cname = cfg_entry; cname.tag = 'cname'; cname.name = 'Name'; cname.help = {'Name of covariate'}; cname.strtype = 's'; cname.num = [1 Inf]; % --------------------------------------------------------------------- % iCFI Interactions % --------------------------------------------------------------------- iCFI = cfg_menu; iCFI.tag = 'iCFI'; iCFI.name = 'Interactions'; iCFI.help = { 'For each covariate you have defined, there is an opportunity to create an additional regressor that is the interaction between the covariate and a chosen experimental factor. ' '' }'; iCFI.labels = { 'None' 'With Factor 1' 'With Factor 2' 'With Factor 3' }'; iCFI.values = {1 2 3 4}; iCFI.val = {1}; % --------------------------------------------------------------------- % iCC Centering % --------------------------------------------------------------------- iCC = cfg_menu; iCC.tag = 'iCC'; iCC.name = 'Centering'; iCC.help = { 'The appropriate centering option is usually the one that corresponds to the interaction chosen, and ensures that main effects of the interacting factor aren''t affected by the covariate. You are advised to choose this option, unless you have other modelling considerations. ' '' }'; iCC.labels = { 'Overall mean' 'Factor 1 mean' 'Factor 2 mean' 'Factor 3 mean' 'No centering' 'User specified value' 'As implied by ANCOVA' 'GM' }'; iCC.values = {1 2 3 4 5 6 7 8}; iCC.val = {1}; % --------------------------------------------------------------------- % cov Covariate % --------------------------------------------------------------------- cov = cfg_branch; cov.tag = 'cov'; cov.name = 'Covariate'; cov.val = {c cname iCFI iCC }; cov.help = {'Add a new covariate to your experimental design'}; % --------------------------------------------------------------------- % generic Covariates % --------------------------------------------------------------------- generic = cfg_repeat; generic.tag = 'generic'; generic.name = 'Covariates'; generic.help = { 'This option allows for the specification of covariates and nuisance variables. Unlike SPM94/5/6, where the design was partitioned into effects of interest and nuisance effects for the computation of adjusted data and the F-statistic (which was used to thresh out voxels where there appeared to be no effects of interest), SPM does not partition the design in this way anymore. The only remaining distinction between effects of interest (including covariates) and nuisance effects is their location in the design matrix, which we have retained for continuity. Pre-specified design matrix partitions can be entered. ' '' }'; generic.values = {cov }; generic.num = [0 Inf]; % --------------------------------------------------------------------- % tm_none None % --------------------------------------------------------------------- tm_none = cfg_const; tm_none.tag = 'tm_none'; tm_none.name = 'None'; tm_none.val = {1}; tm_none.help = {'No threshold masking'}; % --------------------------------------------------------------------- % athresh Threshold % --------------------------------------------------------------------- athresh = cfg_entry; athresh.tag = 'athresh'; athresh.name = 'Threshold'; athresh.help = { 'Enter the absolute value of the threshold.' '' }'; athresh.strtype = 'e'; athresh.num = [1 1]; athresh.val = {100}; % --------------------------------------------------------------------- % tma Absolute % --------------------------------------------------------------------- tma = cfg_branch; tma.tag = 'tma'; tma.name = 'Absolute'; tma.val = {athresh }; tma.help = { 'Images are thresholded at a given value and only voxels at which all images exceed the threshold are included. ' '' 'This option allows you to specify the absolute value of the threshold.' '' }'; % --------------------------------------------------------------------- % rthresh Threshold % --------------------------------------------------------------------- rthresh = cfg_entry; rthresh.tag = 'rthresh'; rthresh.name = 'Threshold'; rthresh.help = { 'Enter the threshold as a proportion of the global value' '' }'; rthresh.strtype = 'e'; rthresh.num = [1 1]; rthresh.val = {.8}; % --------------------------------------------------------------------- % tmr Relative % --------------------------------------------------------------------- tmr = cfg_branch; tmr.tag = 'tmr'; tmr.name = 'Relative'; tmr.val = {rthresh }; tmr.help = { 'Images are thresholded at a given value and only voxels at which all images exceed the threshold are included. ' '' 'This option allows you to specify the value of the threshold as a proportion of the global value. ' '' }'; % --------------------------------------------------------------------- % tm Threshold masking % --------------------------------------------------------------------- tm = cfg_choice; tm.tag = 'tm'; tm.name = 'Threshold masking'; tm.val = {tm_none }; tm.help = { 'Images are thresholded at a given value and only voxels at which all images exceed the threshold are included. ' '' }'; tm.values = {tm_none tma tmr }; % --------------------------------------------------------------------- % im Implicit Mask % --------------------------------------------------------------------- im = cfg_menu; im.tag = 'im'; im.name = 'Implicit Mask'; im.help = { 'An "implicit mask" is a mask implied by a particular voxel value. Voxels with this mask value are excluded from the analysis. ' '' 'For image data-types with a representation of NaN (see spm_type.m), NaN''s is the implicit mask value, (and NaN''s are always masked out). ' '' 'For image data-types without a representation of NaN, zero is the mask value, and the user can choose whether zero voxels should be masked out or not.' '' 'By default, an implicit mask is used. ' '' }'; im.labels = { 'Yes' 'No' }'; im.values = {1 0}; im.val = {1}; % --------------------------------------------------------------------- % em Explicit Mask % --------------------------------------------------------------------- em = cfg_files; em.tag = 'em'; em.name = 'Explicit Mask'; em.val = {{''}}; em.help = { 'Explicit masks are other images containing (implicit) masks that are to be applied to the current analysis.' '' 'All voxels with value NaN (for image data-types with a representation of NaN), or zero (for other data types) are excluded from the analysis. ' '' 'Explicit mask images can have any orientation and voxel/image size. Nearest neighbour interpolation of a mask image is used if the voxel centers of the input images do not coincide with that of the mask image.' '' }'; em.filter = 'image'; em.ufilter = '.*'; em.num = [0 1]; % --------------------------------------------------------------------- % masking Masking % --------------------------------------------------------------------- masking = cfg_branch; masking.tag = 'masking'; masking.name = 'Masking'; masking.val = {tm im em }; masking.help = { 'The mask specifies the voxels within the image volume which are to be assessed. SPM supports three methods of masking (1) Threshold, (2) Implicit and (3) Explicit. The volume analysed is the intersection of all masks.' '' }'; % --------------------------------------------------------------------- % g_omit Omit % --------------------------------------------------------------------- g_omit = cfg_const; g_omit.tag = 'g_omit'; g_omit.name = 'Omit'; g_omit.val = {1}; g_omit.help = {'Omit'}; % --------------------------------------------------------------------- % global_uval Global values % --------------------------------------------------------------------- global_uval = cfg_entry; global_uval.tag = 'global_uval'; global_uval.name = 'Global values'; global_uval.help = { 'Enter the vector of global values' '' }'; global_uval.strtype = 'e'; global_uval.num = [Inf 1]; % --------------------------------------------------------------------- % g_user User % --------------------------------------------------------------------- g_user = cfg_branch; g_user.tag = 'g_user'; g_user.name = 'User'; g_user.val = {global_uval }; g_user.help = { 'User defined global effects (enter your own ' 'vector of global values)' }'; % --------------------------------------------------------------------- % g_mean Mean % --------------------------------------------------------------------- g_mean = cfg_const; g_mean.tag = 'g_mean'; g_mean.name = 'Mean'; g_mean.val = {1}; g_mean.help = { 'SPM standard mean voxel value' '' 'This defines the global mean via a two-step process. Firstly, the overall mean is computed. Voxels with values less than 1/8 of this value are then deemed extra-cranial and get masked out. The mean is then recomputed on the remaining voxels.' '' }'; % --------------------------------------------------------------------- % globalc Global calculation % --------------------------------------------------------------------- globalc = cfg_choice; globalc.tag = 'globalc'; globalc.name = 'Global calculation'; globalc.val = {g_omit }; globalc.help = { 'This option is only used for PET data.' '' 'There are three methods for estimating global effects (1) Omit (assumming no other options requiring the global value chosen) (2) User defined (enter your own vector of global values) (3) Mean: SPM standard mean voxel value (within per image fullmean/8 mask) ' '' }'; globalc.values = {g_omit g_user g_mean }; % --------------------------------------------------------------------- % gmsca_no No % --------------------------------------------------------------------- gmsca_no = cfg_const; gmsca_no.tag = 'gmsca_no'; gmsca_no.name = 'No'; gmsca_no.val = {1}; gmsca_no.help = {'No overall grand mean scaling'}; % --------------------------------------------------------------------- % gmscv Grand mean scaled value % --------------------------------------------------------------------- gmscv = cfg_entry; gmscv.tag = 'gmscv'; gmscv.name = 'Grand mean scaled value'; gmscv.help = { 'The default value of 50, scales the global flow to a physiologically realistic value of 50ml/dl/min.' '' }'; gmscv.strtype = 'e'; gmscv.num = [Inf 1]; gmscv.val = {50}; % --------------------------------------------------------------------- % gmsca_yes Yes % --------------------------------------------------------------------- gmsca_yes = cfg_branch; gmsca_yes.tag = 'gmsca_yes'; gmsca_yes.name = 'Yes'; gmsca_yes.val = {gmscv }; gmsca_yes.help = { 'Scaling of the overall grand mean simply scales all the data by a common factor such that the mean of all the global values is the value specified. For qualitative data, this puts the data into an intuitively accessible scale without altering the statistics. ' '' }'; % --------------------------------------------------------------------- % gmsca Overall grand mean scaling % --------------------------------------------------------------------- gmsca = cfg_choice; gmsca.tag = 'gmsca'; gmsca.name = 'Overall grand mean scaling'; gmsca.val = {gmsca_no }; gmsca.help = { 'Scaling of the overall grand mean simply scales all the data by a common factor such that the mean of all the global values is the value specified. For qualitative data, this puts the data into an intuitively accessible scale without altering the statistics. ' '' 'When proportional scaling global normalisation is used each image is separately scaled such that it''s global value is that specified (in which case the grand mean is also implicitly scaled to that value). So, to proportionally scale each image so that its global value is eg. 20, select <Yes> then type in 20 for the grand mean scaled value.' '' 'When using AnCova or no global normalisation, with data from different subjects or sessions, an intermediate situation may be appropriate, and you may be given the option to scale group, session or subject grand means separately. ' '' }'; gmsca.values = {gmsca_no gmsca_yes }; % --------------------------------------------------------------------- % glonorm Normalisation % --------------------------------------------------------------------- glonorm = cfg_menu; glonorm.tag = 'glonorm'; glonorm.name = 'Normalisation'; glonorm.help = { 'Global nuisance effects are usually accounted for either by scaling the images so that they all have the same global value (proportional scaling), or by including the global covariate as a nuisance effect in the general linear model (AnCova). Much has been written on which to use, and when. Basically, since proportional scaling also scales the variance term, it is appropriate for situations where the global measurement predominantly reflects gain or sensitivity. Where variance is constant across the range of global values, linear modelling in an AnCova approach has more flexibility, since the model is not restricted to a simple proportional regression. ' '' '''Ancova by subject'' or ''Ancova by effect'' options are implemented using the ANCOVA options provided where each experimental factor (eg. subject or effect), is defined. These allow eg. different subjects to have different relationships between local and global measurements. ' '' 'Since differences between subjects may be due to gain and sensitivity effects, AnCova by subject could be combined with "grand mean scaling by subject" (an option also provided where each experimental factor is originally defined) to obtain a combination of between subject proportional scaling and within subject AnCova. ' '' }'; glonorm.labels = { 'None' 'Proportional' 'ANCOVA' }'; glonorm.values = {1 2 3}; glonorm.val = {1}; % --------------------------------------------------------------------- % globalm Global normalisation % --------------------------------------------------------------------- globalm = cfg_branch; globalm.tag = 'globalm'; globalm.name = 'Global normalisation'; globalm.val = {gmsca glonorm }; globalm.help = { 'This option is only used for PET data.' '' 'Global nuisance effects are usually accounted for either by scaling the images so that they all have the same global value (proportional scaling), or by including the global covariate as a nuisance effect in the general linear model (AnCova). Much has been written on which to use, and when. Basically, since proportional scaling also scales the variance term, it is appropriate for situations where the global measurement predominantly reflects gain or sensitivity. Where variance is constant across the range of global values, linear modelling in an AnCova approach has more flexibility, since the model is not restricted to a simple proportional regression. ' '' '''Ancova by subject'' or ''Ancova by effect'' options are implemented using the ANCOVA options provided where each experimental factor (eg. subject or effect), is defined. These allow eg. different subjects to have different relationships between local and global measurements. ' '' 'Since differences between subjects may be due to gain and sensitivity effects, AnCova by subject could be combined with "grand mean scaling by subject" (an option also provided where each experimental factor is originally defined) to obtain a combination of between subject proportional scaling and within subject AnCova. ' '' }'; % --------------------------------------------------------------------- % factorial_design Factorial design specification % --------------------------------------------------------------------- factorial_design = cfg_exbranch; factorial_design.tag = 'factorial_design'; factorial_design.name = 'Factorial design specification'; factorial_design.val = {dir des generic masking globalc globalm }; factorial_design.help = { 'This interface is used for setting up analyses of PET data. It is also used for ''2nd level'' or ''random effects'' analysis which allow one to make a population inference. First level models can be used to produce appropriate summary data, which can then be used as raw data for a second-level analysis. For example, a simple t-test on contrast images from the first-level turns out to be a random-effects analysis with random subject effects, inferring for the population based on a particular sample of subjects.' '' 'This interface configures the design matrix, describing the general linear model, data specification, and other parameters necessary for the statistical analysis. These parameters are saved in a configuration file (SPM.mat), which can then be passed on to spm_spm.m which estimates the design. This is achieved by pressing the ''Estimate'' button. Inference on these estimated parameters is then handled by the SPM results section. ' '' 'A separate interface handles design configuration for fMRI time series.' '' 'Various data and parameters need to be supplied to specify the design (1) the image files, (2) indicators of the corresponding condition/subject/group (2) any covariates, nuisance variables, or design matrix partitions (3) the type of global normalisation (if any) (4) grand mean scaling options (5) thresholds and masks defining the image volume to analyse. The interface supports a comprehensive range of options for all these parameters.' '' }'; factorial_design.prog = @spm_run_factorial_design; factorial_design.vout = @vout_stats; %------------------------------------------------------------------------- %------------------------------------------------------------------------- function dep = vout_stats(job) dep(1) = cfg_dep; dep(1).sname = 'SPM.mat File'; dep(1).src_output = substruct('.','spmmat'); dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); %dep(2) = cfg_dep; %dep(2).sname = 'SPM Variable'; %dep(2).src_output = substruct('.','spmvar'); %dep(2).tgt_spec = cfg_findspec({{'strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_con.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_con.m
33,800
utf_8
79fe74a6a2a79a4f4215918ab982042d
function con = spm_cfg_con % SPM Configuration file for contrast specification %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_con.m 3993 2010-07-13 11:59:32Z volkmar $ rev = '$Rev: 3993 $'; % --------------------------------------------------------------------- % spmmat Select SPM.mat % --------------------------------------------------------------------- spmmat = cfg_files; spmmat.tag = 'spmmat'; spmmat.name = 'Select SPM.mat'; spmmat.help = {'Select SPM.mat file for contrasts'}; spmmat.filter = 'mat'; spmmat.ufilter = '^SPM\.mat$'; spmmat.num = [1 1]; % --------------------------------------------------------------------- % name Name % --------------------------------------------------------------------- name = cfg_entry; name.tag = 'name'; name.name = 'Name'; name.help = {'Name of contrast'}; name.strtype = 's'; name.num = [1 Inf]; % --------------------------------------------------------------------- % convec T contrast vector % --------------------------------------------------------------------- convec = cfg_entry; convec.tag = 'convec'; convec.name = 'T contrast vector'; convec.help = {'Enter T contrast vector. This is done similarly to the contrast manager. A 1 x n vector should be entered for T-contrasts.'}; convec.strtype = 'e'; convec.num = [1 Inf]; % --------------------------------------------------------------------- % sessrep Replicate over sessions % --------------------------------------------------------------------- sessrep = cfg_menu; sessrep.tag = 'sessrep'; sessrep.name = 'Replicate over sessions'; sessrep.val = {'none'}; sessrep.help = { 'If there are multiple sessions with identical conditions, one might want to specify contrasts which are identical over sessions. This can be done automatically based on the contrast spec for one session.' 'Contrasts can be either replicated (thus testing average effects over sessions) or created per session. In both cases, zero padding up to the length of each session and the block effects is done automatically. In addition, weights of replicated contrasts can be scaled by the number of sessions. This allows to use the same contrast manager batch for fMRI analyses with a variable number of sessions. The scaled contrasts can then be compared in a 2nd level model without a need for further adjustment of effect sizes.' }'; sessrep.labels = { 'Don''t replicate' 'Replicate' 'Replicate&Scale' 'Create per session' 'Both: Replicate + Create per session' 'Both: Replicate&Scale + Create per session' }'; sessrep.values = { 'none' 'repl' 'replsc' 'sess' 'both' 'bothsc' }'; % --------------------------------------------------------------------- % tcon T-contrast % --------------------------------------------------------------------- tcon = cfg_branch; tcon.tag = 'tcon'; tcon.name = 'T-contrast'; tcon.val = {name convec sessrep }; tcon.help = { '* Simple one-dimensional contrasts for an SPM{T}' '' 'A simple contrast for an SPM{T} tests the null hypothesis c''B=0 against the one-sided alternative c''B>0, where c is a column vector. ' '' ' Note that throughout SPM, the transpose of the contrast weights is used for display and input. That is, you''ll enter and visualise c''. For an SPM{T} this will be a row vector.' '' 'For example, if you have a design in which the first two columns of the design matrix correspond to the effects for "baseline" and "active" conditions respectively, then a contrast with weights c''=[-1,+1,0,...] (with zero weights for any other parameters) tests the hypothesis that there is no "activation" (the parameters for both conditions are the same), against the alternative that there is some activation (i.e. the parameter for the "active" condition is greater than that for the "baseline" condition). The resulting SPM{T} (created by spm_getSPM.m) is a statistic image, with voxel values the value of the t-statistic for the specified contrast at that location. Areas of the SPM{T} with high voxel values indicate evidence for "activation". To look for areas of relative "de-activation", the inverse contrast could be used c''=[+1,-1,0,...].' '' 'Similarly, if you have a design where the third column in the design matrix is a covariate, then the corresponding parameter is essentially a regression slope, and a contrast with weights c''=[0,0,1,0,...] (with zero weights for all parameters but the third) tests the hypothesis of zero regression slope, against the alternative of a positive slope. This is equivalent to a test no correlation, against the alternative of positive correlation. If there are other terms in the model beyond a constant term and the covariate, then this correlation is apartial correlation, the correlation between the data Y and the covariate, after accounting for the other effects.' }'; % --------------------------------------------------------------------- % name Name % --------------------------------------------------------------------- name = cfg_entry; name.tag = 'name'; name.name = 'Name'; name.help = {'Name of contrast'}; name.strtype = 's'; name.num = [1 Inf]; % --------------------------------------------------------------------- % convec F contrast vector % --------------------------------------------------------------------- convec = cfg_entry; convec.tag = 'convec'; convec.name = 'F contrast vector'; convec.help = {'Enter F contrast vector. This is done similarly to the contrast manager. One or multiline contrasts may be entered.'}; convec.strtype = 'e'; convec.num = [Inf Inf]; % --------------------------------------------------------------------- % generic Contrast vectors % --------------------------------------------------------------------- generic = cfg_repeat; generic.tag = 'generic'; generic.name = 'Contrast vectors'; generic.help = {'F contrasts are defined by a series of vectors.'}; generic.values = {convec }; generic.num = [1 Inf]; % --------------------------------------------------------------------- % sessrep Replicate over sessions % --------------------------------------------------------------------- sessrep = cfg_menu; sessrep.tag = 'sessrep'; sessrep.name = 'Replicate over sessions'; sessrep.val = {'none'}; sessrep.help = { 'If there are multiple sessions with identical conditions, one might want to specify contrasts which are identical over sessions. This can be done automatically based on the contrast spec for one session.' 'Contrasts can be either replicated (either testing average effects over sessions or per-session/condition effects) or created per session. In both cases, zero padding up to the length of each session and the block effects is done automatically.' }'; sessrep.labels = { 'Don''t replicate' 'Replicate (average over sessions)' 'Replicate (no averaging)' 'Create per session' 'Both - ''Per session'' and ''Replicate (average over sessions)''' }'; sessrep.values = { 'none' 'repl' 'replna' 'sess' 'both' }'; % --------------------------------------------------------------------- % fcon F-contrast % --------------------------------------------------------------------- fcon = cfg_branch; fcon.tag = 'fcon'; fcon.name = 'F-contrast'; fcon.val = {name generic sessrep }; fcon.help = { '* Linear constraining matrices for an SPM{F}' '' 'The null hypothesis c''B=0 can be thought of as a (linear) constraint on the full model under consideration, yielding a reduced model. Taken from the viewpoint of two designs, with the full model an extension of the reduced model, the null hypothesis is that the additional terms in the full model are redundent.' '' 'Statistical inference proceeds by comparing the additional variance explained by full design over and above the reduced design to the error variance (of the full design), an "Extra Sum-of-Squares" approach yielding an F-statistic for each voxel, whence an SPM{F}.' '' 'This is useful in a number of situations:' '' '* Two sided tests' '' 'The simplest use of F-contrasts is to effect a two-sided test of a simple linear contrast c''B, where c is a column vector. The SPM{F} is the square of the corresponding SPM{T}. High values of the SPM{F} therefore indicate evidence against the null hypothesis c''B=0 in favour of the two-sided alternative c''B~=0.' '' '* General linear hypotheses' '' 'Where the contrast weights is a matrix, the rows of the (transposed) contrast weights matrix c'' must define contrasts in their own right, and the test is effectively simultaneously testing the null hypotheses associated with the individual component contrasts with weights defined in the rows. The null hypothesis is still c''B=0, but since c is a matrix, 0 here is a zero vector rather than a scalar zero, asserting that under the null hypothesis all the component hypotheses are true.' '' 'For example: Suppose you have a language study with 3 word categories (A,B & C), and would like to test whether there is any difference at all between the three levels of the "word category" factor.' '' 'The design matrix might look something like:' '' ' [ 1 0 0 ..]' ' [ : : : ..]' ' [ 1 0 0 ..]' ' [ 0 1 0 ..]' ' X = [ : : : ..]' ' [ 0 1 0 ..]' ' [ 0 0 1 ..]' ' [ : : : ..]' ' [ 0 0 1 ..]' ' [ 0 0 0 ..]' ' [ : : : ..]' '' ' ...with the three levels of the "word category" factor modelled in the first three columns of the design matrix.' '' 'The matrix of contrast weights will look like:' '' ' c'' = [1 -1 0 ...;' ' 0 1 -1 ...]' '' 'Reading the contrasts weights in each row of c'', we see that row 1 states that category A elicits the same response as category B, row 2 that category B elicits the same response as category C, and hence together than categories A, B & C all elicit the same response.' '' 'The alternative hypothesis is simply that the three levels are not all the same, i.e. that there is some difference in the paraeters for the three levels of the factor: The first and the second categories produce different brain responses, OR the second and third categories, or both.' '' 'In other words, under the null hypothesis (the categories produce the same brain responses), the model reduces to one in which the three level "word category" factor can be replaced by a single "word" effect, since there is no difference in the parameters for each category. The corresponding design matrix would have the first three columns replaced by a single column that is the sum (across rows) of the first three columns in the design matric above, modelling the brain response to a word, whatever is the category. The F-contrast above is in fact testing the hypothesis that this reduced design doesn''t account for significantly less variance than the full design with an effect for each word category.' '' 'Another way of seeing that, is to consider a reparameterisation of the model, where the first column models effects common to all three categories, with the second and third columns modelling the differences between the three conditions, for example:' '' ' [ 1 1 0 ..]' ' [ : : : ..]' ' [ 1 1 0 ..]' ' [ 1 0 1 ..]' ' X = [ : : : ..]' ' [ 1 0 1 ..]' ' [ 1 -1 -1 ..]' ' [ : : : ..]' ' [ 1 -1 -1 ..]' ' [ 0 0 0 ..]' ' [ : : : ..]' '' 'In this case, an equivalent F contrast is of the form' ' c'' = [ 0 1 0 ...;' ' 0 0 1 ...]' 'and would be exactly equivalent to the previous contrast applied to the previous design. In this latter formulation, you are asking whewher the two columns modelling the "interaction space" account for a significant amount of variation (variance) of the data. Here the component contrasts in the rows of c'' are simply specifying that the parameters for the corresponding rows are are zero, and it is clear that the F-test is comparing this full model with a reduced model in which the second and third columns of X are omitted.' '' ' Note the difference between the following two F-contrasts:' ' c'' = [ 0 1 0 ...; (1)' ' 0 0 1 ...]' ' and' ' c'' = [ 0 1 1 ...] (2)' '' ' The first is an F-contrast, testing whether either of the parameters for the effects modelled in the 2nd & 3rd columns of the design matrix are significantly different from zero. Under the null hypothesis c''B=0, the first contrast imposes a two-dimensional constraint on the design. The second contrast tests whether the SUM of the parameters for the 2nd & 3rd columns is significantly different from zero. Under the null hypothesis c''B=0, this second contrast only imposes a one dimensional constraint on the design.' '' ' An example of the difference between the two is that the first contrast would be sensitive to the situation where the 2nd & 3rd parameters were +a and -a, for some constant a, wheras the second contrast would not detect this, since the parameters sum to zero.' '' 'The test for an effect of the factor "word category" is an F-test with 3-1=2 "dimensions", or degrees of freedom.' '' '* Testing the significance of effects modelled by multiple columns' '' 'A conceptially similar situation arises when one wonders whether a set of coufound effects are explaining any variance in the data. One important advantage of testing the with F contrasts rather than one by one using SPM{T}''s is the following. Say you have two covariates that you would like to know whether they can "predict" the brain responses, and these two are correlated (even a small correlation would be important in this instance). Testing one and then the other may lead you to conclude that there is no effect. However, testing with an F test the two covariates may very well show a not suspected effect. This is because by testing one covariate after the other, one never tests for what is COMMON to these covariates (see Andrade et al, Ambiguous results in functional neuroimaging, NeuroImage, 1999).' '' '' 'More generally, F-tests reflect the usual analysis of variance, while t-tests are traditionally post hoc tests, useful to see in which direction is an effect going (positive or negative). The introduction of F-tests can also be viewed as a first means to do model selection.' '' '' 'Technically speaking, an F-contrast defines a number of directions (as many as the rank of the contrast) in the space spanned by the column vectors of the design matrix. These directions are simply given by X*c if the vectors of X are orthogonal, if not, the space define by c is a bit more complex and takes care of the correlation within the design matrix. In essence, an F-contrast is defining a reduced model by imposing some linear constraints (that have to be estimable, see below) on the parameters estimates. Sometimes, this reduced model is simply made of a subset of the column of the original design matrix but generally, it is defined by a combination of those columns. (see spm_FcUtil for what (I hope) is an efficient handling of F-contrats computation).' }'; % --------------------------------------------------------------------- % name Name % --------------------------------------------------------------------- name = cfg_entry; name.tag = 'name'; name.name = 'Name'; name.help = {'Name of contrast'}; name.strtype = 's'; name.num = [1 Inf]; % --------------------------------------------------------------------- % conweight Contrast weight % --------------------------------------------------------------------- conweight = cfg_entry; conweight.tag = 'conweight'; conweight.name = 'Contrast weight'; conweight.help = {'The contrast weight for the selected column.'}; conweight.strtype = 'e'; conweight.num = [1 1]; % --------------------------------------------------------------------- % colcond Condition # % --------------------------------------------------------------------- colcond = cfg_entry; colcond.tag = 'colcond'; colcond.name = 'Condition #'; colcond.help = {'Select which condition function set is to be contrasted.'}; colcond.strtype = 'e'; colcond.num = [1 1]; % --------------------------------------------------------------------- % colbf Basis function # % --------------------------------------------------------------------- colbf = cfg_entry; colbf.tag = 'colbf'; colbf.name = 'Basis function #'; colbf.help = {'Select which basis function from the basis function set is to be contrasted.'}; colbf.strtype = 'e'; colbf.num = [1 1]; % --------------------------------------------------------------------- % colmod Parametric modulation # % --------------------------------------------------------------------- colmod = cfg_entry; colmod.tag = 'colmod'; colmod.name = 'Parametric modulation #'; colmod.help = {'Select which parametric modulation is to be contrasted. If there is no time/parametric modulation, enter "1". If there are both time and parametric modulations, then time modulation comes before parametric modulation.'}; colmod.strtype = 'e'; colmod.num = [1 1]; % --------------------------------------------------------------------- % colmodord Parametric modulation order % --------------------------------------------------------------------- colmodord = cfg_entry; colmodord.tag = 'colmodord'; colmodord.name = 'Parametric modulation order'; colmodord.help = { 'Order of parametric modulation to be contrasted. ' '' '0 - the basis function itself, 1 - 1st order mod etc' }'; colmodord.strtype = 'e'; colmodord.num = [1 1]; % --------------------------------------------------------------------- % colconds Contrast entry % --------------------------------------------------------------------- colconds = cfg_branch; colconds.tag = 'colconds'; colconds.name = 'Contrast entry'; colconds.val = {conweight colcond colbf colmod colmodord }; colconds.help = {''}; % --------------------------------------------------------------------- % generic T contrast for conditions % --------------------------------------------------------------------- generic = cfg_repeat; generic.tag = 'generic'; generic.name = 'T contrast for conditions'; generic.help = {'Assemble your contrast column by column.'}; generic.values = {colconds }; generic.num = [1 Inf]; % --------------------------------------------------------------------- % colreg T contrast for extra regressors % --------------------------------------------------------------------- colreg = cfg_entry; colreg.tag = 'colreg'; colreg.name = 'T contrast for extra regressors'; colreg.help = {'Enter T contrast vector for extra regressors.'}; colreg.strtype = 'e'; colreg.num = [1 Inf]; % --------------------------------------------------------------------- % coltype Contrast columns % --------------------------------------------------------------------- coltype = cfg_choice; coltype.tag = 'coltype'; coltype.name = 'Contrast columns'; coltype.val = {generic }; coltype.help = {'Contrasts can be specified either over conditions or over extra regressors.'}; coltype.values = {generic colreg }; % --------------------------------------------------------------------- % sessions Session(s) % --------------------------------------------------------------------- sessions = cfg_entry; sessions.tag = 'sessions'; sessions.name = 'Session(s)'; sessions.help = {'Enter session number(s) for which this contrast should be created. If more than one session number is specified, the contrast will be an average contrast over the specified conditions or regressors from these sessions.'}; sessions.strtype = 'e'; sessions.num = [1 Inf]; % --------------------------------------------------------------------- % tconsess T-contrast (cond/sess based) % --------------------------------------------------------------------- tconsess = cfg_branch; tconsess.tag = 'tconsess'; tconsess.name = 'T-contrast (cond/sess based)'; tconsess.val = {name coltype sessions }; tconsess.help = { 'Define a contrast in terms of conditions or regressors instead of columns of the design matrix. This allows to create contrasts automatically even if some columns are not always present (e.g. parametric modulations).' '' 'Each contrast column can be addressed by specifying' '* session number' '* condition number' '* basis function number' '* parametric modulation number and' '* parametric modulation order.' '' 'If the design is specified without time or parametric modulation, SPM creates a "pseudo-modulation" with order zero. To put a contrast weight on a basis function one therefore has to enter "1" for parametric modulation number and "0" for parametric modulation order.' '' 'Time and parametric modulations are not distinguished internally. If time modulation is present, it will be parametric modulation "1", and additional parametric modulations will be numbered starting with "2".' '' '* Simple one-dimensional contrasts for an SPM{T}' '' 'A simple contrast for an SPM{T} tests the null hypothesis c''B=0 against the one-sided alternative c''B>0, where c is a column vector. ' '' ' Note that throughout SPM, the transpose of the contrast weights is used for display and input. That is, you''ll enter and visualise c''. For an SPM{T} this will be a row vector.' '' 'For example, if you have a design in which the first two columns of the design matrix correspond to the effects for "baseline" and "active" conditions respectively, then a contrast with weights c''=[-1,+1,0,...] (with zero weights for any other parameters) tests the hypothesis that there is no "activation" (the parameters for both conditions are the same), against the alternative that there is some activation (i.e. the parameter for the "active" condition is greater than that for the "baseline" condition). The resulting SPM{T} (created by spm_getSPM.m) is a statistic image, with voxel values the value of the t-statistic for the specified contrast at that location. Areas of the SPM{T} with high voxel values indicate evidence for "activation". To look for areas of relative "de-activation", the inverse contrast could be used c''=[+1,-1,0,...].' '' 'Similarly, if you have a design where the third column in the design matrix is a covariate, then the corresponding parameter is essentially a regression slope, and a contrast with weights c''=[0,0,1,0,...] (with zero weights for all parameters but the third) tests the hypothesis of zero regression slope, against the alternative of a positive slope. This is equivalent to a test no correlation, against the alternative of positive correlation. If there are other terms in the model beyond a constant term and the covariate, then this correlation is apartial correlation, the correlation between the data Y and the covariate, after accounting for the other effects.' }'; % --------------------------------------------------------------------- % consess Contrast Sessions % --------------------------------------------------------------------- consess = cfg_repeat; consess.tag = 'consess'; consess.name = 'Contrast Sessions'; consess.help = { 'For general linear model Y = XB + E with data Y, desgin matrix X, parameter vector B, and (independent) errors E, a contrast is a linear combination of the parameters c''B. Usually c is a column vector, defining a simple contrast of the parameters, assessed via an SPM{T}. More generally, c can be a matrix (a linear constraining matrix), defining an "F-contrast" assessed via an SPM{F}.' '' 'The vector/matrix c contains the contrast weights. It is this contrast weights vector/matrix that must be specified to define the contrast. The null hypothesis is that the linear combination c''B is zero. The order of the parameters in the parameter (column) vector B, and hence the order to which parameters are referenced in the contrast weights vector c, is determined by the construction of the design matrix.' '' 'There are two types of contrast in SPM: simple contrasts for SPM{T}, and "F-contrasts" for SPM{F}.' '' 'For a thorough theoretical treatment, see the Human Brain Function book and the statistical literature referenced therein.' '' '' '* Non-orthogonal designs' '' 'Note that parameters zero-weighted in the contrast are still included in the model. This is particularly important if the design is not orthogonal (i.e. the columns of the design matrix are not orthogonal). In effect, the significance of the contrast is assessed *after* accounting for the other effects in the design matrix. Thus, if two covariates are correlated, testing the significance of the parameter associated with one will only test for the part that is not present in the second covariate. This is a general point that is also true for F-contrasts. See Andrade et al, Ambiguous results in functional neuroimaging, NeuroImage, 1999, for a full description of the effect of non othogonal design testing.' '' '' '* Estimability' '' 'The contrast c''B is estimated by c''b, where b are the parameter estimates given by b=pinv(X)*Y.' '' 'However, if a design is rank-deficient (i.e. the columns of the design matrix are not linearly independent), then the parameters are not unique, and not all linear combinations of the parameter are valid contrasts, since contrasts must be uniquely estimable.' '' 'A weights vector defines a valid contrast if and only if it can be constructed as a linear combination of the rows of the design matrix. That is c'' (the transposed contrast vector - a row vector) is in the row-space of the design matrix.' '' 'Usually, a valid contrast will have weights that sum to zero over the levels of a factor (such as condition).' '' 'A simple example is a simple two condition design including a constant, with design matrix' '' ' [ 1 0 1 ]' ' [ : : : ]' ' X = [ 1 0 1 ]' ' [ 0 1 1 ]' ' [ : : : ]' ' [ 0 1 1 ]' '' 'The first column corresponds to condition 1, the second to condition 2, and the third to a constant (mean) term. Although there are three columns to the design matrix, the design only has two degrees of freedom, since any one column can be derived from the other two (for instance, the third column is the sum of the first two). There is no unique set of parameters for this model, since for any set of parameters adding a constant to the two condition effects and subtracting it from the constant effect yields another set of viable parameters. However, the difference between the two condition effects is uniquely estimated, so c''=[-1,+1,0] does define a contrast.' '' 'If a parameter is estimable, then the weights vector with a single "1" corresponding to that parameter (and zero elsewhere) defines a valid contrast.' '' '' '* Multiple comparisons' '' 'Note that SPM implements no corrections to account for you looking at multiple contrasts.' '' 'If you are interested in a set of hypotheses that together define a consistent question, then you should account for this when assessing the individual contrasts. A simple Bonferroni approach would assess N simultaneous contrasts at significance level alpha/N, where alpha is the chosen significance level (usually 0.05).' '' 'For two sided t-tests using SPM{T}s, the significance level should be halved. When considering both SPM{T}s produced by a contrast and it''s inverse (the contrast with negative weights), to effect a two-sided test to look for both "increases" and "decreases", you should review each SPM{T} at at level 0.05/2 rather than 0.05. (Or consider an F-contrast!)' '' '' '* Contrast images and ESS images' '' 'For a simple contrast, SPM (spm_getSPM.m) writes a contrast image: con_????.{img,nii}, with voxel values c''b. (The ???? in the image names are replaced with the contrast number.) These contrast images (for appropriate contrasts) are suitable summary images of an effect at this level, and can be used as input at a higher level when effecting a random effects analysis. See spm_RandFX.man for further details.' '' 'For an F-contrast, SPM (spm_getSPM.m) writes the Extra Sum-of-Squares (the difference in the residual sums of squares for the full and reduced model) as ess_????.{img,nii}. (Note that the ess_????.{img,nii} and SPM{T,F}_????.{img,nii} images are not suitable input for a higher level analysis.)' }'; consess.values = {tcon fcon tconsess }; consess.num = [0 Inf]; % --------------------------------------------------------------------- % delete Delete existing contrasts % --------------------------------------------------------------------- delete = cfg_menu; delete.tag = 'delete'; delete.name = 'Delete existing contrasts'; delete.help = {''}; delete.labels = { 'Yes' 'No' }'; delete.values = {1 0}; delete.val = {0}; % --------------------------------------------------------------------- % con Contrast Manager % --------------------------------------------------------------------- con = cfg_exbranch; con.tag = 'con'; con.name = 'Contrast Manager'; con.val = {spmmat consess delete }; con.help = {'Set up T and F contrasts.'}; con.prog = @spm_run_con; con.vout = @vout_stats; %------------------------------------------------------------------------- %------------------------------------------------------------------------- function dep = vout_stats(job) dep(1) = cfg_dep; dep(1).sname = 'SPM.mat File'; dep(1).src_output = substruct('.','spmmat'); dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); %dep(2) = cfg_dep; %dep(2).sname = 'SPM Variable'; %dep(2).src_output = substruct('.','spmvar'); %dep(2).tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'All Con Images'; dep(2).src_output = substruct('.','con'); dep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(3) = cfg_dep; dep(3).sname = 'All Stats Images'; dep(3).src_output = substruct('.','spm'); dep(3).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_eeg_inv_headmodel.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_inv_headmodel.m
8,264
utf_8
bdaa34d7b948462ae8b446b38e7aaf6e
function headmodel = spm_cfg_eeg_inv_headmodel % configuration file for specifying the head model for source % reconstruction %_______________________________________________________________________ % Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging % Vladimir Litvak % $Id: spm_cfg_eeg_inv_headmodel.m 4118 2010-11-10 14:48:16Z vladimir $ D = cfg_files; D.tag = 'D'; D.name = 'M/EEG datasets'; D.filter = 'mat'; D.num = [1 Inf]; D.help = {'Select the M/EEG mat files.'}; val = cfg_entry; val.tag = 'val'; val.name = 'Inversion index'; val.strtype = 'n'; val.help = {'Index of the cell in D.inv where the results will be stored.'}; val.val = {1}; comment = cfg_entry; comment.tag = 'comment'; comment.name = 'Comment'; comment.strtype = 's'; comment.help = {'User-specified information about this inversion'}; comment.val = {''}; template = cfg_const; template.tag = 'template'; template.name = 'Template'; template.val = {1}; mri = cfg_files; mri.tag = 'mri'; mri.name = 'Individual structural image'; mri.filter = 'image'; mri.ufilter = '.*'; mri.num = [1 1]; mri.help = {'Select the subject''s structural image'}; meshes = cfg_choice; meshes.tag = 'meshes'; meshes.name = 'Mesh source'; meshes.values = {template, mri}; meshes.val = {template}; meshres = cfg_menu; meshres.tag = 'meshres'; meshres.name = 'Mesh resolution'; meshres.help = {'Specify the resolution of the cortical mesh'}; meshres.labels = {'coarse', 'normal', 'fine'}; meshres.values = {1, 2, 3}; meshres.val = {2}; meshing = cfg_branch; meshing.tag = 'meshing'; meshing.name = 'Meshes'; meshing.help = {'Create head meshes for building the head model'}; meshing.val = {meshes, meshres}; fidname = cfg_entry; fidname.tag = 'fidname'; fidname.name = 'M/EEG fiducial label'; fidname.strtype = 's'; fidname.help = {'Label of a fiducial point (as specified in the M/EEG dataset)'}; type = cfg_entry; type.tag = 'type'; type.name = 'Type MNI coordinates'; type.strtype = 'r'; type.num = [1 3]; type.help = {'Type the coordinates corresponding to the fiducial in the structural image.'}; fid = fopen(fullfile(spm('dir'), 'EEGtemplates', 'fiducials.sfp') ,'rt'); fidtable =textscan(fid ,'%s %f %f %f'); fclose(fid); select = cfg_menu; select.tag = 'select'; select.name = 'Select from a list'; select.help = {'Select the corresponding fiducial point from a pre-specified list.'}; select.labels = fidtable{1}'; select.values = fidtable{1}'; specification = cfg_choice; specification.tag = 'specification'; specification.name = 'How to specify?'; specification.values = {select, type}; fiducial = cfg_branch; fiducial.tag = 'fiducial'; fiducial.name = 'Fiducial'; fiducial.help = {'Specify fiducial for coregistration'}; fiducial.val = {fidname, specification}; fiducials = cfg_repeat; fiducials.tag = 'fiducials'; fiducials.name = 'Fiducials'; fiducials.help = {'Specify fiducials for coregistration (at least 3 fiducials need to be specified)'}; fiducials.num = [3 Inf]; fiducials.values = {fiducial}; fiducials.val = {fiducial fiducial fiducial}; useheadshape = cfg_menu; useheadshape.tag = 'useheadshape'; useheadshape.name = 'Use headshape points?'; useheadshape.help = {'Use headshape points (if available)'}; useheadshape.labels = {'yes', 'no'}; useheadshape.values = {1, 0}; useheadshape.val = {0}; coregspecify = cfg_branch; coregspecify.tag = 'coregspecify'; coregspecify.name = 'Specify coregistration parameters'; coregspecify.val = {fiducials, useheadshape}; coregdefault = cfg_const; coregdefault.tag = 'coregdefault'; coregdefault.name = 'Sensor locations are in MNI space already'; coregdefault.help = {'No coregistration is necessary because default EEG sensor locations were used'}; coregdefault.val = {1}; coregistration = cfg_choice; coregistration.tag = 'coregistration'; coregistration.name = 'Coregistration'; coregistration.values = {coregspecify, coregdefault}; coregistration.val = {coregspecify}; eeg = cfg_menu; eeg.tag = 'eeg'; eeg.name = 'EEG head model'; eeg.help = {'Select the head model type to use for EEG (if present)'}; eeg.labels = {'EEG BEM', '3-Shell Sphere (experimental)'}; eeg.values = {'EEG BEM', '3-Shell Sphere (experimental)'}; eeg.val = {'EEG BEM'}; meg = cfg_menu; meg.tag = 'meg'; meg.name = 'MEG head model'; meg.help = {'Select the head model type to use for MEG (if present)'}; meg.labels = {'Single Sphere', 'MEG Local Spheres', 'Single Shell'}; meg.values = {'Single Sphere', 'MEG Local Spheres', 'Single Shell'}; meg.val = {'Single Sphere'}; forward = cfg_branch; forward.tag = 'forward'; forward.name = 'Forward model'; forward.val = {eeg, meg}; headmodel = cfg_exbranch; headmodel.tag = 'headmodel'; headmodel.name = 'M/EEG head model specification'; headmodel.val = {D, val, comment, meshing, coregistration, forward}; headmodel.help = {'Specify M/EEG head model for forward computation'}; headmodel.prog = @specify_headmodel; headmodel.vout = @vout_specify_headmodel; headmodel.modality = {'EEG'}; function out = specify_headmodel(job) mesh = spm_eeg_inv_mesh; out.D = {}; %- Loop over input datasets %-------------------------------------------------------------------------- for i = 1:numel(job.D) D = spm_eeg_load(job.D{i}); if ~isfield(D,'inv') val = 1; elseif numel(D.inv)<job.val val = numel(D.inv) + 1; else val = job.val; end if val ~= job.val error(sprintf('Cannot use the user-specified inversion index %d for dataset ', job.val, i)); end D.val = val; %-Meshes %-------------------------------------------------------------------------- if ~isfield(D,'inv') D.inv = {struct('mesh', [])}; end D.inv{val}.date = strvcat(date,datestr(now,15)); D.inv{val}.comment = {job.comment}; if isfield(job.meshing.meshes, 'template') sMRI = 1; else sMRI = job.meshing.meshes.mri{1}; end D = spm_eeg_inv_mesh_ui(D, val, sMRI, job.meshing.meshres); %-Coregistration %-------------------------------------------------------------------------- if isfield(job.coregistration, 'coregdefault') D = spm_eeg_inv_datareg_ui(D); else meegfid = D.fiducials; selection = spm_match_str(meegfid.fid.label, {job.coregistration.coregspecify.fiducial.fidname}); meegfid.fid.pnt = meegfid.fid.pnt(selection, :); meegfid.fid.label = meegfid.fid.label(selection); mrifid = []; mrifid.pnt = D.inv{val}.mesh.fid.pnt; mrifid.fid.pnt = []; mrifid.fid.label = {job.coregistration.coregspecify.fiducial.fidname}'; for j = 1:numel(job.coregistration.coregspecify.fiducial) if isfield(job.coregistration.coregspecify.fiducial(j).specification, 'select') lbl = job.coregistration.coregspecify.fiducial(j).specification.select; ind = strmatch(lbl, mesh.fid.fid.label); mrifid.fid.pnt(j, :) = mesh.fid.fid.pnt(ind, :); else mrifid.fid.pnt(j, :) = job.coregistration.coregspecify.fiducial(j).specification.type; end end D = spm_eeg_inv_datareg_ui(D, D.val, meegfid, mrifid, job.coregistration.coregspecify.useheadshape); end %-Compute forward model %---------------------------------------------------------------------- D.inv{val}.forward = struct([]); for j = 1:numel(D.inv{val}.datareg) switch D.inv{val}.datareg(j).modality case 'EEG' D.inv{D.val}.forward(j).voltype = job.forward.eeg; case 'MEG' D.inv{D.val}.forward(j).voltype = job.forward.meg; end end D = spm_eeg_inv_forward(D); for j = 1:numel(D.inv{val}.forward) spm_eeg_inv_checkforward(D, D.val, j); end save(D); out.D{i, 1} = fullfile(D.path, D.fname); end function dep = vout_specify_headmodel(job) % Output is always in field "D", no matter how job is structured dep = cfg_dep; dep.sname = 'M/EEG dataset(s) with a forward model'; % reference field "D" from output dep.src_output = substruct('.','D'); % this can be entered into any evaluated input dep.tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_cfg_eeg_average.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_average.m
3,037
utf_8
dd74140584689604aeafa61c63166da8
function S = spm_cfg_eeg_average % configuration file for M/EEG epoching %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: spm_cfg_eeg_average.m 3881 2010-05-07 21:02:57Z vladimir $ rev = '$Rev: 3881 $'; D = cfg_files; D.tag = 'D'; D.name = 'File Name'; D.filter = 'mat'; D.num = [1 1]; D.help = {'Select the M/EEG mat file.'}; standard = cfg_const; standard.tag = 'standard'; standard.name = 'Standard'; standard.val = {false}; ks = cfg_entry; ks.tag = 'ks'; ks.name = 'Offset of the weighting function'; ks.strtype = 'r'; ks.val = {3}; ks.num = [1 1]; ks.help = {'Parameter determining the how far the values should be from the median, '... 'to be considered outliers (the larger, the farther).'}; bycondition = cfg_menu; bycondition.tag = 'bycondition'; bycondition.name = 'Compute weights by condition'; bycondition.help = {'Compute weights for each condition separately or for all conditions together.'}; bycondition.labels = {'Yes', 'No'}; bycondition.values = {true, false}; bycondition.val = {true}; savew = cfg_menu; savew.tag = 'savew'; savew.name = 'Save weights'; savew.help = {'Save weights in a separate dataset for quality control.'}; savew.labels = {'Yes', 'No'}; savew.values = {true, false}; savew.val = {true}; robust = cfg_branch; robust.tag = 'robust'; robust.name = 'Robust'; robust.val = {ks, bycondition, savew}; userobust = cfg_choice; userobust.tag = 'userobust'; userobust.name = 'Averaging type'; userobust.help = {'choose between using standard and robust averaging'}; userobust.values = {standard, robust}; userobust.val = {standard}; plv = cfg_menu; plv.tag = 'plv'; plv.name = 'Compute phase-locking value'; plv.help = {'Compute phase-locking value rather than average the phase',... 'This option is only relevant for TF-phase datasets'}; plv.labels = {'Yes', 'No'}; plv.values = {true, false}; plv.val = {false}; S = cfg_exbranch; S.tag = 'average'; S.name = 'M/EEG Averaging'; S.val = {D, userobust, plv}; S.help = {'Average epoched EEG/MEG data.'}; S.prog = @eeg_average; S.vout = @vout_eeg_average; S.modality = {'EEG'}; function out = eeg_average(job) % construct the S struct S.D = job.D{1}; if isfield(job.userobust, 'robust') S.robust = job.userobust.robust; else S.robust = false; end S.review = false; S.circularise = job.plv; out.D = spm_eeg_average(S); out.Dfname = {fullfile(out.D.path, out.D.fname)}; function dep = vout_eeg_average(job) % Output is always in field "D", no matter how job is structured dep = cfg_dep; dep.sname = 'Average Data'; % reference field "D" from output dep.src_output = substruct('.','D'); % this can be entered into any evaluated input dep.tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Averaged Datafile'; % reference field "Dfname" from output dep(2).src_output = substruct('.','Dfname'); % this can be entered into any file selector dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_cfg_eeg_fuse.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_fuse.m
1,316
utf_8
f68fede02ad0b7e98d3e5bcffb4067f1
function S = spm_cfg_eeg_fuse % configuration file for fusing M/EEG files %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Vladimir Litvak % $Id: spm_cfg_eeg_fuse.m 3881 2010-05-07 21:02:57Z vladimir $ rev = '$Rev: 3881 $'; D = cfg_files; D.tag = 'D'; D.name = 'File Names'; D.filter = 'mat'; D.num = [2 Inf]; D.help = {'Select the M/EEG mat files.'}; S = cfg_exbranch; S.tag = 'fuse'; S.name = 'M/EEG Fusion'; S.val = {D}; S.help = {'Fuse EEG/MEG data.'}; S.prog = @eeg_fuse; S.vout = @vout_eeg_fuse; S.modality = {'EEG'}; function out = eeg_fuse(job) % construct the S struct S.D = strvcat(job.D{:}); out.D = spm_eeg_fuse(S); out.Dfname = {fullfile(out.D.path, out.D.fname)}; function dep = vout_eeg_fuse(job) % Output is always in field "D", no matter how job is structured dep = cfg_dep; dep.sname = 'Fused Data'; % reference field "D" from output dep.src_output = substruct('.','D'); % this can be entered into any evaluated input dep.tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Fused Datafile'; % reference field "Dfname" from output dep(2).src_output = substruct('.','Dfname'); % this can be entered into any file selector dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_cfg_reorient.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_reorient.m
5,240
utf_8
2ea92b7d5abbfb7cc208d7967030afa3
function reorient = spm_cfg_reorient % SPM Configuration file % automatically generated by the MATLABBATCH utility function GENCODE %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_reorient.m 4380 2011-07-05 11:27:12Z volkmar $ rev = '$Rev: 4380 $'; % --------------------------------------------------------------------- % srcfiles Images to reorient % --------------------------------------------------------------------- srcfiles = cfg_files; srcfiles.tag = 'srcfiles'; srcfiles.name = 'Images to reorient'; srcfiles.help = {'Select images to reorient.'}; srcfiles.filter = 'image'; srcfiles.ufilter = '.*'; srcfiles.num = [0 Inf]; % --------------------------------------------------------------------- % transM Reorientation Matrix % --------------------------------------------------------------------- transM = cfg_entry; transM.tag = 'transM'; transM.name = 'Reorientation Matrix'; transM.help = { 'Enter a valid 4x4 matrix for reorientation.' '' 'Example: This will L-R flip the images.' '' ' -1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1' }'; transM.strtype = 'e'; transM.num = [4 4]; % --------------------------------------------------------------------- % transprm Reorientation Parameters % --------------------------------------------------------------------- transprm = cfg_entry; transprm.tag = 'transprm'; transprm.name = 'Reorientation Parameters'; transprm.help = { 'Enter 12 reorientation parameters.' 'P(1) - x translation' 'P(2) - y translation' 'P(3) - z translation' 'P(4) - x rotation about - {pitch} (radians)' 'P(5) - y rotation about - {roll} (radians)' 'P(6) - z rotation about - {yaw} (radians)' 'P(7) - x scaling' 'P(8) - y scaling' 'P(9) - z scaling' 'P(10) - x affine' 'P(11) - y affine' 'P(12) - z affine' 'Parameters are entered as listed above and then processed by spm_matrix.' '' 'Example: This will L-R flip the images (extra spaces are inserted between each group for illustration purposes).' '' ' 0 0 0 0 0 0 -1 1 1 0 0 0' '' }'; transprm.strtype = 'e'; transprm.num = [1 12]; % --------------------------------------------------------------------- % transform Reorient by % --------------------------------------------------------------------- transform = cfg_choice; transform.tag = 'transform'; transform.name = 'Reorient by'; transform.val = {transM }; transform.help = {'Specify reorientation parameters - either 12 parameters or a 4x4 transformation matrix. The resulting transformation will be left-multiplied to the voxel-to-world transformation of each image and the new transformation will be written to the image header.'}; transform.values = {transM transprm }; % --------------------------------------------------------------------- % prefix Filename Prefix % --------------------------------------------------------------------- prefix = cfg_entry; prefix.tag = 'prefix'; prefix.name = 'Filename Prefix'; prefix.help = {['Specify the string to be prepended to the filenames ' ... 'of the reoriented image file(s). If this is left ' ... 'empty, the original files will be overwritten.']}; prefix.strtype = 's'; prefix.num = [0 Inf]; % This should not be hardcoded here prefix.val = {''}; % Final solution: defaults setting % prefix.def = @(val)spm_get_defaults('reorient.prefix', val{:}); % The following 3 lines should go into spm_defaults.m % % Reorient defaults % %======================================================================= % defaults.reorient.prefix = ''; % Output filename prefix ('' == overwrite) % --------------------------------------------------------------------- % reorient Reorient Images % --------------------------------------------------------------------- reorient = cfg_exbranch; reorient.tag = 'reorient'; reorient.name = 'Reorient Images'; reorient.val = {srcfiles transform prefix}; reorient.help = {'This facility allows to reorient images in a batch. The reorientation parameters can be given either as a 4x4 matrix or as parameters as defined for spm_matrix.m. The new image orientation will be computed by PRE-multiplying the original orientation matrix with the supplied matrix.'}; reorient.prog = @spm_run_reorient; reorient.vout = @vout; % --------------------------------------------------------------------- % --------------------------------------------------------------------- function dep = vout(job) dep = cfg_dep; dep.sname = 'Reoriented Images'; dep.src_output = substruct('.','files'); dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_fmri_design.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_fmri_design.m
41,307
utf_8
544e55095f3244947f8aa8b98fd18c93
function fmri_design = spm_cfg_fmri_design % SPM Configuration file for fMRI model specification (design only) %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_fmri_design.m 637 2011-05-11 09:53:31Z vglauche $ rev = '$Rev: 637 $'; % --------------------------------------------------------------------- % dir Directory % --------------------------------------------------------------------- dir = cfg_files; dir.tag = 'dir'; dir.name = 'Directory'; dir.help = {'Select a directory where the SPM.mat file containing the specified design matrix will be written.'}; dir.filter = 'dir'; dir.ufilter = '.*'; dir.num = [1 1]; % --------------------------------------------------------------------- % units Units for design % --------------------------------------------------------------------- units = cfg_menu; units.tag = 'units'; units.name = 'Units for design'; units.help = {'The onsets of events or blocks can be specified in either scans or seconds.'}; units.labels = { 'Scans' 'Seconds' }'; units.values = { 'scans' 'secs' }'; % --------------------------------------------------------------------- % RT Interscan interval % --------------------------------------------------------------------- RT = cfg_entry; RT.tag = 'RT'; RT.name = 'Interscan interval'; RT.help = {'Interscan interval, TR, (specified in seconds). This is the time between acquiring a plane of one volume and the same plane in the next volume. It is assumed to be constant throughout.'}; RT.strtype = 'e'; RT.num = [1 1]; % --------------------------------------------------------------------- % fmri_t Microtime resolution % --------------------------------------------------------------------- fmri_t = cfg_entry; fmri_t.tag = 'fmri_t'; fmri_t.name = 'Microtime resolution'; fmri_t.help = { 'The microtime resolution, t, is the number of time-bins per scan used when building regressors. ' '' 'Do not change this parameter unless you have a long TR and wish to shift regressors so that they are aligned to a particular slice. ' }'; fmri_t.strtype = 'e'; fmri_t.num = [1 1]; fmri_t.def = @(val)spm_get_defaults('stats.fmri.fmri_t', val{:}); % --------------------------------------------------------------------- % fmri_t0 Microtime onset % --------------------------------------------------------------------- fmri_t0 = cfg_entry; fmri_t0.tag = 'fmri_t0'; fmri_t0.name = 'Microtime onset'; fmri_t0.help = { 'The microtime onset, t0, is the first time-bin at which the regressors are resampled to coincide with data acquisition. If t0 = 1 then the regressors will be appropriate for the first slice. If you want to temporally realign the regressors so that they match responses in the middle slice then make t0 = t/2 (assuming there is a negligible gap between volume acquisitions). ' '' 'Do not change the default setting unless you have a long TR. ' }'; fmri_t0.strtype = 'e'; fmri_t0.num = [1 1]; fmri_t0.def = @(val)spm_get_defaults('stats.fmri.fmri_t0', val{:}); % --------------------------------------------------------------------- % timing Timing parameters % --------------------------------------------------------------------- timing = cfg_branch; timing.tag = 'timing'; timing.name = 'Timing parameters'; timing.val = {units RT fmri_t fmri_t0 }; timing.help = { 'Specify various timing parameters needed to construct the design matrix. This includes the units of the design specification and the interscan interval.' '' 'Also, with longs TRs you may want to shift the regressors so that they are aligned to a particular slice. This is effected by changing the microtime resolution and onset. ' }'; % --------------------------------------------------------------------- % nscan Number of scans % --------------------------------------------------------------------- nscan = cfg_entry; nscan.tag = 'nscan'; nscan.name = 'Number of scans'; nscan.help = {'Specify the number of scans for this session.The actual scans must be specified in a separate batch job ''fMRI data specification''.'}; nscan.strtype = 'e'; nscan.num = [1 1]; % --------------------------------------------------------------------- % name Name % --------------------------------------------------------------------- name = cfg_entry; name.tag = 'name'; name.name = 'Name'; name.help = {'Condition Name'}; name.strtype = 's'; name.num = [1 Inf]; % --------------------------------------------------------------------- % onset Onsets % --------------------------------------------------------------------- onset = cfg_entry; onset.tag = 'onset'; onset.name = 'Onsets'; onset.help = {'Specify a vector of onset times for this condition type. '}; onset.strtype = 'e'; onset.num = [Inf 1]; % --------------------------------------------------------------------- % duration Durations % --------------------------------------------------------------------- duration = cfg_entry; duration.tag = 'duration'; duration.name = 'Durations'; duration.help = {'Specify the event durations. Epoch and event-related responses are modeled in exactly the same way but by specifying their different durations. Events are specified with a duration of 0. If you enter a single number for the durations it will be assumed that all trials conform to this duration. If you have multiple different durations, then the number must match the number of onset times.'}; duration.strtype = 'e'; duration.num = [Inf 1]; % --------------------------------------------------------------------- % tmod Time Modulation % --------------------------------------------------------------------- tmod = cfg_menu; tmod.tag = 'tmod'; tmod.name = 'Time Modulation'; tmod.help = { 'This option allows for the characterisation of linear or nonlinear time effects. For example, 1st order modulation would model the stick functions and a linear change of the stick function heights over time. Higher order modulation will introduce further columns that contain the stick functions scaled by time squared, time cubed etc.' '' 'Interactions or response modulations can enter at two levels. Firstly the stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate or, secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types).' }'; tmod.labels = { 'No Time Modulation' '1st order Time Modulation' '2nd order Time Modulation' '3rd order Time Modulation' '4th order Time Modulation' '5th order Time Modulation' '6th order Time Modulation' }'; tmod.values = {0 1 2 3 4 5 6}; tmod.val = {0}; % --------------------------------------------------------------------- % name Name % --------------------------------------------------------------------- name1 = cfg_entry; name1.tag = 'name'; name1.name = 'Name'; name1.help = {'Enter a name for this parameter.'}; name1.strtype = 's'; name1.num = [1 Inf]; % --------------------------------------------------------------------- % param Values % --------------------------------------------------------------------- param = cfg_entry; param.tag = 'param'; param.name = 'Values'; param.help = {'Enter a vector of values, one for each occurence of the event.'}; param.strtype = 'e'; param.num = [Inf 1]; % --------------------------------------------------------------------- % poly Polynomial Expansion % --------------------------------------------------------------------- poly = cfg_menu; poly.tag = 'poly'; poly.name = 'Polynomial Expansion'; poly.help = {'For example, 1st order modulation would model the stick functions and a linear change of the stick function heights over different values of the parameter. Higher order modulation will introduce further columns that contain the stick functions scaled by parameter squared, cubed etc.'}; poly.labels = { '1st order' '2nd order' '3rd order' '4th order' '5th order' '6th order' }'; poly.values = {1 2 3 4 5 6}; % --------------------------------------------------------------------- % pmod Parameter % --------------------------------------------------------------------- pmod = cfg_branch; pmod.tag = 'pmod'; pmod.name = 'Parameter'; pmod.val = {name1 param poly }; pmod.help = { 'Model interractions with user specified parameters. This allows nonlinear effects relating to some other measure to be modelled in the design matrix.' '' 'Interactions or response modulations can enter at two levels. Firstly the stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate or, secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types).' }'; % --------------------------------------------------------------------- % generic Parametric Modulations % --------------------------------------------------------------------- generic2 = cfg_repeat; generic2.tag = 'generic'; generic2.name = 'Parametric Modulations'; generic2.help = {'The stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate. The events can be modulated by zero or more parameters.'}; generic2.values = {pmod }; generic2.num = [0 Inf]; % --------------------------------------------------------------------- % cond Condition % --------------------------------------------------------------------- cond = cfg_branch; cond.tag = 'cond'; cond.name = 'Condition'; cond.val = {name onset duration tmod generic2 }; cond.check = @cond_check; cond.help = {'An array of input functions is contructed, specifying occurrence events or epochs (or both). These are convolved with a basis set at a later stage to give regressors that enter into the design matrix. Interactions of evoked responses with some parameter (time or a specified variate) enter at this stage as additional columns in the design matrix with each trial multiplied by the [expansion of the] trial-specific parameter. The 0th order expansion is simply the main effect in the first column.'}; % --------------------------------------------------------------------- % generic Conditions % --------------------------------------------------------------------- generic1 = cfg_repeat; generic1.tag = 'generic'; generic1.name = 'Conditions'; generic1.help = {'You are allowed to combine both event- and epoch-related responses in the same model and/or regressor. Any number of condition (event or epoch) types can be specified. Epoch and event-related responses are modeled in exactly the same way by specifying their onsets [in terms of onset times] and their durations. Events are specified with a duration of 0. If you enter a single number for the durations it will be assumed that all trials conform to this duration.For factorial designs, one can later associate these experimental conditions with the appropriate levels of experimental factors. '}; generic1.values = {cond }; generic1.num = [0 Inf]; % --------------------------------------------------------------------- % multi Multiple conditions % --------------------------------------------------------------------- multi = cfg_files; multi.tag = 'multi'; multi.name = 'Multiple conditions'; multi.val{1} = {''}; multi.help = { 'Select the *.mat file containing details of your multiple experimental conditions. ' '' 'If you have multiple conditions then entering the details a condition at a time is very inefficient. This option can be used to load all the required information in one go. You will first need to create a *.mat file containing the relevant information. ' '' 'This *.mat file must include the following cell arrays (each 1 x n): names, onsets and durations. eg. names=cell(1,5), onsets=cell(1,5), durations=cell(1,5), then names{2}=''SSent-DSpeak'', onsets{2}=[3 5 19 222], durations{2}=[0 0 0 0], contain the required details of the second condition. These cell arrays may be made available by your stimulus delivery program, eg. COGENT. The duration vectors can contain a single entry if the durations are identical for all events.' '' 'Time and Parametric effects can also be included. For time modulation include a cell array (1 x n) called tmod. It should have a have a single number in each cell. Unused cells may contain either a 0 or be left empty. The number specifies the order of time modulation from 0 = No Time Modulation to 6 = 6th Order Time Modulation. eg. tmod{3} = 1, modulates the 3rd condition by a linear time effect.' '' 'For parametric modulation include a structure array, which is up to 1 x n in size, called pmod. n must be less than or equal to the number of cells in the names/onsets/durations cell arrays. The structure array pmod must have the fields: name, param and poly. Each of these fields is in turn a cell array to allow the inclusion of one or more parametric effects per column of the design. The field name must be a cell array containing strings. The field param is a cell array containing a vector of parameters. Remember each parameter must be the same length as its corresponding onsets vector. The field poly is a cell array (for consistency) with each cell containing a single number specifying the order of the polynomial expansion from 1 to 6.' '' 'Note that each condition is assigned its corresponding entry in the structure array (condition 1 parametric modulators are in pmod(1), condition 2 parametric modulators are in pmod(2), etc. Within a condition multiple parametric modulators are accessed via each fields cell arrays. So for condition 1, parametric modulator 1 would be defined in pmod(1).name{1}, pmod(1).param{1}, and pmod(1).poly{1}. A second parametric modulator for condition 1 would be defined as pmod(1).name{2}, pmod(1).param{2} and pmod(1).poly{2}. If there was also a parametric modulator for condition 2, then remember the first modulator for that condition is in cell array 1: pmod(2).name{1}, pmod(2).param{1}, and pmod(2).poly{1}. If some, but not all conditions are parametrically modulated, then the non-modulated indices in the pmod structure can be left blank. For example, if conditions 1 and 3 but not condition 2 are modulated, then specify pmod(1) and pmod(3). Similarly, if conditions 1 and 2 are modulated but there are 3 conditions overall, it is only necessary for pmod to be a 1 x 2 structure array.' '' 'EXAMPLE:' 'Make an empty pmod structure: ' ' pmod = struct(''name'',{''''},''param'',{},''poly'',{});' 'Specify one parametric regressor for the first condition: ' ' pmod(1).name{1} = ''regressor1'';' ' pmod(1).param{1} = [1 2 4 5 6];' ' pmod(1).poly{1} = 1;' 'Specify 2 parametric regressors for the second condition: ' ' pmod(2).name{1} = ''regressor2-1'';' ' pmod(2).param{1} = [1 3 5 7]; ' ' pmod(2).poly{1} = 1;' ' pmod(2).name{2} = ''regressor2-2'';' ' pmod(2).param{2} = [2 4 6 8 10];' ' pmod(2).poly{2} = 1;' '' 'The parametric modulator should be mean corrected if appropriate. Unused structure entries should have all fields left empty.' }'; multi.filter = 'mat'; multi.ufilter = '.*'; multi.num = [0 1]; % --------------------------------------------------------------------- % name Name % --------------------------------------------------------------------- name = cfg_entry; name.tag = 'name'; name.name = 'Name'; name.help = {'Enter name of regressor eg. First movement parameter'}; name.strtype = 's'; name.num = [1 Inf]; % --------------------------------------------------------------------- % val Value % --------------------------------------------------------------------- val = cfg_entry; val.tag = 'val'; val.name = 'Value'; val.help = {'Enter the vector of regressor values'}; val.strtype = 'e'; val.num = [Inf 1]; % --------------------------------------------------------------------- % regress Regressor % --------------------------------------------------------------------- regress = cfg_branch; regress.tag = 'regress'; regress.name = 'Regressor'; regress.val = {name val }; regress.help = {'regressor'}; % --------------------------------------------------------------------- % generic Regressors % --------------------------------------------------------------------- generic2 = cfg_repeat; generic2.tag = 'generic'; generic2.name = 'Regressors'; generic2.help = {'Regressors are additional columns included in the design matrix, which may model effects that would not be convolved with the haemodynamic response. One such example would be the estimated movement parameters, which may confound the data.'}; generic2.values = {regress }; generic2.num = [0 Inf]; % --------------------------------------------------------------------- % multi_reg Multiple regressors % --------------------------------------------------------------------- multi_reg = cfg_files; multi_reg.tag = 'multi_reg'; multi_reg.name = 'Multiple regressors'; multi_reg.val{1} = {''}; multi_reg.help = { 'Select the *.mat/*.txt file containing details of your multiple regressors. ' '' 'If you have multiple regressors eg. realignment parameters, then entering the details a regressor at a time is very inefficient. This option can be used to load all the required information in one go. ' '' 'You will first need to create a *.mat file containing a matrix R or a *.txt file containing the regressors. Each column of R will contain a different regressor. When SPM creates the design matrix the regressors will be named R1, R2, R3, ..etc.' }'; multi_reg.filter = 'mat'; multi_reg.ufilter = '.*'; multi_reg.num = [0 1]; % --------------------------------------------------------------------- % hpf High-pass filter % --------------------------------------------------------------------- hpf = cfg_entry; hpf.tag = 'hpf'; hpf.name = 'High-pass filter'; hpf.help = {'The default high-pass filter cutoff is 128 seconds.Slow signal drifts with a period longer than this will be removed. Use ''explore design'' to ensure this cut-off is not removing too much experimental variance. High-pass filtering is implemented using 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.'}; hpf.strtype = 'e'; hpf.num = [1 1]; hpf.def = @(val)spm_get_defaults('stats.fmri.hpf', val{:}); % --------------------------------------------------------------------- % sess Subject/Session % --------------------------------------------------------------------- sess = cfg_branch; sess.tag = 'sess'; sess.name = 'Subject/Session'; sess.val = {nscan generic1 multi generic2 multi_reg hpf }; sess.check = @sess_check; sess.help = {'The design matrix for fMRI data consists of one or more separable, session-specific partitions. These partitions are usually either one per subject, or one per fMRI scanning session for that subject.'}; % --------------------------------------------------------------------- % generic Data & Design % --------------------------------------------------------------------- generic = cfg_repeat; generic.tag = 'generic'; generic.name = 'Data & Design'; generic.help = { '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). ' '' 'This 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, where the latter model involves prolonged and possibly time-varying responses to state-related changes in experimental conditions. Event-related response are modelled in terms of responses to instantaneous events. Mathematically they are both modelled by convolving a series of delta (stick) or box-car functions, encoding the input or stimulus function. with a set of hemodynamic basis functions.' }'; generic.values = {sess }; generic.num = [1 Inf]; % --------------------------------------------------------------------- % name Name % --------------------------------------------------------------------- name = cfg_entry; name.tag = 'name'; name.name = 'Name'; name.help = {'Name of factor, eg. ''Repetition'' '}; name.strtype = 's'; name.num = [1 Inf]; % --------------------------------------------------------------------- % levels Levels % --------------------------------------------------------------------- levels = cfg_entry; levels.tag = 'levels'; levels.name = 'Levels'; levels.help = {'Enter number of levels for this factor, eg. 2'}; levels.strtype = 'e'; levels.num = [Inf 1]; % --------------------------------------------------------------------- % fact Factor % --------------------------------------------------------------------- fact = cfg_branch; fact.tag = 'fact'; fact.name = 'Factor'; fact.val = {name levels }; fact.help = {'Add a new factor to your experimental design'}; % --------------------------------------------------------------------- % generic Factorial design % --------------------------------------------------------------------- generic1 = cfg_repeat; generic1.tag = 'generic'; generic1.name = 'Factorial design'; generic1.help = { 'If you have a factorial design then SPM can automatically generate the contrasts necessary to test for the main effects and interactions. ' '' 'This includes the F-contrasts necessary to test for these effects at the within-subject level (first level) and the simple contrasts necessary to generate the contrast images for a between-subject (second-level) analysis.' '' 'To use this option, create as many factors as you need and provide a name and number of levels for each. SPM assumes that the condition numbers of the first factor change slowest, the second factor next slowest etc. It is best to write down the contingency table for your design to ensure this condition is met. This table relates the levels of each factor to the conditions. ' '' 'For example, if you have 2-by-3 design your contingency table has two rows and three columns where the the first factor spans the rows, and the second factor the columns. The numbers of the conditions are 1,2,3 for the first row and 4,5,6 for the second. ' }'; generic1.values = {fact }; generic1.num = [0 Inf]; % --------------------------------------------------------------------- % derivs Model derivatives % --------------------------------------------------------------------- derivs = cfg_menu; derivs.tag = 'derivs'; derivs.name = 'Model derivatives'; derivs.help = {'Model HRF Derivatives. The canonical HRF combined with time and dispersion derivatives comprise an ''informed'' basis set, as the shape of the canonical response conforms to the hemodynamic response that is commonly observed. The incorporation of the derivate terms allow for variations in subject-to-subject and voxel-to-voxel responses. The time derivative allows the peak response to vary by plus or minus a second and the dispersion derivative allows the width of the response to vary. The informed basis set requires an SPM{F} for inference. T-contrasts over just the canonical are perfectly valid but assume constant delay/dispersion. The informed basis set compares favourably with eg. FIR bases on many data sets. '}; derivs.labels = { 'No derivatives' 'Time derivatives' 'Time and Dispersion derivatives' }'; derivs.values = {[0 0] [1 0] [1 1]}; derivs.val = {[0 0]}; % --------------------------------------------------------------------- % hrf Canonical HRF % --------------------------------------------------------------------- hrf = cfg_branch; hrf.tag = 'hrf'; hrf.name = 'Canonical HRF'; hrf.val = {derivs }; hrf.help = {'Canonical Hemodynamic Response Function. This is the default option. Contrasts of these effects have a physical interpretation and represent a parsimonious way of characterising event-related responses. This option is also useful if you wish to look separately at activations and deactivations (this is implemented using a t-contrast with a +1 or -1 entry over the canonical regressor). '}; % --------------------------------------------------------------------- % length Window length % --------------------------------------------------------------------- length = cfg_entry; length.tag = 'length'; length.name = 'Window length'; length.help = {'Post-stimulus window length (in seconds)'}; length.strtype = 'e'; length.num = [1 1]; % --------------------------------------------------------------------- % order Order % --------------------------------------------------------------------- order = cfg_entry; order.tag = 'order'; order.name = 'Order'; order.help = {'Number of basis functions'}; order.strtype = 'e'; order.num = [1 1]; % --------------------------------------------------------------------- % fourier Fourier Set % --------------------------------------------------------------------- fourier = cfg_branch; fourier.tag = 'fourier'; fourier.name = 'Fourier Set'; fourier.val = {length order }; fourier.help = {'Fourier basis functions. This option requires an SPM{F} for inference.'}; % --------------------------------------------------------------------- % length Window length % --------------------------------------------------------------------- length = cfg_entry; length.tag = 'length'; length.name = 'Window length'; length.help = {'Post-stimulus window length (in seconds)'}; length.strtype = 'e'; length.num = [1 1]; % --------------------------------------------------------------------- % order Order % --------------------------------------------------------------------- order = cfg_entry; order.tag = 'order'; order.name = 'Order'; order.help = {'Number of basis functions'}; order.strtype = 'e'; order.num = [1 1]; % --------------------------------------------------------------------- % fourier_han Fourier Set (Hanning) % --------------------------------------------------------------------- fourier_han = cfg_branch; fourier_han.tag = 'fourier_han'; fourier_han.name = 'Fourier Set (Hanning)'; fourier_han.val = {length order }; fourier_han.help = {'Fourier basis functions with Hanning Window - requires SPM{F} for inference.'}; % --------------------------------------------------------------------- % length Window length % --------------------------------------------------------------------- length = cfg_entry; length.tag = 'length'; length.name = 'Window length'; length.help = {'Post-stimulus window length (in seconds)'}; length.strtype = 'e'; length.num = [1 1]; % --------------------------------------------------------------------- % order Order % --------------------------------------------------------------------- order = cfg_entry; order.tag = 'order'; order.name = 'Order'; order.help = {'Number of basis functions'}; order.strtype = 'e'; order.num = [1 1]; % --------------------------------------------------------------------- % gamma Gamma Functions % --------------------------------------------------------------------- gamma = cfg_branch; gamma.tag = 'gamma'; gamma.name = 'Gamma Functions'; gamma.val = {length order }; gamma.help = {'Gamma basis functions - requires SPM{F} for inference.'}; % --------------------------------------------------------------------- % length Window length % --------------------------------------------------------------------- length = cfg_entry; length.tag = 'length'; length.name = 'Window length'; length.help = {'Post-stimulus window length (in seconds)'}; length.strtype = 'e'; length.num = [1 1]; % --------------------------------------------------------------------- % order Order % --------------------------------------------------------------------- order = cfg_entry; order.tag = 'order'; order.name = 'Order'; order.help = {'Number of basis functions'}; order.strtype = 'e'; order.num = [1 1]; % --------------------------------------------------------------------- % fir Finite Impulse Response % --------------------------------------------------------------------- fir = cfg_branch; fir.tag = 'fir'; fir.name = 'Finite Impulse Response'; fir.val = {length order }; fir.help = {'Finite impulse response - requires SPM{F} for inference.'}; % --------------------------------------------------------------------- % bases Basis Functions % --------------------------------------------------------------------- bases = cfg_choice; bases.tag = 'bases'; bases.name = 'Basis Functions'; bases.val = {hrf }; bases.help = {'The most common choice of basis function is the Canonical HRF with or without time and dispersion derivatives. '}; bases.values = {hrf fourier fourier_han gamma fir }; % --------------------------------------------------------------------- % volt Model Interactions (Volterra) % --------------------------------------------------------------------- volt = cfg_menu; volt.tag = 'volt'; volt.name = 'Model Interactions (Volterra)'; volt.help = { 'Generalized convolution of inputs (U) with basis set (bf).' '' 'For first order expansions the causes are simply convolved (e.g. stick functions) in U.u by the basis functions in bf to create a design matrix X. For second order expansions new entries appear in ind, bf and name that correspond to the interaction among the orginal causes. The basis functions for these efects are two dimensional and are used to assemble the second order kernel. Second order effects are computed for only the first column of U.u.' 'Interactions or response modulations can enter at two levels. Firstly the stick function itself can be modulated by some parametric variate (this can be time or some trial-specific variate like reaction time) modeling the interaction between the trial and the variate or, secondly interactions among the trials themselves can be modeled using a Volterra series formulation that accommodates interactions over time (and therefore within and between trial types).' }'; volt.labels = { 'Do not model Interactions' 'Model Interactions' }'; volt.values = {1 2}; volt.val = {1}; % --------------------------------------------------------------------- % global Global normalisation % --------------------------------------------------------------------- xGlobal = cfg_menu; xGlobal.tag = 'global'; xGlobal.name = 'Global normalisation'; xGlobal.help = {'Global intensity normalisation'}; xGlobal.labels = { 'Scaling' 'None' }'; xGlobal.values = { 'Scaling' 'None' }'; xGlobal.val = {'None'}; % --------------------------------------------------------------------- % cvi Serial correlations % --------------------------------------------------------------------- cvi = cfg_menu; cvi.tag = 'cvi'; cvi.name = 'Serial correlations'; cvi.help = { 'Serial correlations in fMRI time series due to aliased biorhythms and unmodelled neuronal activity can be accounted for using an autoregressive AR(1) model during Classical (ReML) parameter estimation. ' '' 'This estimate assumes the same correlation structure for each voxel, within each session. 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. ' '' 'Serial correlation can be ignored if you choose the ''none'' option. Note that the above options only apply if you later specify that your model will be estimated using the Classical (ReML) approach. If you choose Bayesian estimation these options will be ignored. For Bayesian estimation, the choice of noisemodel (AR model order) is made under the estimation options. ' }'; cvi.labels = { 'none' 'AR(1)' }'; cvi.values = { 'none' 'AR(1)' }'; for k = 1:20 label = sprintf('AR(%d) [arfit fixed order]',k); cvi.labels{end+1} = label; cvi.values{end+1} = {label k}; end for k = 1:20 label = sprintf('AR(%d) [arfit estimate order]',k); cvi.labels{end+1} = label; cvi.values{end+1} = {label -k}; end cvi.def = @(val)spm_get_defaults('stats.fmri.cvi', val{:}); % --------------------------------------------------------------------- % fmri_design fMRI model specification (design only) % --------------------------------------------------------------------- fmri_design = cfg_exbranch; fmri_design.tag = 'fmri_design'; fmri_design.name = 'fMRI model specification (design only)'; fmri_design.val = {dir timing generic generic1 bases volt xGlobal cvi }; fmri_design.help = { 'Statistical analysis of fMRI data uses a mass-univariate approach based on General Linear Models (GLMs). It comprises the following steps (1) specification of the GLM design matrix, fMRI data files and filtering (2) estimation of GLM paramaters using classical or Bayesian approaches and (3) interrogation of results using contrast vectors to produce Statistical Parametric Maps (SPMs) or Posterior Probability Maps (PPMs).' '' '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. (eg. regressor or stimulus function). You can 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 modeled 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 modeled to second order (if you specify the Volterra option). The same inputs are used by the Hemodynamic model or Dynamic Causal Models which model the convolution explicitly in terms of hidden state variables. ' '' '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 probability 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 evoked response to a specific event type (as opposed to differential responses) then a null event must be included (even if it is not modeled explicitly).' '' 'In SPM, analysis of data from multiple subjects typically proceeds in two stages using models at two ''levels''. The ''first level'' models are used to implement a within-subject analysis. Typically there will be as many first level models as there are subjects. Analysis proceeds as described using the ''Specify first level'' and ''Estimate'' options. The results of these analyses can then be presented as ''case studies''. More often, however, one wishes to make inferences about the population from which the subjects were drawn. This is an example of a ''Random-Effects (RFX) analysis'' (or, more properly, a mixed-effects analysis). In SPM, RFX analysis is implemented using the ''summary-statistic'' approach where contrast images from each subject are used as summary measures of subject responses. These are then entered as data into a ''second level'' model. ' }'; fmri_design.prog = @spm_run_fmri_design; fmri_design.vout = @vout_stats; fmri_design.modality = {'FMRI'}; %------------------------------------------------------------------------- %------------------------------------------------------------------------ function t = cond_check(job) t = {}; if (numel(job.onset) ~= numel(job.duration)) && (numel(job.duration)~=1), t = {sprintf('"%s": Number of event onsets (%d) does not match the number of durations (%d).',... job.name, numel(job.onset),numel(job.duration))}; end; for i=1:numel(job.pmod), if numel(job.onset) ~= numel(job.pmod(i).param), t = {t{:}, sprintf('"%s" & "%s":Number of event onsets (%d) does not equal the number of parameters (%d).',... job.name, job.pmod(i).name, numel(job.onset),numel(job.pmod(i).param))}; end; end; return; %------------------------------------------------------------------------- %------------------------------------------------------------------------- function t = sess_check(sess) t = {}; for i=1:numel(sess.regress), if sess.nscan ~= numel(sess.regress(i).val), t = {t{:}, sprintf('Num scans (%d) ~= Num regress[%d] (%d).',numel(sess.nscan),i,numel(sess.regress(i).val))}; end; end; return; %------------------------------------------------------------------------- %------------------------------------------------------------------------- function dep = vout_stats(job) dep(1) = cfg_dep; dep(1).sname = 'SPM.mat File'; dep(1).src_output = substruct('.','spmmat'); dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); %dep(2) = cfg_dep; %dep(2).sname = 'SPM Variable'; %dep(2).src_output = substruct('.','spmvar'); %dep(2).tgt_spec = cfg_findspec({{'strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_voi.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_voi.m
14,416
utf_8
a2ccb5fea6f79b4ec5ddf31f014ce87a
function voi = spm_cfg_voi % SPM Configuration file for VOIs %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id: spm_cfg_voi.m 4513 2011-10-07 17:26:41Z guillaume $ % ------------------------------------------------------------------------- % spmmat Select SPM.mat % ------------------------------------------------------------------------- spmmat = cfg_files; spmmat.tag = 'spmmat'; spmmat.name = 'Select SPM.mat'; spmmat.help = {'Select SPM.mat file. If empty, use the SPM.mat selected above.'}; spmmat.filter = 'mat'; spmmat.ufilter = '^SPM\.mat$'; spmmat.num = [0 1]; spmmat.val = {{''}}; % ------------------------------------------------------------------------- % contrast Contrast % ------------------------------------------------------------------------- contrast = cfg_entry; contrast.tag = 'contrast'; contrast.name = 'Contrast'; contrast.help = {'Index of contrast. If more than one index is entered, a conjunction analysis is performed.'}; contrast.strtype = 'e'; contrast.num = [1 Inf]; % ------------------------------------------------------------------------- % conjunction Conjunction Number % ------------------------------------------------------------------------- conjunction = cfg_entry; conjunction.tag = 'conjunction'; conjunction.name = 'Conjunction number'; conjunction.help = {'Conjunction number. Unused if a simple contrast is entered.' 'For Conjunction Null, enter 1.' 'For Global Null, enter the number of selected contrasts.' 'For Intermediate, enter the number of selected contrasts minus the number of effects under the Null.'}'; conjunction.strtype = 'e'; conjunction.num = [1 1]; conjunction.val = {1}; % ------------------------------------------------------------------------- % threshdesc Threshold type % ------------------------------------------------------------------------- threshdesc = cfg_menu; threshdesc.tag = 'threshdesc'; threshdesc.name = 'Threshold type'; threshdesc.help = {''}; threshdesc.labels = {'FWE' 'none'}; threshdesc.values = {'FWE' 'none'}; threshdesc.val = {'none'}; % ------------------------------------------------------------------------- % thresh Threshold % ------------------------------------------------------------------------- thresh = cfg_entry; thresh.tag = 'thresh'; thresh.name = 'Threshold'; thresh.help = {''}; thresh.strtype = 'e'; thresh.num = [1 1]; thresh.val = {0.001}; % ------------------------------------------------------------------------- % extent Extent (voxels) % ------------------------------------------------------------------------- extent = cfg_entry; extent.tag = 'extent'; extent.name = 'Extent (voxels)'; extent.help = {''}; extent.strtype = 'e'; extent.num = [1 1]; extent.val = {0}; % ------------------------------------------------------------------------- % contrast Contrast % ------------------------------------------------------------------------- contrastm = cfg_entry; contrastm.tag = 'contrast'; contrastm.name = 'Contrast'; contrastm.help = {'Indices of contrast(s).'}; contrastm.strtype = 'e'; contrastm.num = [1 Inf]; % ------------------------------------------------------------------------- % threshm Threshold % ------------------------------------------------------------------------- threshm = cfg_entry; threshm.tag = 'thresh'; threshm.name = 'Uncorrected mask p-value'; threshm.help = {''}; threshm.strtype = 'e'; threshm.num = [1 1]; threshm.val = {0.05}; % ------------------------------------------------------------------------- % mtype Nature of mask % ------------------------------------------------------------------------- mtype = cfg_menu; mtype.tag = 'mtype'; mtype.name = 'Nature of mask'; mtype.help = {''}; mtype.labels = {'Inclusive' 'Exclusive'}; mtype.values = {0 1}; % ------------------------------------------------------------------------- % mask Mask definition % ------------------------------------------------------------------------- mask = cfg_branch; mask.tag = 'mask'; mask.name = 'Mask definition'; mask.val = {contrastm threshm mtype}; mask.help = {''}; % ------------------------------------------------------------------------- % generic Masking % ------------------------------------------------------------------------- generic = cfg_repeat; generic.tag = 'generic'; generic.name = 'Masking'; generic.help = {''}; generic.values = {mask}; generic.num = [0 1]; % ------------------------------------------------------------------------- % map Thresholded SPM % ------------------------------------------------------------------------- map = cfg_branch; map.tag = 'spm'; map.name = 'Thresholded SPM'; map.val = {spmmat contrast conjunction threshdesc thresh extent generic}; map.help = {'Thresholded SPM'}'; % ------------------------------------------------------------------------- % fix Movement of centre: fixed % ------------------------------------------------------------------------- fix = cfg_const; fix.tag = 'fixed'; fix.name = 'Fixed'; fix.val = { 1 }; fix.help = {'Fixed centre'}; % ------------------------------------------------------------------------- % mp SPM index % ------------------------------------------------------------------------- mp = cfg_entry; mp.tag = 'spm'; mp.name = 'SPM index'; mp.help = {'SPM index'}; mp.strtype = 'e'; mp.num = [1 1]; % ------------------------------------------------------------------------- % mskexp Expression % ------------------------------------------------------------------------- mskexp = cfg_entry; mskexp.tag = 'mask'; mskexp.name = 'Mask expression'; mskexp.help = {'Example expressions (f):'}; mskexp.strtype = 's'; mskexp.num = [0 Inf]; mskexp.val = {''}; % ------------------------------------------------------------------------- % glob Movement of centre: Global maxima % ------------------------------------------------------------------------- glob = cfg_branch; glob.tag = 'global'; glob.name = 'Global maxima'; glob.val = { mp mskexp }; glob.help = {'Global maxima'}; % ------------------------------------------------------------------------- % loc Movement of centre: Nearest local maxima % ------------------------------------------------------------------------- loc = cfg_branch; loc.tag = 'local'; loc.name = 'Nearest local maxima'; loc.val = { mp mskexp }; loc.help = {'Nearest local maxima'}; % ------------------------------------------------------------------------- % supra Movement of centre: Nearest suprathreshold maxima % ------------------------------------------------------------------------- supra = cfg_branch; supra.tag = 'supra'; supra.name = 'Nearest suprathreshold maxima'; supra.val = { mp mskexp }; supra.help = {'Nearest suprathreshold maxima.'}; % ------------------------------------------------------------------------- % mvt Movement of centre % ------------------------------------------------------------------------- mvt = cfg_choice; mvt.tag = 'move'; mvt.name = 'Movement of centre'; mvt.help = {'Movement of centre.'}; mvt.values = {fix glob loc supra}; mvt.val = { fix }; % ------------------------------------------------------------------------- % centre Centre of Sphere/Box % ------------------------------------------------------------------------- centre = cfg_entry; centre.tag = 'centre'; centre.name = 'Centre'; centre.help = {'Centre [x y z] {mm}.'}; centre.strtype = 'e'; centre.num = [1 3]; % ------------------------------------------------------------------------- % radius Radius of Sphere % ------------------------------------------------------------------------- radius = cfg_entry; radius.tag = 'radius'; radius.name = 'Radius'; radius.help = {'Sphere radius (mm).'}; radius.strtype = 'e'; radius.num = [1 1]; % ------------------------------------------------------------------------- % sphere Sphere % ------------------------------------------------------------------------- sphere = cfg_branch; sphere.tag = 'sphere'; sphere.name = 'Sphere'; sphere.val = {centre radius mvt}; sphere.help = {'Sphere.'}'; % ------------------------------------------------------------------------- % dim Box Dimension % ------------------------------------------------------------------------- dim = cfg_entry; dim.tag = 'dim'; dim.name = 'Dimensions'; dim.help = {'Box dimensions [x y z] {mm}.'}; dim.strtype = 'e'; dim.num = [1 3]; % ------------------------------------------------------------------------- % box Box % ------------------------------------------------------------------------- box = cfg_branch; box.tag = 'box'; box.name = 'Box'; box.val = {centre dim mvt}; box.help = {'Box.'}'; % ------------------------------------------------------------------------- % image Image % ------------------------------------------------------------------------- image = cfg_files; image.tag = 'image'; image.name = 'Image file'; image.help = {'Select image.'}; image.filter = 'image'; image.ufilter = '.*'; image.num = [1 1]; % ------------------------------------------------------------------------- % threshold Threshold % ------------------------------------------------------------------------- threshold = cfg_entry; threshold.tag = 'threshold'; threshold.name = 'Threshold'; threshold.help = {'Threshold.'}; threshold.strtype = 'e'; threshold.num = [1 1]; threshold.val = {0.5}; % ------------------------------------------------------------------------- % mask Mask % ------------------------------------------------------------------------- mask = cfg_branch; mask.tag = 'mask'; mask.name = 'Mask Image'; mask.val = {image threshold}; mask.help = {'Mask Image.'}'; % ------------------------------------------------------------------------- % list List of labels % ------------------------------------------------------------------------- list = cfg_entry; list.tag = 'list'; list.name = 'List of labels'; list.help = {'List of labels.'}; list.strtype = 'e'; list.num = [1 Inf]; % ------------------------------------------------------------------------- % label Label Image % ------------------------------------------------------------------------- label = cfg_branch; label.tag = 'label'; label.name = 'Label Image'; label.val = {image list}; label.help = {'Label Image.'}'; % ------------------------------------------------------------------------- % roi ROI % ------------------------------------------------------------------------- roi = cfg_repeat; roi.tag = 'roi'; roi.name = 'Region(s) of Interest'; roi.help = {'Region(s) of Interest'}; roi.values = {map sphere box mask label}; roi.num = [1 Inf]; % ------------------------------------------------------------------------- % expression Expression % ------------------------------------------------------------------------- expression = cfg_entry; expression.tag = 'expression'; expression.name = 'Expression'; expression.help = {['Expression to be evaluated, using i1, i2, ...',... 'and logical operators (&, |, ~)']}; expression.strtype = 's'; expression.num = [2 Inf]; % ------------------------------------------------------------------------- % spmmat Select SPM.mat % ------------------------------------------------------------------------- spmmat = cfg_files; spmmat.tag = 'spmmat'; spmmat.name = 'Select SPM.mat'; spmmat.help = {'Select SPM.mat file'}; spmmat.filter = 'mat'; spmmat.ufilter = '^SPM\.mat$'; spmmat.num = [1 1]; % ------------------------------------------------------------------------- % adjust Contrast used to adjust data % ------------------------------------------------------------------------- adjust = cfg_entry; adjust.tag = 'adjust'; adjust.name = 'Adjust data'; adjust.help = {'Index of F-contrast used to adjust data. Enter ''0'' for no adjustment. Enter ''NaN'' for adjusting for everything.'}'; adjust.strtype = 'e'; adjust.num = [1 1]; % ------------------------------------------------------------------------- % session Session index % ------------------------------------------------------------------------- session = cfg_entry; session.tag = 'session'; session.name = 'Which session'; session.help = {'Enter the session number from which you want to extract data.'}'; session.strtype = 'e'; session.num = [1 1]; % ------------------------------------------------------------------------- % name Name of VOI % ------------------------------------------------------------------------- name = cfg_entry; name.tag = 'name'; name.name = 'Name of VOI'; name.help = {['Name of the VOI mat file that will be saved in the ' ... 'same directory than the SPM.mat file. A ''VOI_'' prefix will be added. ' ... '' ... 'A binary NIfTI image of the VOI will also be saved.']}; name.strtype = 's'; name.num = [1 Inf]; % ------------------------------------------------------------------------- % voi VOI % ------------------------------------------------------------------------- voi = cfg_exbranch; voi.tag = 'voi'; voi.name = 'Volume of Interest'; voi.val = {spmmat adjust session name roi expression}; voi.help = {' VOI time-series extraction of adjusted data (& local eigenimage analysis).'}; voi.prog = @spm_run_voi; voi.vout = @vout_voi; %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- function dep = vout_voi(varargin) dep(1) = cfg_dep; dep(1).sname = ' VOI mat File'; dep(1).src_output = substruct('.','voimat'); dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = ' VOI Image File'; dep(2).src_output = substruct('.','voiimg'); dep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_defs.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_defs.m
12,082
utf_8
d7106895556ec79d85dcffa5211d3048
function conf = spm_cfg_defs % Configuration file for deformation jobs. %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id: spm_cfg_defs.m 4136 2010-12-09 22:22:28Z guillaume $ hsummary = {[... 'This is a utility for working with deformation fields. ',... 'They can be loaded, inverted, combined etc, and the results ',... 'either saved to disk, or applied to some image.']}; hinv = {[... 'Creates the inverse of a deformation field. ',... 'Deformations are assumed to be one-to-one, in which case they ',... 'have a unique inverse. If y'':A->B is the inverse of y:B->A, then ',... 'y'' o y = y o y'' = Id, where Id is the identity transform.'],... '',... 'Deformations are inverted using the method described in the appendix of:',... [' * Ashburner J, Andersson JLR & Friston KJ (2000) ',... '"Image Registration using a Symmetric Prior - in Three-Dimensions." ',... 'Human Brain Mapping 9(4):212-225']}; hcomp = {[... 'Deformation fields can be thought of as mappings. ',... 'These can be combined by the operation of "composition", which is ',... 'usually denoted by a circle "o". ',... 'Suppose x:A->B and y:B->C are two mappings, where A, B and C refer ',... 'to domains in 3 dimensions. ',... 'Each element a in A points to element x(a) in B. ',... 'This in turn points to element y(x(a)) in C, so we have a mapping ',... 'from A to C. ',... 'The composition of these mappings is denoted by yox:A->C. ',... 'Compositions can be combined in an associative way, such that zo(yox) = (zoy)ox.'],... '',[... 'In this utility, the left-to-right order of the compositions is ',... 'from top to bottom (note that the rightmost deformation would ',... 'actually be applied first). ',... 'i.e. ...((first o second) o third)...o last. The resulting deformation field will ',... 'have the same domain as the first deformation specified, and will map ',... 'to voxels in the codomain of the last specified deformation field.']}; hsn = {[... 'Spatial normalisation, and the unified segmentation model of ',... 'SPM5 save a parameterisation of deformation fields. These consist ',... 'of a combination of an affine transform, and nonlinear warps that ',... 'are parameterised by a linear combination of cosine transform ',... 'basis functions. These are saved in *_sn.mat files, which can be ',... 'converted to deformation fields.']}; hvox = {[... 'Specify the voxel sizes of the deformation field to be produced. ',... 'Non-finite values will default to the voxel sizes of the template image',... 'that was originally used to estimate the deformation.']}; hbb = {[... 'Specify the bounding box of the deformation field to be produced. ',... 'Non-finite values will default to the bounding box of the template image',... 'that was originally used to estimate the deformation.']}; himgr = {[... 'Deformations can be thought of as vector fields. These can be represented ',... 'by three-volume images.']}; himgw = {[... 'Save the result as a three-volume image. "y_" will be prepended to the ',... 'filename. The result will be written to the current directory.']}; happly = {[... 'Apply the resulting deformation field to some images. ',... 'The warped images will be written to the current directory, and the ',... 'filenames prepended by "w". Note that trilinear interpolation is used ',... 'to resample the data, so the original values in the images will ',... 'not be preserved.']}; hmatname = {... 'Specify the _sn.mat to be used.'}; himg = {... 'Specify the image file on which to base the dimensions, orientation etc.'}; hid = {[... 'This option generates an identity transform, but this can be useful for ',... 'changing the dimensions of the resulting deformation (and any images that ',... 'are generated from it). Dimensions, orientation etc are derived from ',... 'an image.']}; def = files('Deformation Field','def','.*y_.*\.nii$',[1 1]); def.help = himgr; matname = files('Parameter File','matname','.*_sn\.mat$',[1 1]); matname.help = hmatname; vox = entry('Voxel sizes','vox','e',[1 3]); vox.val = {[NaN NaN NaN]}; vox.help = hvox; bb = entry('Bounding box','bb','e',[2 3]); bb.val = {[NaN NaN NaN;NaN NaN NaN]}; bb.help = hbb; sn2def = branch('Imported _sn.mat','sn2def',{matname,vox,bb}); sn2def.help = hsn; img = files('Image to base Id on','space','image',[1 1]); img.help = himg; id = branch('Identity (Reference Image)','id',{img}); id.help = hid; voxid = entry('Voxel sizes','vox','e',[1 3]); bbid = entry('Bounding box','bb','e',[2 3]); idbbvox = branch('Identity (Bounding Box and Voxel Size)','idbbvox',{voxid, bbid}); id.help = hid; ffield = files('Flow field','flowfield','nifti',[1 1]); ffield.ufilter = '^u_.*'; ffield.help = {... ['The flow field stores the deformation information. '... 'The same field can be used for both forward or backward deformations '... '(or even, in principle, half way or exaggerated deformations).']}; %------------------------------------------------------------------------ forbak = mnu('Forward/Backwards','times',{'Backward','Forward'},{[1 0],[0 1]}); forbak.val = {[1 0]}; forbak.help = {[... 'The direction of the DARTEL flow. '... 'Note that a backward transform will warp an individual subject''s '... 'to match the template (ie maps from template to individual). '... 'A forward transform will warp the template image to the individual.']}; %------------------------------------------------------------------------ K = mnu('Time Steps','K',... {'1','2','4','8','16','32','64','128','256','512'},... {0,1,2,3,4,5,6,7,8,9}); K.val = {6}; K.help = {... ['The number of time points used for solving the '... 'partial differential equations. A single time point would be '... 'equivalent to a small deformation model. '... 'Smaller values allow faster computations, '... 'but are less accurate in terms '... 'of inverse consistency and may result in the one-to-one mapping '... 'breaking down.']}; %------------------------------------------------------------------------ drtl = branch('DARTEL flow','dartel',{ffield,forbak,K}); drtl.help = {'Imported DARTEL flow field.'}; %------------------------------------------------------------------------ other = {sn2def,drtl,def,id,idbbvox}; img = files('Image to base inverse on','space','image',[1 1]); img.help = himg; comp0 = repeat('Composition','comp',other); comp0.help = hcomp; iv0 = branch('Inverse','inv',{comp0,img}); iv0.help = hinv; comp1 = repeat('Composition','comp',{other{:},iv0,comp0}); comp1.num = [1 Inf]; comp1.help = hcomp; iv1 = branch('Inverse','inv',{comp1,img}); iv1.help = hinv; comp2 = repeat('Composition','comp',{other{:},iv1,comp1}); comp2.num = [1 Inf]; comp2.help = hcomp; iv2 = branch('Inverse','inv',{comp2,img}); iv2.help = hinv; comp = repeat('Composition','comp',{other{:},iv2,comp2}); comp.num = [1 Inf]; comp.help = hcomp; saveas = entry('Save as','ofname','s',[0 Inf]); saveas.val = {''}; saveas.help = himgw; applyto = files('Apply to','fnames','image',[0 Inf]); applyto.val = {''}; applyto.help = happly; savepwd = cfg_const; savepwd.name = 'Current directory'; savepwd.tag = 'savepwd'; savepwd.val = {1}; savepwd.help = {['All created files (deformation fields and warped images) ' ... 'are written to the current directory.']}; savesrc = cfg_const; savesrc.name = 'Source directories'; savesrc.tag = 'savesrc'; savesrc.val = {1}; savesrc.help = {['The combined deformation field is written into the ' ... 'directory of the first deformation field, warped images ' ... 'are written to the same directories as the source ' ... 'images.']}; savedef = cfg_const; savedef.name = 'Source directory (deformation)'; savedef.tag = 'savedef'; savedef.val = {1}; savedef.help = {['The combined deformation field and the warped images ' ... 'are written into the directory of the first deformation ' ... 'field.']}; saveusr = files('Output directory','saveusr','dir',[1 1]); saveusr.help = {['The combined deformation field and the warped images ' ... 'are written into the specified directory.']}; savedir = cfg_choice; savedir.name = 'Output destination'; savedir.tag = 'savedir'; savedir.values = {savepwd savesrc savedef saveusr}; savedir.val = {savepwd}; interp = cfg_menu; interp.name = 'Interpolation'; interp.tag = 'interp'; interp.labels = {'Nearest neighbour','Trilinear','2nd Degree B-spline',... '3rd Degree B-Spline ','4th Degree B-Spline ','5th Degree B-Spline',... '6th Degree B-Spline','7th Degree B-Spline'}; interp.values = {0,1,2,3,4,5,6,7}; interp.def = @(val)spm_get_defaults('normalise.write.interp',val{:}); interp.help = { ['The method by which the images are sampled when ' ... 'being written in a different space. ' ... '(Note that Inf or NaN values are treated as zero, ' ... 'rather than as missing data)'] ' Nearest Neighbour:' ' - Fastest, but not normally recommended.' ' Bilinear Interpolation:' ' - OK for PET, realigned fMRI, or segmentations' ' B-spline Interpolation:' [' - Better quality (but slower) interpolation' ... '/* \cite{thevenaz00a}*/, especially with higher ' ... 'degree splines. Can produce values outside the ' ... 'original range (e.g. small negative values from an ' ... 'originally all positive image).'] }'; conf = exbranch('Deformations','defs',{comp,saveas,applyto,savedir,interp}); conf.prog = @spm_defs; conf.vout = @vout; conf.help = hsummary; return; %_______________________________________________________________________ %_______________________________________________________________________ function vo = vout(job) vo = []; if ~isempty(job.ofname) && ~isequal(job.ofname,'<UNDEFINED>') vo = cfg_dep; vo.sname = 'Combined deformation'; vo.src_output = substruct('.','def'); vo.tgt_spec = cfg_findspec({{'filter','image','filter','nifti'}}); end if ~isempty(job.fnames) && ~isequal(job.fnames, {''}) if isempty(vo), vo = cfg_dep; else vo(end+1) = cfg_dep; end vo(end).sname = 'Warped images'; vo(end).src_output = substruct('.','warped'); vo(end).tgt_spec = cfg_findspec({{'filter','image'}}); end return; %_______________________________________________________________________ %_______________________________________________________________________ function entry_item = entry(name, tag, strtype, num) entry_item = cfg_entry; entry_item.name = name; entry_item.tag = tag; entry_item.strtype = strtype; entry_item.num = num; function files_item = files(name, tag, fltr, num) files_item = cfg_files; files_item.name = name; files_item.tag = tag; files_item.filter = fltr; files_item.num = num; function branch_item = branch(name, tag, val) branch_item = cfg_branch; branch_item.name = name; branch_item.tag = tag; branch_item.val = val; function exbranch_item = exbranch(name, tag, val) exbranch_item = cfg_exbranch; exbranch_item.name = name; exbranch_item.tag = tag; exbranch_item.val = val; function repeat_item = repeat(name, tag, values) repeat_item = cfg_repeat; repeat_item.name = name; repeat_item.tag = tag; repeat_item.values = values; function menu_item = mnu(name, tag, labels, values) menu_item = cfg_menu; menu_item.name = name; menu_item.tag = tag; menu_item.labels = labels; menu_item.values = values;
github
philippboehmsturm/antx-master
spm_cfg_coreg.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_coreg.m
15,295
utf_8
d33c81d106b8fca36404ed99f363be34
function coreg = spm_cfg_coreg % SPM Configuration file for Coregister %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_coreg.m 4380 2011-07-05 11:27:12Z volkmar $ % --------------------------------------------------------------------- % ref Reference Image % --------------------------------------------------------------------- ref = cfg_files; ref.tag = 'ref'; ref.name = 'Reference Image'; ref.help = {'This is the image that is assumed to remain stationary (sometimes known as the target or template image), while the source image is moved to match it.'}; ref.filter = 'image'; ref.ufilter = '.*'; ref.num = [1 1]; % --------------------------------------------------------------------- % source Source Image % --------------------------------------------------------------------- source = cfg_files; source.tag = 'source'; source.name = 'Source Image'; source.help = {'This is the image that is jiggled about to best match the reference.'}; source.filter = 'image'; source.ufilter = '.*'; source.num = [1 1]; % --------------------------------------------------------------------- % other Other Images % --------------------------------------------------------------------- other = cfg_files; other.tag = 'other'; other.name = 'Other Images'; other.val = {{''}}; other.help = {'These are any images that need to remain in alignment with the source image.'}; other.filter = 'image'; other.ufilter = '.*'; other.num = [0 Inf]; % --------------------------------------------------------------------- % cost_fun Objective Function % --------------------------------------------------------------------- cost_fun = cfg_menu; cost_fun.tag = 'cost_fun'; cost_fun.name = 'Objective Function'; cost_fun.help = {'Registration involves finding parameters that either maximise or minimise some objective function. For inter-modal registration, use Mutual Information/* \cite{collignon95,wells96}*/, Normalised Mutual Information/* \cite{studholme99}*/, or Entropy Correlation Coefficient/* \cite{maes97}*/.For within modality, you could also use Normalised Cross Correlation.'}; cost_fun.labels = { 'Mutual Information' 'Normalised Mutual Information' 'Entropy Correlation Coefficient' 'Normalised Cross Correlation' }'; cost_fun.values = { 'mi' 'nmi' 'ecc' 'ncc' }'; cost_fun.def = @(val)spm_get_defaults('coreg.estimate.cost_fun', val{:}); % --------------------------------------------------------------------- % sep Separation % --------------------------------------------------------------------- sep = cfg_entry; sep.tag = 'sep'; sep.name = 'Separation'; sep.help = {'The average distance between sampled points (in mm). Can be a vector to allow a coarse registration followed by increasingly fine ones.'}; sep.strtype = 'e'; sep.num = [1 Inf]; sep.def = @(val)spm_get_defaults('coreg.estimate.sep', val{:}); % --------------------------------------------------------------------- % tol Tolerances % --------------------------------------------------------------------- tol = cfg_entry; tol.tag = 'tol'; tol.name = 'Tolerances'; tol.help = {'The accuracy for each parameter. Iterations stop when differences between successive estimates are less than the required tolerance.'}; tol.strtype = 'e'; tol.num = [1 12]; tol.def = @(val)spm_get_defaults('coreg.estimate.tol', val{:}); % --------------------------------------------------------------------- % fwhm Histogram Smoothing % --------------------------------------------------------------------- fwhm = cfg_entry; fwhm.tag = 'fwhm'; fwhm.name = 'Histogram Smoothing'; fwhm.help = {'Gaussian smoothing to apply to the 256x256 joint histogram. Other information theoretic coregistration methods use fewer bins, but Gaussian smoothing seems to be more elegant.'}; fwhm.strtype = 'e'; fwhm.num = [1 2]; fwhm.def = @(val)spm_get_defaults('coreg.estimate.fwhm', val{:}); % --------------------------------------------------------------------- % eoptions Estimation Options % --------------------------------------------------------------------- eoptions = cfg_branch; eoptions.tag = 'eoptions'; eoptions.name = 'Estimation Options'; eoptions.val = {cost_fun sep tol fwhm }; eoptions.help = {'Various registration options, which are passed to the Powell optimisation algorithm/* \cite{press92}*/.'}; % --------------------------------------------------------------------- % estimate Coreg: Estimate % --------------------------------------------------------------------- estimate = cfg_exbranch; estimate.tag = 'estimate'; estimate.name = 'Coregister: Estimate'; estimate.val = {ref source other eoptions }; estimate.help = { 'The registration method used here is based on work by Collignon et al/* \cite{collignon95}*/. 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.' '' 'At the end of coregistration, 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.' '' 'Registration parameters are stored in the headers of the "source" and the "other" images.' }'; estimate.prog = @spm_run_coreg_estimate; estimate.vout = @vout_estimate; % --------------------------------------------------------------------- % ref Image Defining Space % --------------------------------------------------------------------- refwrite = cfg_files; refwrite.tag = 'ref'; refwrite.name = 'Image Defining Space'; refwrite.help = {'This is analogous to the reference image. Images are resliced to match this image (providing they have been coregistered first).'}; refwrite.filter = 'image'; refwrite.ufilter = '.*'; refwrite.num = [1 1]; % --------------------------------------------------------------------- % source Images to Reslice % --------------------------------------------------------------------- source = cfg_files; source.tag = 'source'; source.name = 'Images to Reslice'; source.help = {'These images are resliced to the same dimensions, voxel sizes, orientation etc as the space defining image.'}; source.filter = 'image'; source.ufilter = '.*'; source.num = [1 Inf]; % --------------------------------------------------------------------- % interp Interpolation % --------------------------------------------------------------------- interp = cfg_menu; interp.tag = 'interp'; interp.name = 'Interpolation'; interp.help = {'The method by which the images are sampled when being written in a different space. Nearest Neighbour is fastest, but not normally recommended. It can be useful for re-orienting images while preserving the original intensities (e.g. an image consisting of labels). Bilinear Interpolation is OK for PET, or realigned and re-sliced fMRI. If subject movement (from an fMRI time series) is included in the transformations then it may be better to use a higher degree approach. Note that higher degree B-spline interpolation/* \cite{thevenaz00a,unser93a,unser93b}*/ is slower because it uses more neighbours.'}; interp.labels = { 'Nearest neighbour' 'Trilinear' '2nd Degree B-Spline' '3rd Degree B-Spline' '4th Degree B-Spline' '5th Degree B-Spline' '6th Degree B-Spline' '7th Degree B-Spline' }'; interp.values = {0 1 2 3 4 5 6 7}; interp.def = @(val)spm_get_defaults('coreg.write.interp', val{:}); % --------------------------------------------------------------------- % wrap Wrapping % --------------------------------------------------------------------- wrap = cfg_menu; wrap.tag = 'wrap'; wrap.name = 'Wrapping'; wrap.help = { 'These are typically:' ' No wrapping - for PET or images that have already been spatially transformed.' ' Wrap in Y - for (un-resliced) MRI where phase encoding is in the Y direction (voxel space).' }'; wrap.labels = { 'No wrap' 'Wrap X' 'Wrap Y' 'Wrap X & Y' 'Wrap Z' 'Wrap X & Z' 'Wrap Y & Z' 'Wrap X, Y & Z' }'; wrap.values = {[0 0 0] [1 0 0] [0 1 0] [1 1 0] [0 0 1] [1 0 1] [0 1 1]... [1 1 1]}; wrap.def = @(val)spm_get_defaults('coreg.write.wrap', val{:}); % --------------------------------------------------------------------- % mask Masking % --------------------------------------------------------------------- mask = cfg_menu; mask.tag = 'mask'; mask.name = 'Masking'; mask.help = {'Because of subject motion, different images are likely to have different patterns of zeros from where it was not possible to sample data. With masking enabled, the program searches through the whole time series looking for voxels which need to be sampled from outside the original images. Where this occurs, that voxel is set to zero for the whole set of images (unless the image format can represent NaN, in which case NaNs are used where possible).'}; mask.labels = { 'Mask images' 'Dont mask images' }'; mask.values = {1 0}; mask.def = @(val)spm_get_defaults('coreg.write.mask', val{:}); % --------------------------------------------------------------------- % prefix Filename Prefix % --------------------------------------------------------------------- prefix = cfg_entry; prefix.tag = 'prefix'; prefix.name = 'Filename Prefix'; prefix.help = {'Specify the string to be prepended to the filenames of the resliced image file(s). Default prefix is ''r''.'}; prefix.strtype = 's'; prefix.num = [1 Inf]; prefix.def = @(val)spm_get_defaults('coreg.write.prefix', val{:}); % --------------------------------------------------------------------- % roptions Reslice Options % --------------------------------------------------------------------- roptions = cfg_branch; roptions.tag = 'roptions'; roptions.name = 'Reslice Options'; roptions.val = {interp wrap mask prefix }; roptions.help = {'Various reslicing options.'}; % --------------------------------------------------------------------- % write Coreg: Reslice % --------------------------------------------------------------------- write = cfg_exbranch; write.tag = 'write'; write.name = 'Coregister: Reslice'; write.val = {refwrite source roptions }; write.help = {'Reslice images to match voxel-for-voxel with an image defining some space. The resliced images are named the same as the originals except that they are prefixed by ''r''.'}; write.prog = @spm_run_coreg_reslice; write.vout = @vout_reslice; % --------------------------------------------------------------------- % source Source Image % --------------------------------------------------------------------- source = cfg_files; source.tag = 'source'; source.name = 'Source Image'; source.help = {'This is the image that is jiggled about to best match the reference.'}; source.filter = 'image'; source.ufilter = '.*'; source.num = [1 1]; % --------------------------------------------------------------------- % estwrite Coreg: Estimate & Reslice % --------------------------------------------------------------------- estwrite = cfg_exbranch; estwrite.tag = 'estwrite'; estwrite.name = 'Coregister: Estimate & Reslice'; estwrite.val = {ref source other eoptions roptions }; estwrite.help = { 'The registration method used here is based on work by Collignon et al/* \cite{collignon95}*/. 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.' '' 'At the end of coregistration, 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.' '' 'Registration parameters are stored in the headers of the "source" and the "other" images. These images are also resliced to match the source image voxel-for-voxel. The resliced images are named the same as the originals except that they are prefixed by ''r''.' }'; estwrite.prog = @spm_run_coreg_estwrite; estwrite.vout = @vout_estwrite; % --------------------------------------------------------------------- % coreg Coreg % --------------------------------------------------------------------- coreg = cfg_choice; coreg.tag = 'coreg'; coreg.name = 'Coregister'; coreg.help = { 'Within-subject registration using a rigid-body model. A rigid-body transformation (in 3D) can be parameterised by three translations and three rotations about the different axes.' '' 'You get the options of estimating the transformation, reslicing images according to some rigid-body transformations, or estimating and applying rigid-body transformations.' }'; coreg.values = {estimate write estwrite }; %coreg.num = [1 Inf]; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function dep = vout_estimate(job) dep(1) = cfg_dep; dep(1).sname = 'Coregistered Images'; dep(1).src_output = substruct('.','cfiles'); dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Coregistration Matrix'; dep(2).src_output = substruct('.','M'); dep(2).tgt_spec = cfg_findspec({{'strtype','r'}}); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function dep = vout_reslice(job) dep(1) = cfg_dep; dep(1).sname = 'Resliced Images'; dep(1).src_output = substruct('.','rfiles'); dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); %------------------------------------------------------------------------ %------------------------------------------------------------------------ function dep = vout_estwrite(job) depe = vout_estimate(job); depc = vout_reslice(job); dep = [depe depc];
github
philippboehmsturm/antx-master
spm_cfg_spm_surf.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_spm_surf.m
3,180
utf_8
bfb0cbe3b4a7af4aec50af905110631c
function spm_surf_node = spm_cfg_spm_surf % SPM Configuration file %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_spm_surf.m 3081 2009-04-22 20:15:38Z guillaume $ rev = '$Rev: 3081 $'; % --------------------------------------------------------------------- % data Grey+white matter image % --------------------------------------------------------------------- data = cfg_files; data.tag = 'data'; data.name = 'Grey and white matter images'; data.help = {'Images to create rendering/surface from (grey and white matter segments).'}; data.filter = 'image'; data.ufilter = '.*'; data.num = [1 Inf]; % --------------------------------------------------------------------- % mode Output % --------------------------------------------------------------------- mode = cfg_menu; mode.tag = 'mode'; mode.name = 'Output'; mode.help = {''}; mode.labels = {'Save Rendering' 'Save Extracted Surface' 'Save Rendering and Surface'}'; mode.values = {1 2 3}; mode.val = {3}; % --------------------------------------------------------------------- % thresh Surface isovalue(s) % --------------------------------------------------------------------- thresh = cfg_entry; thresh.tag = 'thresh'; thresh.name = 'Surface isovalue(s)'; thresh.help = {'Enter one or more values at which isosurfaces through the input images will be computed.'}; thresh.strtype = 'e'; thresh.val = {0.5}; thresh.num = [1 Inf]; % --------------------------------------------------------------------- % spm_surf Create Rendering/Surface % --------------------------------------------------------------------- spm_surf_node = cfg_exbranch; spm_surf_node.tag = 'spm_surf'; spm_surf_node.name = 'Create Rendering/Surface'; spm_surf_node.val = { data mode thresh}; spm_surf_node.help = {''}; spm_surf_node.prog = @spm_surf; spm_surf_node.vout = @vout_surf; % --------------------------------------------------------------------- % % --------------------------------------------------------------------- function dep = vout_surf(job) % fail silently, if job.mode or job.thresh can not be evaluated try cdep = 1; if any(job.mode==[1 3]), dep(cdep) = cfg_dep; dep(cdep).sname = 'Render .mat File'; dep(cdep).src_output = substruct('.','rendfile'); dep(cdep).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); cdep = cdep+1; end if any(job.mode==[2 3]), for k=1:numel(job.thresh) if any(job.mode==[2 3]), dep(cdep) = cfg_dep; dep(cdep).sname = sprintf('Surface .gii File (thr=%.02f)', ... job.thresh(k)); dep(cdep).src_output = substruct('.','surffile', '()',{k}); dep(cdep).tgt_spec = cfg_findspec({{'filter','mesh','strtype','e'}}); cdep = cdep+1; end end end catch % something failed, no dependencies dep = []; end
github
philippboehmsturm/antx-master
spm_run_voi.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_run_voi.m
7,634
utf_8
028d2bd9767100793c0c5af2426d1a0b
function out = spm_run_voi(job) % SPM job execution function % takes a harvested job data structure and call SPM functions to perform % computations on the data. % Input: % job - harvested job data structure (see matlabbatch help) % Output: % out - computation results, usually a struct variable. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Guillaume Flandin % $Id: spm_run_voi.m 4269 2011-03-29 16:03:43Z guillaume $ fprintf('## Note: this VOI facility is in a beta version. ##\n'); fprintf('## Interface and features might change in the future. ##\n'); %-Load SPM.mat %-------------------------------------------------------------------------- swd = spm_str_manip(job.spmmat{1},'H'); load(fullfile(swd,'SPM.mat')); SPM.swd = swd; %-Initialise VOI voxels coordinates %-------------------------------------------------------------------------- [x,y,z] = ndgrid(1:SPM.xVol.DIM(1),1:SPM.xVol.DIM(2),1:SPM.xVol.DIM(3)); XYZ = [x(:),y(:),z(:)]'; clear x y z XYZmm = SPM.xVol.M(1:3,:) * [XYZ;ones(1,size(XYZ,2))]; %-Estimate VOIs %-------------------------------------------------------------------------- voi = cell(1,numel(job.roi)); for i=1:numel(job.roi) voi = roi_estim(XYZmm,i,job,SPM,voi); end %-Evaluate resulting VOI %-------------------------------------------------------------------------- voi = roi_eval(voi,job.expression); %-Save VOI as image %-------------------------------------------------------------------------- V = struct('fname', fullfile(swd, ['VOI_' job.name '.' spm_get_defaults('images.format')]), ... 'dim', SPM.xVol.DIM', ... 'dt', [spm_type('uint8') spm_platform('bigend')], ... 'mat', SPM.xVol.M, ... 'pinfo', [1 0 0]', ... 'descrip', 'VOI'); V = spm_create_vol(V); for i=1:V.dim(3) V = spm_write_plane(V,voi(:,:,i),i); end %-Extract VOI time-series %-------------------------------------------------------------------------- xY.name = job.name; xY.Ic = job.adjust; xY.Sess = job.session; xY.xyz = []'; % irrelevant here xY.def = 'mask'; xY.spec = V; xSPM.XYZmm = XYZmm; xSPM.XYZ = XYZ; xSPM.M = SPM.xVol.M; % irrelevant here if ~isempty(xY.Ic), cwd = pwd; cd(SPM.swd); end % to find beta images [Y,xY] = spm_regions(xSPM,SPM,[],xY); if ~isempty(xY.Ic), cd(cwd); end %-Export results %-------------------------------------------------------------------------- assignin('base','Y',Y); assignin('base','xY',xY); if isfield(SPM,'Sess'), s = sprintf('_%i',xY.Sess); else s = ''; end out.voimat = cellstr(fullfile(swd,['VOI_' job.name s '.mat'])); out.voiimg = cellstr(V.fname); %========================================================================== function voi = roi_estim(xyz,n,job,SPM,voi) if ~isempty(voi{n}), return; end voi{n} = false(SPM.xVol.DIM'); Q = ones(1,size(xyz,2)); switch char(fieldnames(job.roi{n})) case 'sphere' %---------------------------------------------------------------------- c = get_centre(xyz,n,job,SPM,voi); r = job.roi{n}.sphere.radius; voi{n}(sum((xyz - c*Q).^2) <= r^2) = true; case 'box' %---------------------------------------------------------------------- c = get_centre(xyz,n,job,SPM,voi); d = job.roi{n}.box.dim(:); voi{n}(all(abs(xyz - c*Q) <= d*Q/2)) = true; case 'spm' %---------------------------------------------------------------------- if isempty(job.roi{n}.spm.spmmat{1}) job.roi{n}.spm.spmmat = job.spmmat; end [SPM1,xSPM] = getSPM(job.roi{n}.spm); voi1 = zeros(SPM1.xVol.DIM'); voi1(sub2ind(SPM1.xVol.DIM',xSPM.XYZ(1,:),xSPM.XYZ(2,:),xSPM.XYZ(3,:))) = 1; XYZ = SPM1.xVol.iM(1:3,:)*[xyz; Q]; voi{n}(spm_sample_vol(voi1, XYZ(1,:), XYZ(2,:), XYZ(3,:),0) > 0) = true; case 'mask' %---------------------------------------------------------------------- v = spm_vol(job.roi{n}.mask.image{1}); t = job.roi{n}.mask.threshold; iM = inv(v.mat); XYZ = iM(1:3,:)*[xyz; Q]; voi{n}(spm_sample_vol(v, XYZ(1,:), XYZ(2,:), XYZ(3,:),0) > t) = true; case 'label' %---------------------------------------------------------------------- v = spm_vol(job.roi{n}.label.image{1}); l = job.roi{n}.label.list; iM = inv(v.mat); XYZ = iM(1:3,:)*[xyz; Q]; voi{n}(ismember(spm_sample_vol(v, XYZ(1,:), XYZ(2,:), XYZ(3,:),0),l)) = true; end %========================================================================== function voi = roi_eval(voi,expr) for i=1:numel(voi) eval(sprintf('i%d=voi{%d};',i,i)); end try eval(['voi=' expr ';']); catch error('The expression cannot be evaluated.'); end %========================================================================== function idx = roi_expr(expr) e = regexp(expr,'i\d+','match'); idx = zeros(1,numel(e)); for i=1:numel(e) idx(i) = str2num(e{i}(2:end)); end %========================================================================== function [SPM, xSPM] = getSPM(s) xSPM.swd = spm_str_manip(s.spmmat{1},'H'); xSPM.Ic = s.contrast; xSPM.n = s.conjunction; xSPM.u = s.thresh; xSPM.thresDesc = s.threshdesc; xSPM.k = s.extent; xSPM.title = ''; xSPM.Im = []; if ~isempty(s.mask) xSPM.Im = s.mask.contrast; xSPM.pm = s.mask.thresh; xSPM.Ex = s.mask.mtype; end [SPM,xSPM] = spm_getSPM(xSPM); %========================================================================== function c = get_centre(xyz,n,job,SPM,voi) t = char(fieldnames(job.roi{n})); c = job.roi{n}.(t).centre(:); mv = char(fieldnames(job.roi{n}.(t).move)); if strcmp(mv,'fixed'), return; end m = job.roi{n}.(t).move.(mv).spm; e = job.roi{n}.(t).move.(mv).mask; k = union(roi_expr(e), m); for i=1:numel(k) voi = roi_estim(xyz,k(i),job,SPM,voi); end try if isempty(job.roi{m}.spm.spmmat{1}) job.roi{m}.spm.spmmat = job.spmmat; end catch error('The SPM index does not correspond to a Thresholded SPM ROI.'); end [mySPM, xSPM] = getSPM(job.roi{m}.spm); XYZmm = xSPM.XYZmm; XYZ = SPM.xVol.iM(1:3,:)*[XYZmm;ones(1,size(XYZmm,2))]; Z = xSPM.Z; if ~isempty(e) R = spm_sample_vol(uint8(roi_eval(voi,e)), ... XYZ(1,:), XYZ(2,:), XYZ(3,:),0) > 0; XYZ = XYZ(:,R); XYZmm = xSPM.XYZmm(:,R); Z = xSPM.Z(R); end [N, Z, M] = spm_max(Z,XYZ); if isempty(Z) warning('No voxel survived. Default to user-specified centre.'); return end str = '[%3.0f %3.0f %3.0f]'; switch mv case 'global' [i,j] = max(Z); nc = SPM.xVol.M(1:3,:)*[M(:,j);1]; str = sprintf(['centre moved to global maxima ' str],nc); case 'local' XYZmm = SPM.xVol.M(1:3,:)*[M;ones(1,size(M,2))]; nc = spm_XYZreg('NearestXYZ',c,XYZmm); str = sprintf(['centre moved from ' str ' to ' str],c,nc); case 'supra' nc = spm_XYZreg('NearestXYZ',c,XYZmm); str = sprintf(['centre moved from ' str ' to ' str],c,nc); otherwise error(sprintf('Unknown option: ''%s''.',mv)); end c = nc; fprintf([' ' upper(t(1)) t(2:end) ' ' str '\n']); %-#
github
philippboehmsturm/antx-master
spm_cfg_eeg_merge.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_merge.m
2,920
utf_8
5724987e1f048f63b75ae6f68520be28
function S = spm_cfg_eeg_merge % configuration file for merging of M/EEG files %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel, Volkmar Glauche % $Id: spm_cfg_eeg_merge.m 3881 2010-05-07 21:02:57Z vladimir $ rev = '$Rev: 3881 $'; D = cfg_files; D.tag = 'D'; D.name = 'File Names'; D.filter = 'mat'; D.num = [2 Inf]; D.help = {'Select the M/EEG mat files.'}; file = cfg_entry; file.tag = 'file'; file.name = 'Files to which the rule applies'; file.strtype = 's'; file.val = {'.*'}; file.help = {'Regular expression to match the files to which the rule applies (default - all)'}; labelorg = cfg_entry; labelorg.tag = 'labelorg'; labelorg.name = 'Original labels to which the rule applies'; labelorg.strtype = 's'; labelorg.val = {'.*'}; labelorg.help = {'Regular expression to match the original condition labels to which the rule applies (default - all)'}; labelnew = cfg_entry; labelnew.tag = 'labelnew'; labelnew.name = 'New label for the merged file'; labelnew.strtype = 's'; labelnew.val = {'#labelorg#'}; labelnew.help = {['New condition label for the merged file. Special tokens can be used as part of the name. '... '#file# will be replaced by the name of the original file, #labelorg# will be replaced by the original '... 'condition labels.']}; rule = cfg_branch; rule.tag = 'rule'; rule.name = 'Recoding rule'; rule.val = {file, labelorg, labelnew}; rule.help = {'Recoding rule. The default means that all trials will keep their original label.'}; rules = cfg_repeat; rules.tag = 'unused'; rules.name = 'Condition label recoding rules'; rules.values = {rule}; rules.num = [1 Inf]; rules.val = {rule}; rules.help = {['Specify the rules for translating condition labels from ' ... 'the original files to the merged file. Multiple rules can be specified. The later ' ... 'rules have precedence. Trials not matched by any of the rules will keep their original labels.']}; S = cfg_exbranch; S.tag = 'merge'; S.name = 'M/EEG Merging'; S.val = {D, rules}; S.help = {'Merge EEG/MEG data.'}; S.prog = @eeg_merge; S.vout = @vout_eeg_merge; S.modality = {'EEG'}; function out = eeg_merge(job) % construct the S struct S.D = strvcat(job.D{:}); S.recode = job.rule; out.D = spm_eeg_merge(S); out.Dfname = {fullfile(out.D.path, out.D.fname)}; function dep = vout_eeg_merge(job) % Output is always in field "D", no matter how job is structured dep = cfg_dep; dep.sname = 'Merged Data'; % reference field "D" from output dep.src_output = substruct('.','D'); % this can be entered into any evaluated input dep.tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Merged Datafile'; % reference field "Dfname" from output dep(2).src_output = substruct('.','Dfname'); % this can be entered into any file selector dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_cfg_eeg_artefact.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_artefact.m
2,704
utf_8
9be0b57d491daf05b39ef0bb0e836673
function S = spm_cfg_eeg_artefact % configuration file for M/EEG artefact detection %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Vladimir Litvak % $Id: spm_cfg_eeg_artefact.m 3881 2010-05-07 21:02:57Z vladimir $ rev = '$Rev: 3881 $'; D = cfg_files; D.tag = 'D'; D.name = 'File Name'; D.filter = 'mat'; D.num = [1 1]; D.help = {'Select the EEG mat file.'}; badchanthresh = cfg_entry; badchanthresh.tag = 'badchanthresh'; badchanthresh.name = 'Bad channel threshold'; badchanthresh.strtype = 'r'; badchanthresh.num = [1 1]; badchanthresh.val = {0.2}; badchanthresh.help = {'Fraction of trials with artefacts ', ... 'above which an M/EEG channel is declared as bad.'}; artefact_funs = dir(fullfile(spm('dir'), 'spm_eeg_artefact_*.m')); artefact_funs = {artefact_funs(:).name}; fun = cfg_choice; fun.tag = 'fun'; fun.name = 'Detection algorithm'; for i = 1:numel(artefact_funs) fun.values{i} = feval(spm_str_manip(artefact_funs{i}, 'r')); end methods = cfg_branch; methods.tag = 'methods'; methods.name = 'Method'; methods.val = {spm_cfg_eeg_channel_selector, fun}; methodsrep = cfg_repeat; methodsrep.tag = 'methodsrep'; methodsrep.name = 'How to look for artefacts'; methodsrep.help = {'Choose channels and methods for artefact detection'}; methodsrep.values = {methods}; methodsrep.num = [1 Inf]; S = cfg_exbranch; S.tag = 'artefact'; S.name = 'M/EEG Artefact detection'; S.val = {D, badchanthresh, methodsrep}; S.help = {'Detect artefacts in epoched M/EEG data.'}; S.prog = @eeg_artefact; S.vout = @vout_eeg_artefact; S.modality = {'EEG'}; function out = eeg_artefact(job) % construct the S struct S.D = job.D{1}; S.badchanthresh = job.badchanthresh; for i = 1:numel(job.methods) S.methods(i).channels = spm_cfg_eeg_channel_selector(job.methods(i).channels); fun = fieldnames(job.methods(i).fun); fun = fun{1}; S.methods(i).fun = fun; S.methods(i).settings = getfield(job.methods(i).fun, fun); end out.D = spm_eeg_artefact(S); out.Dfname = {fullfile(out.D.path, out.D.fname)}; function dep = vout_eeg_artefact(job) % Output is always in field "D", no matter how job is structured dep = cfg_dep; dep.sname = 'Artefact detection'; % reference field "D" from output dep.src_output = substruct('.','D'); % this can be entered into any evaluated input dep.tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Artefact-detected Datafile'; % reference field "Dfname" from output dep(2).src_output = substruct('.','Dfname'); % this can be entered into any file selector dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_run_fmri_spec.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_run_fmri_spec.m
11,586
utf_8
323408725405fe269ac8eb5e2e667b6c
function out = spm_run_fmri_spec(job) % Set up the design matrix and run a design. % SPM job execution function % takes a harvested job data structure and call SPM functions to perform % computations on the data. % Input: % job - harvested job data structure (see matlabbatch help) % Output: % out - computation results, usually a struct variable. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_run_fmri_spec.m 4185 2011-02-01 18:46:18Z guillaume $ original_dir = pwd; my_cd(job.dir); %-Ask about overwriting files from previous analyses %-------------------------------------------------------------------------- if exist(fullfile(job.dir{1},'SPM.mat'),'file') str = { 'Current directory contains existing SPM file:',... 'Continuing will overwrite existing file!'}; if spm_input(str,1,'bd','stop|continue',[1,0],1,mfilename); fprintf('%-40s: %30s\n\n',... 'Abort... (existing SPM file)',spm('time')); return end end % If we've gotten to this point we're committed to overwriting files. % Delete them so we don't get stuck in spm_spm %-------------------------------------------------------------------------- files = {'^mask\..{3}$','^ResMS\..{3}$','^RPV\..{3}$',... '^beta_.{4}\..{3}$','^con_.{4}\..{3}$','^ResI_.{4}\..{3}$',... '^ess_.{4}\..{3}$', '^spm\w{1}_.{4}\..{3}$'}; for i=1:length(files) j = spm_select('List',pwd,files{i}); for k=1:size(j,1) spm_unlink(deblank(j(k,:))); end end % Variables %-------------------------------------------------------------------------- SPM.xY.RT = job.timing.RT; SPM.xY.P = []; % Slice timing %-------------------------------------------------------------------------- % The following lines have the side effect of modifying the global % defaults variable. This is necessary to pass job.timing.fmri_t to % spm_hrf.m. The original values are saved here and restored at the end % of this function, after the design has been specified. The original % values may not be restored if this function crashes. olddefs.stats.fmri.fmri_t = spm_get_defaults('stats.fmri.fmri_t'); olddefs.stats.fmri.fmri_t0 = spm_get_defaults('stats.fmri.fmri_t0'); spm_get_defaults('stats.fmri.t', job.timing.fmri_t); spm_get_defaults('stats.fmri.t0', job.timing.fmri_t0); % Basis function variables %-------------------------------------------------------------------------- SPM.xBF.UNITS = job.timing.units; SPM.xBF.dt = job.timing.RT/job.timing.fmri_t; SPM.xBF.T = job.timing.fmri_t; SPM.xBF.T0 = job.timing.fmri_t0; % Basis functions %-------------------------------------------------------------------------- if strcmp(fieldnames(job.bases),'hrf') if all(job.bases.hrf.derivs == [0 0]) SPM.xBF.name = 'hrf'; elseif all(job.bases.hrf.derivs == [1 0]) SPM.xBF.name = 'hrf (with time derivative)'; elseif all(job.bases.hrf.derivs == [1 1]) SPM.xBF.name = 'hrf (with time and dispersion derivatives)'; else error('Unrecognized hrf derivative choices.') end else nambase = fieldnames(job.bases); if ischar(nambase) nam=nambase; else nam=nambase{1}; end switch nam, case 'fourier', SPM.xBF.name = 'Fourier set'; case 'fourier_han', SPM.xBF.name = 'Fourier set (Hanning)'; case 'gamma', SPM.xBF.name = 'Gamma functions'; case 'fir', SPM.xBF.name = 'Finite Impulse Response'; otherwise error('Unrecognized hrf derivative choices.') end SPM.xBF.length = job.bases.(nam).length; SPM.xBF.order = job.bases.(nam).order; end SPM.xBF = spm_get_bf(SPM.xBF); if isempty(job.sess), SPM.xBF.Volterra = false; else SPM.xBF.Volterra = job.volt; end for i = 1:numel(job.sess), sess = job.sess(i); % Image filenames %---------------------------------------------------------------------- SPM.nscan(i) = numel(sess.scans); SPM.xY.P = strvcat(SPM.xY.P,sess.scans{:}); U = []; % Augment the singly-specified conditions with the multiple % conditions specified in a .mat file provided by the user %---------------------------------------------------------------------- if ~isempty(sess.multi{1}) try multicond = load(sess.multi{1}); catch error('Cannot load %s',sess.multi{1}); end if ~(isfield(multicond,'names')&&isfield(multicond,'onsets')&&... isfield(multicond,'durations')) || ... ~all([numel(multicond.names),numel(multicond.onsets), ... numel(multicond.durations)]==numel(multicond.names)) error(['Multiple conditions MAT-file ''%s'' is invalid.\n',... 'File must contain names, onsets, and durations '... 'cell arrays of equal length.\n'],sess.multi{1}); end %-contains three cell arrays: names, onsets and durations for j=1:length(multicond.onsets) cond.name = multicond.names{j}; cond.onset = multicond.onsets{j}; cond.duration = multicond.durations{j}; % Mutiple Conditions Time Modulation %-------------------------------------------------------------- % initialise the variable. cond.tmod = 0; if isfield(multicond,'tmod'); try cond.tmod = multicond.tmod{j}; catch error('Error specifying time modulation.'); end end % Mutiple Conditions Parametric Modulation %-------------------------------------------------------------- % initialise the parametric modulation variable. cond.pmod = []; if isfield(multicond,'pmod') % only access existing modulators try % check if there is a parametric modulator. this allows % pmod structures with fewer entries than conditions. % then check whether any cells are filled in. if (j <= numel(multicond.pmod)) && ... ~isempty(multicond.pmod(j).name) % we assume that the number of cells in each % field of pmod is the same (or should be). for ii = 1:numel(multicond.pmod(j).name) cond.pmod(ii).name = multicond.pmod(j).name{ii}; cond.pmod(ii).param = multicond.pmod(j).param{ii}; cond.pmod(ii).poly = multicond.pmod(j).poly{ii}; end end; catch error('Error specifying parametric modulation.'); end end sess.cond(end+1) = cond; end end % Configure the input structure array %---------------------------------------------------------------------- for j = 1:length(sess.cond), cond = sess.cond(j); U(j).name = {cond.name}; U(j).ons = cond.onset(:); U(j).dur = cond.duration(:); if length(U(j).dur) == 1 U(j).dur = U(j).dur*ones(size(U(j).ons)); elseif length(U(j).dur) ~= length(U(j).ons) error('Mismatch between number of onset and number of durations.') end P = []; q1 = 0; if cond.tmod>0, % time effects P(1).name = 'time'; P(1).P = U(j).ons*job.timing.RT/60; P(1).h = cond.tmod; q1 = 1; end; if ~isempty(cond.pmod) for q = 1:numel(cond.pmod), % Parametric effects q1 = q1 + 1; P(q1).name = cond.pmod(q).name; P(q1).P = cond.pmod(q).param(:); P(q1).h = cond.pmod(q).poly; end; end if isempty(P) P.name = 'none'; P.h = 0; end U(j).P = P; end SPM.Sess(i).U = U; % User specified regressors %---------------------------------------------------------------------- C = []; Cname = cell(1,numel(sess.regress)); for q = 1:numel(sess.regress), Cname{q} = sess.regress(q).name; C = [C, sess.regress(q).val(:)]; end % Augment the singly-specified regressors with the multiple regressors % specified in the regressors.mat file %---------------------------------------------------------------------- if ~strcmp(sess.multi_reg,'') tmp = load(char(sess.multi_reg{:})); if isstruct(tmp) && isfield(tmp,'R') R = tmp.R; elseif isnumeric(tmp) % load from e.g. text file R = tmp; else warning('Can''t load user specified regressors in %s', ... char(sess.multi_reg{:})); R = []; end C = [C, R]; nr = size(R,2); nq = length(Cname); for inr=1:nr, Cname{inr+nq} = ['R',int2str(inr)]; end end SPM.Sess(i).C.C = C; SPM.Sess(i).C.name = Cname; end % Factorial design %-------------------------------------------------------------------------- if isfield(job,'fact') if ~isempty(job.fact) NC=length(SPM.Sess(1).U); % Number of conditions CheckNC=1; for i=1:length(job.fact) SPM.factor(i).name=job.fact(i).name; SPM.factor(i).levels=job.fact(i).levels; CheckNC=CheckNC*SPM.factor(i).levels; end if ~(CheckNC==NC) disp('Error in fmri_spec job: factors do not match conditions'); return end end else SPM.factor=[]; end % Globals %-------------------------------------------------------------------------- SPM.xGX.iGXcalc = job.global; SPM.xGX.sGXcalc = 'mean voxel value'; SPM.xGX.sGMsca = 'session specific'; % High Pass filter %-------------------------------------------------------------------------- for i = 1:numel(job.sess), SPM.xX.K(i).HParam = job.sess(i).hpf; end % Autocorrelation %-------------------------------------------------------------------------- SPM.xVi.form = job.cvi; % Let SPM configure the design %-------------------------------------------------------------------------- SPM = spm_fmri_spm_ui(SPM); if ~isempty(job.mask)&&~isempty(job.mask{1}) SPM.xM.VM = spm_vol(job.mask{:}); SPM.xM.xs.Masking = [SPM.xM.xs.Masking, '+explicit mask']; end %-Save SPM.mat %-------------------------------------------------------------------------- fprintf('%-40s: ','Saving SPM configuration') %-# if spm_check_version('matlab','7') >= 0 save('SPM.mat','-V6','SPM'); else save('SPM.mat','SPM'); end; fprintf('%30s\n','...SPM.mat saved') %-# out.spmmat{1} = fullfile(pwd, 'SPM.mat'); my_cd(original_dir); % Change back dir spm_get_defaults('stats.fmri.fmri_t',olddefs.stats.fmri.fmri_t); % Restore old timing spm_get_defaults('stats.fmri.fmri_t0',olddefs.stats.fmri.fmri_t0); % parameters fprintf('Done\n') return %========================================================================== function my_cd(jobDir) if ~isempty(jobDir) try cd(char(jobDir)); catch error('Failed to change directory. Aborting run.') end end
github
philippboehmsturm/antx-master
spm_cfg_realign.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_realign.m
22,762
utf_8
91e216ef099732fd3b42a4b8561c487c
function realign = spm_cfg_realign % SPM Configuration file % automatically generated by the MATLABBATCH utility function GENCODE %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_realign.m 4152 2011-01-11 14:13:35Z volkmar $ rev = '$Rev: 4152 $'; % --------------------------------------------------------------------- % data Session % --------------------------------------------------------------------- data = cfg_files; data.tag = 'data'; data.name = 'Session'; data.help = {'Select scans for this session. In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.'}; data.filter = 'image'; data.ufilter = '.*'; data.num = [1 Inf]; % --------------------------------------------------------------------- % generic Data % --------------------------------------------------------------------- generic = cfg_repeat; generic.tag = 'generic'; generic.name = 'Data'; generic.help = {'Add new sessions for this subject. In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.'}; generic.values = {data }; generic.num = [1 Inf]; % --------------------------------------------------------------------- % quality Quality % --------------------------------------------------------------------- quality = cfg_entry; quality.tag = 'quality'; quality.name = 'Quality'; quality.help = {'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.'}; quality.strtype = 'r'; quality.num = [1 1]; quality.extras = [0 1]; quality.def = @(val)spm_get_defaults('realign.estimate.quality', val{:}); % --------------------------------------------------------------------- % sep Separation % --------------------------------------------------------------------- sep = cfg_entry; sep.tag = 'sep'; sep.name = 'Separation'; sep.help = {'The separation (in mm) between the points sampled in the reference image. Smaller sampling distances gives more accurate results, but will be slower.'}; sep.strtype = 'e'; sep.num = [1 1]; sep.def = @(val)spm_get_defaults('realign.estimate.sep', val{:}); % --------------------------------------------------------------------- % fwhm Smoothing (FWHM) % --------------------------------------------------------------------- fwhm = cfg_entry; fwhm.tag = 'fwhm'; fwhm.name = 'Smoothing (FWHM)'; fwhm.help = { 'The FWHM of the Gaussian smoothing kernel (mm) applied to the images before estimating the realignment parameters.' '' ' * PET images typically use a 7 mm kernel.' '' ' * MRI images typically use a 5 mm kernel.' }'; fwhm.strtype = 'e'; fwhm.num = [1 1]; fwhm.def = @(val)spm_get_defaults('realign.estimate.fwhm', val{:}); % --------------------------------------------------------------------- % rtm Num Passes % --------------------------------------------------------------------- rtm = cfg_menu; rtm.tag = 'rtm'; rtm.name = 'Num Passes'; rtm.help = { 'Register to first: Images are registered to the first image in the series. Register to mean: A two pass procedure is used in order to register the images to the mean of the images after the first realignment.' '' 'PET images are typically registered to the mean. This is because PET data are more noisy than fMRI and there are fewer of them, so time is less of an issue.' '' 'MRI images are typically registered to the first image. The more accurate way would be to use a two pass procedure, but this probably wouldn''t improve the results so much and would take twice as long to run.' }'; rtm.labels = { 'Register to first' 'Register to mean' }'; rtm.values = {0 1}; rtm.def = @(val)spm_get_defaults('realign.estimate.rtm', val{:}); % --------------------------------------------------------------------- % interp Interpolation % --------------------------------------------------------------------- interp = cfg_menu; interp.tag = 'interp'; interp.name = 'Interpolation'; interp.help = {'The method by which the images are sampled when estimating the optimum transformation. Higher degree interpolation methods provide the better interpolation, but they are slower because they use more neighbouring voxels /* \cite{thevenaz00a,unser93a,unser93b}*/. '}; interp.labels = { 'Trilinear (1st Degree)' '2nd Degree B-Spline' '3rd Degree B-Spline ' '4th Degree B-Spline' '5th Degree B-Spline' '6th Degree B-Spline' '7th Degree B-Spline' }'; interp.values = {1 2 3 4 5 6 7}; interp.def = @(val)spm_get_defaults('realign.estimate.interp', val{:}); % --------------------------------------------------------------------- % wrap Wrapping % --------------------------------------------------------------------- wrap = cfg_menu; wrap.tag = 'wrap'; wrap.name = 'Wrapping'; wrap.help = { 'This indicates which directions in the volumes the values should wrap around in. For example, in MRI scans, the images wrap around in the phase encode direction, so (e.g.) the subject''s nose may poke into the back of the subject''s head. These are typically:' ' No wrapping - for PET or images that have already been spatially transformed. Also the recommended option if you are not really sure.' ' Wrap in Y - for (un-resliced) MRI where phase encoding is in the Y direction (voxel space).' }'; wrap.labels = { 'No wrap' 'Wrap X' 'Wrap Y' 'Wrap X & Y' 'Wrap Z' 'Wrap X & Z' 'Wrap Y & Z' 'Wrap X, Y & Z' }'; wrap.values = {[0 0 0] [1 0 0] [0 1 0] [1 1 0] [0 0 1] [1 0 1] [0 1 1] ... [1 1 1]}; wrap.def = @(val)spm_get_defaults('realign.estimate.wrap', val{:}); % --------------------------------------------------------------------- % weight Weighting % --------------------------------------------------------------------- weight = cfg_files; weight.tag = 'weight'; weight.name = 'Weighting'; weight.val = {''}; weight.help = {'The option of providing a weighting image to weight each voxel of the reference image differently when estimating the realignment parameters. The weights are proportional to the inverses of the standard deviations. This would be used, for example, when there is a lot of extra-brain motion - e.g., during speech, or when there are serious artifacts in a particular region of the images.'}; weight.filter = 'image'; weight.ufilter = '.*'; weight.num = [0 1]; % --------------------------------------------------------------------- % eoptions Estimation Options % --------------------------------------------------------------------- eoptions = cfg_branch; eoptions.tag = 'eoptions'; eoptions.name = 'Estimation Options'; eoptions.val = {quality sep fwhm rtm interp wrap weight }; eoptions.help = {'Various registration options. If in doubt, simply keep the default values.'}; % --------------------------------------------------------------------- % estimate Realign: Estimate % --------------------------------------------------------------------- estimate = cfg_exbranch; estimate.tag = 'estimate'; estimate.name = 'Realign: Estimate'; estimate.val = {generic eoptions }; estimate.help = { 'This routine realigns a time-series of images acquired from the same subject using a least squares approach and a 6 parameter (rigid body) spatial transformation/* \cite{friston95a}*/. The first image in the list specified by the user is used as a reference to which all subsequent scans are realigned. The reference scan does not have to the the first chronologically and it may be wise to chose a "representative scan" in this role.' '' 'The aim is primarily to remove movement artefact in fMRI and PET time-series (or more generally longitudinal studies). The headers are modified for each of the input images, such that. they reflect the relative orientations of the data. 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. These can be modelled as confounds within the general linear model/* \cite{friston95a}*/.' }'; estimate.prog = @spm_run_realign_estimate; estimate.vout = @vout_estimate; % --------------------------------------------------------------------- % data Images % --------------------------------------------------------------------- data = cfg_files; data.tag = 'data'; data.name = 'Images'; data.help = {'Select scans to reslice to match the first.'}; data.filter = 'image'; data.ufilter = '.*'; data.num = [1 Inf]; % --------------------------------------------------------------------- % which Resliced images % --------------------------------------------------------------------- which = cfg_menu; which.tag = 'which'; which.name = 'Resliced images'; which.help = { 'All Images (1..n) : This reslices all the images - including the first image selected - which will remain in its original position.' '' 'Images 2..n : Reslices images 2..n only. Useful for if you wish to reslice (for example) a PET image to fit a structural MRI, without creating a second identical MRI volume.' '' 'All Images + Mean Image : In addition to reslicing the images, it also creates a mean of the resliced image.' '' 'Mean Image Only : Creates the mean resliced image only.' }'; which.labels = { ' All Images (1..n)' 'Images 2..n' ' All Images + Mean Image' ' Mean Image Only' }'; which.values = {[2 0] [1 0] [2 1] [0 1]}; which.def = @(val)spm_get_defaults('realign.write.which', val{:}); % --------------------------------------------------------------------- % interp Interpolation % --------------------------------------------------------------------- interp = cfg_menu; interp.tag = 'interp'; interp.name = 'Interpolation'; interp.help = {'The method by which the images are sampled when being written in a different space. Nearest Neighbour is fastest, but not recommended for image realignment. Bilinear Interpolation is probably OK for PET, but not so suitable for fMRI because higher degree interpolation generally gives better results/* \cite{thevenaz00a,unser93a,unser93b}*/. Although higher degree methods provide better interpolation, but they are slower because they use more neighbouring voxels. Fourier Interpolation/* \cite{eddy96,cox99}*/ is another option, but note that it is only implemented for purely rigid body transformations. Voxel sizes must all be identical and isotropic.'}; interp.labels = { 'Nearest neighbour' 'Trilinear' '2nd Degree B-Spline' '3rd Degree B-Spline' '4th Degree B-Spline' '5th Degree B-Spline' '6th Degree B-Spline' '7th Degree B-Spline' 'Fourier Interpolation' }'; interp.values = {0 1 2 3 4 5 6 7 Inf}; interp.def = @(val)spm_get_defaults('realign.write.interp', val{:}); % --------------------------------------------------------------------- % wrap Wrapping % --------------------------------------------------------------------- wrap = cfg_menu; wrap.tag = 'wrap'; wrap.name = 'Wrapping'; wrap.help = { 'This indicates which directions in the volumes the values should wrap around in. For example, in MRI scans, the images wrap around in the phase encode direction, so (e.g.) the subject''s nose may poke into the back of the subject''s head. These are typically:' ' No wrapping - for PET or images that have already been spatially transformed.' ' Wrap in Y - for (un-resliced) MRI where phase encoding is in the Y direction (voxel space).' }'; wrap.labels = { 'No wrap' 'Wrap X' 'Wrap Y' 'Wrap X & Y' 'Wrap Z' 'Wrap X & Z' 'Wrap Y & Z' 'Wrap X, Y & Z' }'; wrap.values = {[0 0 0] [1 0 0] [0 1 0] [1 1 0] [0 0 1] [1 0 1] [0 1 1]... [1 1 1]}; wrap.def = @(val)spm_get_defaults('realign.write.wrap', val{:}); % --------------------------------------------------------------------- % mask Masking % --------------------------------------------------------------------- mask = cfg_menu; mask.tag = 'mask'; mask.name = 'Masking'; mask.help = {'Because of subject motion, different images are likely to have different patterns of zeros from where it was not possible to sample data. With masking enabled, the program searches through the whole time series looking for voxels which need to be sampled from outside the original images. Where this occurs, that voxel is set to zero for the whole set of images (unless the image format can represent NaN, in which case NaNs are used where possible).'}; mask.labels = { 'Mask images' 'Dont mask images' }'; mask.values = {1 0}; mask.def = @(val)spm_get_defaults('realign.write.mask', val{:}); % --------------------------------------------------------------------- % prefix Filename Prefix % --------------------------------------------------------------------- prefix = cfg_entry; prefix.tag = 'prefix'; prefix.name = 'Filename Prefix'; prefix.help = {'Specify the string to be prepended to the filenames of the resliced image file(s). Default prefix is ''r''.'}; prefix.strtype = 's'; prefix.num = [1 Inf]; prefix.def = @(val)spm_get_defaults('realign.write.prefix', val{:}); % --------------------------------------------------------------------- % roptions Reslice Options % --------------------------------------------------------------------- roptions = cfg_branch; roptions.tag = 'roptions'; roptions.name = 'Reslice Options'; roptions.val = {which interp wrap mask prefix }; roptions.help = {'Various reslicing options. If in doubt, simply keep the default values.'}; % --------------------------------------------------------------------- % write Realign: Reslice % --------------------------------------------------------------------- write = cfg_exbranch; write.tag = 'write'; write.name = 'Realign: Reslice'; write.val = {data roptions }; write.help = {'This function reslices a series of registered images such that they match the first image selected voxel-for-voxel. The resliced images are named the same as the originals, except that they are prefixed by ''r''.'}; write.prog = @spm_run_realign_reslice; write.vout = @vout_reslice; % --------------------------------------------------------------------- % data Session % --------------------------------------------------------------------- data = cfg_files; data.tag = 'data'; data.name = 'Session'; data.help = {'Select scans for this session. In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.'}; data.filter = 'image'; data.ufilter = '.*'; data.num = [1 Inf]; % --------------------------------------------------------------------- % generic Data % --------------------------------------------------------------------- generic = cfg_repeat; generic.tag = 'generic'; generic.name = 'Data'; generic.help = {'Add new sessions for this subject. In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.'}; generic.values = {data }; generic.num = [1 Inf]; % --------------------------------------------------------------------- % estwrite Realign: Estimate & Reslice % --------------------------------------------------------------------- estwrite = cfg_exbranch; estwrite.tag = 'estwrite'; estwrite.name = 'Realign: Estimate & Reslice'; estwrite.val = {generic eoptions roptions }; estwrite.help = { 'This routine realigns a time-series of images acquired from the same subject using a least squares approach and a 6 parameter (rigid body) spatial transformation/* \cite{friston95a}*/. The first image in the list specified by the user is used as a reference to which all subsequent scans are realigned. The reference scan does not have to be the first chronologically and it may be wise to chose a "representative scan" in this role.' '' 'The aim is primarily to remove movement artefact in fMRI and PET time-series (or more generally longitudinal studies) /* \cite{ashburner97bir}*/. The headers are modified for each of the input images, such that. they reflect the relative orientations of the data. 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. After realignment, the images are resliced such that they match the first image selected voxel-for-voxel. The resliced images are named the same as the originals, except that they are prefixed by ''r''.' }'; estwrite.prog = @spm_run_realign_estwrite; estwrite.vout = @vout_estwrite; % --------------------------------------------------------------------- % realign Realign % --------------------------------------------------------------------- realign = cfg_choice; realign.tag = 'realign'; realign.name = 'Realign'; realign.help = {'Within-subject registration of image time series.'}; realign.values = {estimate write estwrite }; %realign.num = [1 Inf]; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function dep = vout_reslice(job) if job.roptions.which(1) > 0 dep(1) = cfg_dep; dep(1).sname = 'Resliced Images'; dep(1).src_output = substruct('.','rfiles'); dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end; if ~strcmp(job.roptions.which,'<UNDEFINED>') && job.roptions.which(2), if exist('dep','var') dep(end+1) = cfg_dep; else dep = cfg_dep; end; dep(end).sname = 'Mean Image'; dep(end).src_output = substruct('.','rmean'); dep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function dep = vout_estimate(job) for k=1:numel(job.data) cdep(1) = cfg_dep; cdep(1).sname = sprintf('Realignment Param File (Sess %d)', k); cdep(1).src_output = substruct('.','sess', '()',{k}, '.','rpfile'); cdep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); cdep(2) = cfg_dep; cdep(2).sname = sprintf('Realigned Images (Sess %d)', k); cdep(2).src_output = substruct('.','sess', '()',{k}, '.','cfiles'); cdep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); if k == 1 dep = cdep; else dep = [dep cdep]; end; end; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function dep = vout_estwrite(job) for k=1:numel(job.data) cdep(1) = cfg_dep; cdep(1).sname = sprintf('Realignment Param File (Sess %d)', k); cdep(1).src_output = substruct('.','sess', '()',{k}, '.','rpfile'); cdep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); cdep(2) = cfg_dep; cdep(2).sname = sprintf('Realigned Images (Sess %d)', k); cdep(2).src_output = substruct('.','sess', '()',{k}, '.','cfiles'); cdep(2).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); if job.roptions.which(1) > 0 cdep(3) = cfg_dep; cdep(3).sname = sprintf('Resliced Images (Sess %d)', k); cdep(3).src_output = substruct('.','sess', '()',{k}, '.','rfiles'); cdep(3).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end; if k == 1 dep = cdep; else dep = [dep cdep]; end; end; if ~strcmp(job.roptions.which,'<UNDEFINED>') && job.roptions.which(2), if exist('dep','var') dep(end+1) = cfg_dep; else dep = cfg_dep; end; dep(end).sname = 'Mean Image'; dep(end).src_output = substruct('.','rmean'); dep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end;
github
philippboehmsturm/antx-master
spm_cfg_smooth.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_smooth.m
4,201
utf_8
09740f4ae4c4a5c7260951bcb875e841
function smooth = spm_cfg_smooth % SPM Configuration file for Smooth %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_smooth.m 3691 2010-01-20 17:08:30Z guillaume $ rev = '$Rev: 3691 $'; % --------------------------------------------------------------------- % data Images to Smooth % --------------------------------------------------------------------- data = cfg_files; data.tag = 'data'; data.name = 'Images to Smooth'; data.help = {'Specify the images to smooth. The smoothed images are written to the same subdirectories as the original *.img and are prefixed with a ''s'' (i.e. s*.img). The prefix can be changed by an option setting.'}; data.filter = 'image'; data.ufilter = '.*'; data.num = [0 Inf]; % --------------------------------------------------------------------- % fwhm FWHM % --------------------------------------------------------------------- fwhm = cfg_entry; fwhm.tag = 'fwhm'; fwhm.name = 'FWHM'; fwhm.help = {'Specify the full-width at half maximum (FWHM) of the Gaussian smoothing kernel in mm. Three values should be entered, denoting the FWHM in the x, y and z directions.'}; fwhm.strtype = 'e'; fwhm.num = [1 3]; fwhm.def = @(val)spm_get_defaults('smooth.fwhm', val{:}); % --------------------------------------------------------------------- % dtype Data Type % --------------------------------------------------------------------- dtype = cfg_menu; dtype.tag = 'dtype'; dtype.name = 'Data Type'; dtype.help = {'Data-type of output images. SAME indicates the same datatype as the original images.'}; dtype.labels = { 'SAME' 'UINT8 - unsigned char' 'INT16 - signed short' 'INT32 - signed int' 'FLOAT32 - single prec. float' 'FLOAT64 - double prec. float' }'; dtype.values = {0 spm_type('uint8') spm_type('int16') spm_type('int32') spm_type('float32') spm_type('float64')}; dtype.val = {0}; % --------------------------------------------------------------------- % im Implicit masking % --------------------------------------------------------------------- im = cfg_menu; im.tag = 'im'; im.name = 'Implicit masking'; im.help = {'An "implicit mask" is a mask implied by a particular voxel value (0 for images with integer type, NaN for float images).' 'If set to ''Yes'', the implicit masking of the input image is preserved in the smoothed image.'}; im.labels = {'Yes' 'No'}; im.values = {1 0}; im.val = {0}; % --------------------------------------------------------------------- % prefix Filename Prefix % --------------------------------------------------------------------- prefix = cfg_entry; prefix.tag = 'prefix'; prefix.name = 'Filename Prefix'; prefix.help = {'Specify the string to be prepended to the filenames of the smoothed image file(s). Default prefix is ''s''.'}; prefix.strtype = 's'; prefix.num = [1 Inf]; prefix.def = @(val)spm_get_defaults('smooth.prefix', val{:}); % --------------------------------------------------------------------- % smooth Smooth % --------------------------------------------------------------------- smooth = cfg_exbranch; smooth.tag = 'smooth'; smooth.name = 'Smooth'; smooth.val = {data fwhm dtype im prefix}; smooth.help = {'This is for smoothing (or convolving) image volumes with a Gaussian kernel of a specified width. It is used as a preprocessing step to suppress noise and effects due to residual differences in functional and gyral anatomy during inter-subject averaging.'}; smooth.prog = @spm_run_smooth; smooth.vout = @vout; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function dep = vout(varargin) % Output file names will be saved in a struct with field .files dep(1) = cfg_dep; dep(1).sname = 'Smoothed Images'; dep(1).src_output = substruct('.','files'); dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_eeg_epochs.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_epochs.m
3,555
utf_8
b602c570d73c2f10fa1a3f0efe68015e
function S = spm_cfg_eeg_epochs % configuration file for M/EEG epoching %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: spm_cfg_eeg_epochs.m 3881 2010-05-07 21:02:57Z vladimir $ rev = '$Rev: 3881 $'; D = cfg_files; D.tag = 'D'; D.name = 'File Name'; D.filter = 'mat'; D.num = [1 1]; D.help = {'Select the EEG mat file.'}; % input via trl file trlfile = cfg_files; trlfile.tag = 'trlfile'; trlfile.name = 'File Name'; trlfile.filter = 'mat'; trlfile.num = [1 1]; trlfile.help = {'Select the trialfile mat file.'}; padding = cfg_entry; padding.tag = 'padding'; padding.name = 'Padding'; padding.strtype = 'r'; padding.num = [1 1]; padding.help = {'Enter padding [s]: the additional time period around each trial',... 'for which the events are saved with the trial (to let the',... 'user keep and use for analysis events which are outside'}; epochinfo = cfg_branch; epochinfo.tag = 'epochinfo'; epochinfo.name = 'Epoch information'; epochinfo.val = {trlfile padding}; % input via trialdef timewindow = cfg_entry; timewindow.tag = 'timewindow'; timewindow.name = 'Timing'; timewindow.strtype = 'r'; timewindow.num = [1 2]; timewindow.help = {'start and end of epoch [ms]'}; conditionlabel = cfg_entry; conditionlabel.tag = 'conditionlabel'; conditionlabel.name = 'Condition label'; conditionlabel.strtype = 's'; eventtype = cfg_entry; eventtype.tag = 'eventtype'; eventtype.name = 'Event type'; eventtype.strtype = 's'; eventvalue = cfg_entry; eventvalue.tag = 'eventvalue'; eventvalue.name = 'Event value'; eventvalue.strtype = 'e'; trialdef = cfg_branch; trialdef.tag = 'trialdef'; trialdef.name = 'Trial'; trialdef.val = {conditionlabel, eventtype, eventvalue}; define1 = cfg_repeat; define1.tag = 'unused'; define1.name = 'Trial definitions'; define1.values = {trialdef}; define = cfg_branch; define.tag = 'define'; define.name = 'Define trial'; define.val = {timewindow define1}; trlchoice = cfg_choice; trlchoice.tag = 'trialchoice'; trlchoice.name = 'Choose a way how to define trials'; trlchoice.help = {'Choose one of the two options how to define trials'}'; trlchoice.values = {epochinfo define}; S = cfg_exbranch; S.tag = 'epoch'; S.name = 'M/EEG Epoching'; S.val = {D trlchoice}; S.help = {'Epoch continuous EEG/MEG data.'}; S.prog = @eeg_epochs; S.vout = @vout_eeg_epochs; S.modality = {'EEG'}; function out = eeg_epochs(job) % construct the S struct S.D = job.D{1}; if isfield(job.trialchoice, 'define') S.pretrig = job.trialchoice.define.timewindow(1); S.posttrig = job.trialchoice.define.timewindow(2); S.trialdef = job.trialchoice.define.trialdef; else S.epochinfo = job.trialchoice.epochinfo; S.epochinfo.trlfile = S.epochinfo.trlfile{1}; end % set review and save options both to 0 to not pop up something S.reviewtrials = 0; S.save = 0; out.D = spm_eeg_epochs(S); out.Dfname = {fullfile(out.D.path, out.D.fname)}; function dep = vout_eeg_epochs(job) % Output is always in field "D", no matter how job is structured dep = cfg_dep; dep.sname = 'Epoched Data'; % reference field "D" from output dep.src_output = substruct('.','D'); % this can be entered into any evaluated input dep.tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Epoched Datafile'; % reference field "Dfname" from output dep(2).src_output = substruct('.','Dfname'); % this can be entered into any file selector dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_cfg_imcalc.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_imcalc.m
8,938
utf_8
27ef890fb5b522b50c01dd5e37434086
function imcalc = spm_cfg_imcalc % SPM Configuration file for ImCalc %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_imcalc.m 4385 2011-07-08 16:53:38Z guillaume $ % --------------------------------------------------------------------- % input Input Images % --------------------------------------------------------------------- input = cfg_files; input.tag = 'input'; input.name = 'Input Images'; input.help = {'These are the images that are used by the calculator. They are referred to as i1, i2, i3, etc in the order that they are specified.'}; input.filter = 'image'; input.ufilter = '.*'; input.num = [1 Inf]; % --------------------------------------------------------------------- % output Output Filename % --------------------------------------------------------------------- output = cfg_entry; output.tag = 'output'; output.name = 'Output Filename'; output.help = {'The output image is written to current working directory unless a valid full pathname is given. If a path name is given here, the output directory setting will be ignored.'}; output.strtype = 's'; output.num = [1 Inf]; output.val = {'output.img'}; % --------------------------------------------------------------------- % outdir Output Directory % --------------------------------------------------------------------- outdir = cfg_files; outdir.tag = 'outdir'; outdir.name = 'Output Directory'; outdir.val{1} = {''}; outdir.help = {'Files produced by this function will be written into this output directory. If no directory is given, images will be written to current working directory. If both output filename and output directory contain a directory, then output filename takes precedence.'}; outdir.filter = 'dir'; outdir.ufilter = '.*'; outdir.num = [0 1]; % --------------------------------------------------------------------- % expression Expression % --------------------------------------------------------------------- expression = cfg_entry; expression.tag = 'expression'; expression.name = 'Expression'; expression.help = { 'Example expressions (f):' ' * Mean of six images (select six images)' ' f = ''(i1+i2+i3+i4+i5+i6)/6''' ' * Make a binary mask image at threshold of 100' ' f = ''i1>100''' ' * Make a mask from one image and apply to another' ' f = ''i2.*(i1>100)''' ' - here the first image is used to make the mask, which is applied to the second image' ' * Sum of n images' ' f = ''i1 + i2 + i3 + i4 + i5 + ...''' ' * Sum of n images (when reading data into a data-matrix - use dmtx arg)' ' f = ''sum(X)''' }'; expression.strtype = 's'; expression.num = [2 Inf]; % --------------------------------------------------------------------- % dmtx Data Matrix % --------------------------------------------------------------------- dmtx = cfg_menu; dmtx.tag = 'dmtx'; dmtx.name = 'Data Matrix'; dmtx.help = {'If the dmtx flag is set, then images are read into a data matrix X (rather than into separate variables i1, i2, i3,...). The data matrix should be referred to as X, and contains images in rows. Computation is plane by plane, so in data-matrix mode, X is a NxK matrix, where N is the number of input images [prod(size(Vi))], and K is the number of voxels per plane [prod(Vi(1).dim(1:2))].'}; dmtx.labels = { 'No - don''t read images into data matrix' 'Yes - read images into data matrix' }'; dmtx.values = {0 1}; dmtx.val = {0}; % --------------------------------------------------------------------- % mask Masking % --------------------------------------------------------------------- mask = cfg_menu; mask.tag = 'mask'; mask.name = 'Masking'; mask.help = {'For data types without a representation of NaN, implicit zero masking assumes that all zero voxels are to be treated as missing, and treats them as NaN. NaN''s are written as zero (by spm_write_plane), for data types without a representation of NaN.'}; mask.labels = { 'No implicit zero mask' 'Implicit zero mask' 'NaNs should be zeroed' }'; mask.values = {0 1 -1}; mask.val = {0}; % --------------------------------------------------------------------- % interp Interpolation % --------------------------------------------------------------------- interp = cfg_menu; interp.tag = 'interp'; interp.name = 'Interpolation'; interp.help = { 'With images of different sizes and orientations, the size and orientation of the first is used for the output image. A warning is given in this situation. Images are sampled into this orientation using the interpolation specified by the hold parameter.' '' 'The method by which the images are sampled when being written in a different space.' ' Nearest Neighbour' ' - Fastest, but not normally recommended.' ' Bilinear Interpolation' ' - OK for PET, or realigned fMRI.' ' Sinc Interpolation' ' - Better quality (but slower) interpolation, especially' ' with higher degrees.' }'; interp.labels = { 'Nearest neighbour' 'Trilinear' '2nd Degree Sinc' '3rd Degree Sinc' '4th Degree Sinc' '5th Degree Sinc' '6th Degree Sinc' '7th Degree Sinc' }'; interp.values = {0 1 -2 -3 -4 -5 -6 -7}; interp.val = {1}; % --------------------------------------------------------------------- % dtype Data Type % --------------------------------------------------------------------- dtype = cfg_menu; dtype.tag = 'dtype'; dtype.name = 'Data Type'; dtype.help = {'Data-type of output image'}; dtype.labels = { 'UINT8 - unsigned char' 'INT16 - signed short' 'INT32 - signed int' 'FLOAT32 - single prec. float' 'FLOAT64 - double prec. float' }'; dtype.values = {spm_type('uint8') spm_type('int16') spm_type('int32') ... spm_type('float32') spm_type('float64')}; dtype.val = {spm_type('int16')}; % --------------------------------------------------------------------- % options Options % --------------------------------------------------------------------- options = cfg_branch; options.tag = 'options'; options.name = 'Options'; options.val = {dmtx mask interp dtype }; options.help = {'Options for image calculator'}; % --------------------------------------------------------------------- % imcalc Image Calculator % --------------------------------------------------------------------- imcalc = cfg_exbranch; imcalc.tag = 'imcalc'; imcalc.name = 'Image Calculator'; imcalc.val = {input output outdir expression options }; imcalc.help = {'The image calculator is for performing user-specified algebraic manipulations on a set of images, with the result being written out as an image. The user is prompted to supply images to work on, a filename for the output image, and the expression to evaluate. The expression should be a standard MATLAB expression, within which the images should be referred to as i1, i2, i3,... etc.'}; imcalc.prog = @my_spm_imcalc_ui; imcalc.vout = @vout; % ===================================================================== function out = my_spm_imcalc_ui(job) %-Decompose job structure and run spm_imcalc_ui with arguments %---------------------------------------------------------------------- flags = {job.options.dmtx, job.options.mask, job.options.dtype, job.options.interp}; [p,nam,ext,num] = spm_fileparts(job.output); if isempty(p) if isempty(job.outdir{1}) p = pwd; else p = job.outdir{1}; end end if isempty(ext) ext = ['.' spm_get_defaults('images.format')]; end if isempty(num) num = ',1'; end out.files{1} = fullfile(p,[nam ext num]); spm_imcalc_ui(strvcat(job.input{:}),out.files{1},job.expression,flags); % ===================================================================== function dep = vout(job) dep = cfg_dep; if ~ischar(job.output) || strcmp(job.output, '<UNDEFINED>') dep.sname = 'Imcalc Computed Image'; else dep.sname = sprintf('Imcalc Computed Image: %s', job.output); end dep.src_output = substruct('.','files'); dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_eeg_montage.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_montage.m
1,898
utf_8
634d67c28180cedd128491a4bb51ecc8
function S = spm_cfg_eeg_montage % configuration file for reading montage files %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: spm_cfg_eeg_montage.m 4212 2011-02-23 17:50:55Z vladimir $ D = cfg_files; D.tag = 'D'; D.name = 'File Name'; D.filter = 'mat'; D.num = [1 1]; D.help = {'Select the EEG mat file.'}; montage = cfg_files; montage.tag = 'montage'; montage.name = 'Montage file name'; montage.filter = 'mat'; montage.num = [1 1]; montage.help = {'Select a montage file.'}; keepothers = cfg_menu; keepothers.tag = 'keepothers'; keepothers.name = 'Keep other channels'; keepothers.labels = {'Yes', 'No'}; keepothers.values = {'yes', 'no'}; keepothers.val = {'no'}; keepothers.help = {'Specify whether you want to keep channels that are not contributing to the new channels'}; S = cfg_exbranch; S.tag = 'montage'; S.name = 'M/EEG Montage'; S.val = {D montage keepothers}; S.help = {'Apply a montage (linear transformation) to EEG/MEG data.'}; S.prog = @eeg_montage; S.vout = @vout_eeg_montage; S.modality = {'EEG'}; function out = eeg_montage(job) % construct the S struct S.D = job.D{1}; S.montage = job.montage{1}; S.keepothers = job.keepothers; out.D = spm_eeg_montage(S); out.Dfname = {fullfile(out.D.path, out.D.fname)}; function dep = vout_eeg_montage(job) % Output is always in field "D", no matter how job is structured dep = cfg_dep; dep.sname = 'montaged data'; % reference field "D" from output dep.src_output = substruct('.','D'); % this can be entered into any evaluated input dep.tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Montaged Datafile'; % reference field "Dfname" from output dep(2).src_output = substruct('.','Dfname'); % this can be entered into any file selector dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_run_regions.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_run_regions.m
8,611
utf_8
9c364ea7e6db98ff80f6e8cd0861f7d3
function varargout = spm_run_regions(cmd, varargin) % Batch callback to extract data from a ROI - This is Freiburg specific!! % varargout = spm_run_regions(cmd, varargin) % where cmd is one of % 'run' - out = spm_run_regions('run', job) % Run extract job. Extracted data are both saved into VOI .mat % file in the SPM.mat directory and returned as output % arguments. % out is a 1-by-#VOI struct array with fields % .fname - cell string containing file name of VOI .mat file % .Y - eigenvariate of filtered data for VOI % .xY - VOI description as returned from spm_regions % 'vout' - dep = spm_run_regions('vout', job) % Create virtual output descriptions for each VOI. % % This code is part of a batch job configuration system for MATLAB. See % help matlabbatch % for a general overview. %_______________________________________________________________________ % Copyright (C) 2007 Freiburg Brain Imaging % Volkmar Glauche % $Id: spm_run_regions.m 662 2011-09-13 08:01:25Z vglauche $ rev = '$Rev: 662 $'; %#ok cfg_message('spm-freiburg:deprecated', 'This function is deprecated and will be removed from future releases of SPM(Freiburg). Please use "Batch->Util->Volume of Interest" instead.'); if ischar(cmd) switch lower(cmd) case 'run' opwd = pwd; job = local_getjob(varargin{1}); % get SPM and contrast-based mask if isfield(job.srcspm.smask,'conspec') % code taken from spm_run_results.m xSPM.swd = spm_str_manip(job.srcspm.spmmat{1},'H'); xSPM.Ic = job.srcspm.smask.conspec.contrasts; xSPM.u = job.srcspm.smask.conspec.thresh; xSPM.Im = []; if ~isempty(job.srcspm.smask.conspec.mask) xSPM.Im = job.srcspm.smask.conspec.mask.contrasts; xSPM.pm = job.srcspm.smask.conspec.mask.thresh; xSPM.Ex = job.srcspm.smask.conspec.mask.mtype; end xSPM.thresDesc = job.srcspm.smask.conspec.threshdesc; xSPM.title = ''; xSPM.k = job.srcspm.smask.conspec.extent; [SPM xSPM] = spm_getSPM(xSPM); else % get all inmask voxels tmp = load(job.srcspm.spmmat{1}); SPM = tmp.SPM; cd(SPM.swd); [msk, XYZmm] = spm_read_vols(SPM.VM); xSPM.XYZmm = XYZmm(:,msk(:)~=0); XYZ = SPM.VM.mat\[xSPM.XYZmm;ones(1,size(xSPM.XYZmm,2))]; xSPM.XYZ = XYZ(1:3,:); xSPM.M = SPM.VM.mat; end nVOI = numel(job.xY); out = repmat(struct('fname',{{}},'Y',[],'xY',struct([])),1,nVOI); for cVOI = 1:nVOI xY = rmfield(job.xY(cVOI),'voi'); % go to nearest coordinate xyzvx = round(SPM.VM.mat\[xY.xyz; 1]); xyzvx(xyzvx<1) = 1; xyzvx = min(xyzvx,[SPM.VM.dim(1:3)';1]); xyz = SPM.VM.mat*xyzvx; xY.xyz=xyz(1:3); % decompose cfg_choice for VOI type xY.def = char(fieldnames(job.xY(cVOI).voi)); xY.spec = job.xY(cVOI).voi.(xY.def); [out(cVOI).Y, out(cVOI).xY] = spm_regions(xSPM, SPM, [], xY); % code taken from spm_regions.m out(cVOI).fname = {fullfile(SPM.swd, sprintf('VOI_%s_%i.mat',out(cVOI).xY.name,out(cVOI).xY.Sess))}; end cd(opwd); if nargout > 0 varargout{1} = out; end case 'vout' job = local_getjob(varargin{1}); % initialise cfg_dep array nVOI = numel(job.xY); dep = repmat(cfg_dep,1,3*nVOI); % determine outputs, return cfg_dep array in variable dep for cVOI = 1:nVOI if ischar(job.xY(cVOI).name) && ~strcmp(job.xY(cVOI).name, '<UNDEFINED>') VOIname = sprintf('VOI(%d): ''%s''', cVOI, job.xY(cVOI).name); else VOIname = sprintf('VOI(%d)', cVOI); end dep(3*(cVOI-1)+1).sname = sprintf('%s - VOI file', VOIname); dep(3*(cVOI-1)+1).src_output = substruct('()',{cVOI},'.','fname'); dep(3*(cVOI-1)+1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); dep(3*(cVOI-1)+2).sname = sprintf('%s - Eigenvariate', VOIname); dep(3*(cVOI-1)+2).src_output = substruct('()',{cVOI},'.','Y'); dep(3*(cVOI-1)+2).tgt_spec = cfg_findspec({{'strtype','r'}}); dep(3*(cVOI-1)+3).sname = sprintf('%s - VOI struct', VOIname); dep(3*(cVOI-1)+3).src_output = substruct('()',{cVOI},'.','xY'); dep(3*(cVOI-1)+3).tgt_spec = cfg_findspec({{'strtype','e'}}); end varargout{1} = dep; case 'check' if ischar(varargin{1}) subcmd = lower(varargin{1}); subjob = varargin{2}; str = ''; switch subcmd % implement checks, return status string in variable str case 'contrasts' if ~all(isfinite(subjob)) str = 'Contrast number must be a finite number.'; end case 'srcspm' % check whether specified contrasts exist in SPM.mat if isfield(subjob.smask, 'conspec') tmp = load(subjob.spmmat{1}); if ~isempty(subjob.smask.conspec.mask) mxc = max([subjob.smask.conspec.contrasts subjob.smask.conspec.mask.contrasts]); else mxc = max(subjob.smask.conspec.contrasts); end if mxc > numel(tmp.SPM.xCon) str = sprintf('Contrast numbers must be in the range [1 %d]', numel(tmp.SPM.xCon)); end end case 'regions' % check whether Ic refers to an F contrast Ics = [subjob.xY.Ic]; Ics = Ics(Ics>0); % find non-zero Ic's if ~isempty(Ics) tmp = load(subjob.srcspm.spmmat{1}); if max(Ics) > numel(tmp.SPM.xCon) str = sprintf('Contrast numbers must be in the range [1 %d]', numel(tmp.SPM.xCon)); elseif ~all(strcmp({tmp.SPM.xCon(Ics).STAT},'F')) str = 'Contrasts for adjustment must be F contrasts.'; end end otherwise cfg_message('unknown:check', ... 'Unknown check subcmd ''%s''.', subcmd); end varargout{1} = str; else cfg_message('ischar:check', 'Subcmd must be a string.'); end case 'defaults' if nargin == 2 varargout{1} = local_defs(varargin{1}); else local_defs(varargin{1:2}); end otherwise cfg_message('unknown:cmd', 'Unknown command ''%s''.', cmd); end else cfg_message('ischar:cmd', 'Cmd must be a string.'); end function varargout = local_defs(defstr, defval) persistent defs; if isempty(defs) % initialise defaults end if ischar(defstr) % construct subscript reference struct from dot delimited tag string tags = textscan(defstr,'%s', 'delimiter','.'); subs = struct('type','.','subs',tags{1}'); try cdefval = subsref(local_def, subs); catch cdefval = []; cfg_message('defaults:noval', ... 'No matching defaults value ''%s'' found.', defstr); end if nargin == 1 varargout{1} = cdefval; else defs = subsasgn(defs, subs, defval); end else cfg_message('ischar:defstr', 'Defaults key must be a string.'); end function job = local_getjob(job) if ~isstruct(job) cfg_message('isstruct:job', 'Job must be a struct.'); end
github
philippboehmsturm/antx-master
spm_run_fmri_data.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_run_fmri_data.m
2,029
utf_8
1c5c4ccd6eaa0935710083844d6d4453
function out = spm_run_fmri_data(job) % Set up the design matrix and run a design. % SPM job execution function % takes a harvested job data structure and call SPM functions to perform % computations on the data. % Input: % job - harvested job data structure (see matlabbatch help) % Output: % out - computation results, usually a struct variable. %_________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_run_fmri_data.m 4185 2011-02-01 18:46:18Z guillaume $ spm('defaults','FMRI'); original_dir = pwd; [p n e v] = spm_fileparts(job.spmmat{1}); my_cd(p); load(job.spmmat{1}); % Image filenames %------------------------------------------------------------------------- SPM.xY.P = strvcat(job.scans); % Let SPM configure the design %------------------------------------------------------------------------- SPM = spm_fmri_spm_ui(SPM); if ~isempty(job.mask)&&~isempty(job.mask{1}) SPM.xM.VM = spm_vol(job.mask{:}); SPM.xM.xs.Masking = [SPM.xM.xs.Masking, '+explicit mask']; end %-Save SPM.mat %------------------------------------------------------------------------- fprintf('%-40s: ','Saving SPM configuration') %-# if spm_check_version('matlab','7') >= 0 save('SPM.mat','-V6','SPM'); else save('SPM.mat','SPM'); end fprintf('%30s\n','...SPM.mat saved') %-# out.spmmat{1} = fullfile(pwd, 'SPM.mat'); my_cd(original_dir); % Change back dir fprintf('Done\n') return %------------------------------------------------------------------------- %------------------------------------------------------------------------- function my_cd(varargin) % jobDir must be the actual directory to change to, NOT the job structure. jobDir = varargin{1}; if ~isempty(jobDir) try cd(char(jobDir)); fprintf('Changing directory to: %s\n',char(jobDir)); catch error('Failed to change directory. Aborting run.') end end return;
github
philippboehmsturm/antx-master
spm_cfg_cdir.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_cdir.m
1,931
utf_8
b1ea39d134d41d865c66dcc2fe876c30
function cdir = spm_cfg_cdir % SPM Configuration file % automatically generated by the MATLABBATCH utility function GENCODE %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_cdir.m 1295 2008-04-02 14:31:24Z volkmar $ rev = '$Rev: 1295 $'; % --------------------------------------------------------------------- % directory Select a directory % --------------------------------------------------------------------- directory = cfg_files; directory.tag = 'directory'; directory.name = 'Select a directory'; directory.help = {'Select a directory to change to.'}; directory.filter = 'dir'; directory.ufilter = '.*'; directory.num = [1 1]; % --------------------------------------------------------------------- % cdir Change Directory (Deprecated) % --------------------------------------------------------------------- cdir = cfg_exbranch; cdir.tag = 'cdir'; cdir.name = 'Change Directory (Deprecated)'; cdir.val = {directory }; cdir.help = { 'This module is deprecated and has been moved to BasicIO.' 'Jobs which are ready to run may continue using it, but the module inputs can not be changed via GUI. Please switch to the BasicIO module instead.' 'This facilty allows programming a directory change. Directories are selected in the right listbox.' }'; cdir.prog = @my_job_cd; cdir.hidden = true; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function my_job_cd(varargin) % job can be a job structure or the directory to change to. job = varargin{1}; if isstruct(job) jobDir = job.directory; else jobDir = job; end if ~isempty(jobDir), cd(char(jobDir)); fprintf('New working directory: %s\n', char(jobDir)); end; return;
github
philippboehmsturm/antx-master
spm_run_preproc.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_run_preproc.m
2,209
utf_8
6527bf563f7e57ac5f3cc404fa7e12ce
function out = spm_run_preproc(job) % SPM job execution function % takes a harvested job data structure and call SPM functions to perform % computations on the data. % Input: % job - harvested job data structure (see matlabbatch help) % Output: % out - computation results, usually a struct variable. %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_run_preproc.m 4185 2011-02-01 18:46:18Z guillaume $ job.opts.tpm = char(job.opts.tpm); if isfield(job.opts,'msk'), job.opts.msk = char(job.opts.msk); end; for i=1:numel(job.data), res = spm_preproc(job.data{i},job.opts); [out(1).sn{i},out(1).isn{i}] = spm_prep2sn(res); [pth,nam] = spm_fileparts(job.data{i}); out(1).snfile{i} = fullfile(pth,[nam '_seg_sn.mat']); savefields(out(1).snfile{i},out(1).sn{i}); out(1).isnfile{i} = fullfile(pth,[nam '_seg_inv_sn.mat']); savefields(out(1).isnfile{i},out(1).isn{i}); end; spm_preproc_write(cat(2,out.sn{:}),job.output); % Guess filenames opts = job.output; sopts = [opts.GM;opts.WM;opts.CSF]; for i=1:numel(job.data) [pth,nam,ext,num] = spm_fileparts(job.data{i}); if opts.biascor, out(1).biascorr{i,1} = ... fullfile(pth, sprintf('m%s%s', nam, ext)); end; for k1=1:3, if sopts(k1,3), out(1).(sprintf('c%d',k1)){i,1} = ... fullfile(pth, sprintf('c%d%s%s', k1, nam, ext)); end; if sopts(k1,2), out(1).(sprintf('wc%d',k1)){i,1} = ... fullfile(pth, sprintf('wc%d%s%s', k1, nam, ext)); end; if sopts(k1,1), out(1).(sprintf('mwc%d',k1)){i,1} = ... fullfile(pth, sprintf('mwc%d%s%s', k1, nam, ext)); end; end; end; return; %========================================================================== function savefields(fnam,p) if length(p)>1, error('Can''t save fields.'); end fn = fieldnames(p); if numel(fn)==0, return; end for i=1:length(fn) eval([fn{i} '= p.' fn{i} ';']); end if spm_check_version('matlab','7') >= 0 save(fnam,'-V6',fn{:}); else save(fnam,fn{:}); end return;
github
philippboehmsturm/antx-master
spm_cfg_eeg_filter.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_filter.m
2,437
utf_8
a82fcc280506266a693b6e8d2b0ff67f
function S = spm_cfg_eeg_filter % configuration file for EEG Filtering %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: spm_cfg_eeg_filter.m 4212 2011-02-23 17:50:55Z vladimir $ rev = '$Rev: 4212 $'; D = cfg_files; D.tag = 'D'; D.name = 'File Name'; D.filter = 'mat'; D.num = [1 1]; D.help = {'Select the EEG mat file.'}; typ = cfg_menu; typ.tag = 'type'; typ.name = 'Filter type'; typ.labels = {'Butterworth', 'FIR'}; typ.values = {'butterworth', 'fir'}; typ.val = {'butterworth'}; typ.help = {'Select the filter type.'}; band = cfg_menu; band.tag = 'band'; band.name = 'Filter band'; band.labels = {'Lowpass', 'Highpass', 'Bandpass', 'Stopband'}; band.values = {'low' 'high' 'bandpass' 'stop'}; band.val = {'low'}; band.help = {'Select the filter band.'}; PHz = cfg_entry; PHz.tag = 'PHz'; PHz.name = 'Cutoff'; PHz.strtype = 'r'; PHz.num = [1 inf]; PHz.help = {'Enter the filter cutoff'}; dir = cfg_menu; dir.tag = 'dir'; dir.name = 'Filter direction'; dir.labels = {'Zero phase', 'Forward', 'Backward'}; dir.values = {'twopass', 'onepass', 'onepass-reverse'}; dir.val = {'twopass'}; dir.help = {'Select the filter direction.'}; order = cfg_entry; order.tag = 'order'; order.name = 'Filter order'; order.val = {5}; order.strtype = 'n'; order.num = [1 1]; order.help = {'Enter the filter order'}; flt = cfg_branch; flt.tag = 'filter'; flt.name = 'Filter'; flt.val = {typ band PHz dir order}; S = cfg_exbranch; S.tag = 'filter'; S.name = 'M/EEG Filter'; S.val = {D flt}; S.help = {'Low-pass filters EEG/MEG epoched data.'}; S.prog = @eeg_filter; S.vout = @vout_eeg_filter; S.modality = {'EEG'}; function out = eeg_filter(job) % construct the S struct S.D = job.D{1}; S.filter = job.filter; out.D = spm_eeg_filter(S); out.Dfname = {fullfile(out.D.path, out.D.fname)}; function dep = vout_eeg_filter(job) % Output is always in field "D", no matter how job is structured dep = cfg_dep; dep.sname = 'Filtered Data'; % reference field "D" from output dep.src_output = substruct('.','D'); % this can be entered into any evaluated input dep.tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Filtered Datafile'; % reference field "Dfname" from output dep(2).src_output = substruct('.','Dfname'); % this can be entered into any file selector dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_cfg_eeg_bc.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_bc.m
2,077
utf_8
cd9810ba021ab48f80a52d739c741c00
function S = spm_cfg_eeg_bc % configuration file for baseline correction %__________________________________________________________________________ % Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging % Vladimir Litvak % $Id: spm_cfg_eeg_bc.m 3818 2010-04-13 14:36:31Z vladimir $ %-------------------------------------------------------------------------- % D %-------------------------------------------------------------------------- D = cfg_files; D.tag = 'D'; D.name = 'File Name'; D.filter = 'mat'; D.num = [1 1]; D.help = {'Select the M/EEG mat file.'}; %-------------------------------------------------------------------------- % time %-------------------------------------------------------------------------- time = cfg_entry; time.tag = 'time'; time.name = 'Baseline'; time.help = {'Start and stop of baseline [ms].'}; time.strtype = 'e'; time.num = [1 2]; %-------------------------------------------------------------------------- % S %-------------------------------------------------------------------------- S = cfg_exbranch; S.tag = 'bc'; S.name = 'M/EEG Baseline correction'; S.val = {D, time}; S.help = {'Baseline correction of M/EEG time data'}'; S.prog = @eeg_bc; S.vout = @vout_eeg_bc; S.modality = {'EEG'}; %========================================================================== function out = eeg_bc(job) % construct the S struct S.D = job.D{1}; S.time = job.time; out.D = spm_eeg_bc(S); out.Dfname = {fullfile(out.D.path,out.D.fname)}; %========================================================================== function dep = vout_eeg_bc(job) % return dependencies dep(1) = cfg_dep; dep(1).sname = 'Baseline corrected M/EEG data'; dep(1).src_output = substruct('.','D'); dep(1).tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Baseline corrected M/EEG datafile'; dep(2).src_output = substruct('.','Dfname'); dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_cfg_eeg_review.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_review.m
780
utf_8
53451e3a49cf80ec8eabbec3f903689a
function S = spm_cfg_eeg_review % configuration file for M/EEG reviewing tool %__________________________________________________________________________ % Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging % Vladimir Litvak % $Id: spm_cfg_eeg_review.m 3881 2010-05-07 21:02:57Z vladimir $ rev = '$Rev: 3881 $'; D = cfg_files; D.tag = 'D'; D.name = 'File Name'; D.filter = 'mat'; D.num = [1 1]; D.help = {'Select the EEG mat file.'}; S = cfg_exbranch; S.tag = 'review'; S.name = 'M/EEG Display'; S.val = {D}; S.help = {'Run the reviewing tool with the given dataset as input.'}; S.prog = @eeg_review; S.modality = {'EEG'}; %========================================================================== function eeg_review(job) spm_eeg_review(spm_eeg_load(job.D{1}));
github
philippboehmsturm/antx-master
spm_cfg_eeg_tf.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_tf.m
3,334
utf_8
d3bf9980666e47b4f76cce8420c31fb6
function S = spm_cfg_eeg_tf % configuration file for M/EEG time-frequency analysis %__________________________________________________________________________ % Copyright (C) 2010 Wellcome Trust Centre for Neuroimaging % Vladimir Litvak % $Id: spm_cfg_eeg_tf.m 4257 2011-03-18 15:28:29Z vladimir $ rev = '$Rev: 4257 $'; D = cfg_files; D.tag = 'D'; D.name = 'File Name'; D.filter = 'mat'; D.num = [1 1]; D.help = {'Select the EEG mat file.'}; timewin = cfg_entry; timewin.tag = 'timewin'; timewin.name = 'Time window'; timewin.strtype = 'r'; timewin.num = [1 2]; timewin.val = {[-Inf Inf]}; timewin.help = {'Time window (ms)'}; frequencies = cfg_entry; frequencies.tag = 'frequencies'; frequencies.name = 'Frequencies of interest'; frequencies.strtype = 'r'; frequencies.num = [0 Inf]; frequencies.val = {[]}; frequencies.help = {'Frequencies of interest (as a vector), if empty 1-48 with optimal frequency bins ~1 Hz or above resolution'}; specest_funs = dir(fullfile(spm('dir'), 'spm_eeg_specest_*.m')); specest_funs = {specest_funs(:).name}; phase = cfg_menu; phase.tag = 'phase'; phase.name = 'Save phase'; phase.help = {'Save phase as well as power'}; phase.labels = {'yes', 'no'}; phase.values = {1, 0}; phase.val = {0}; method = cfg_choice; method.tag = 'method'; method.name = 'Spectral estimation '; for i = 1:numel(specest_funs) method.values{i} = feval(spm_str_manip(specest_funs{i}, 'r')); end S = cfg_exbranch; S.tag = 'analysis'; S.name = 'M/EEG Time-Frequency analysis'; S.val = {D, spm_cfg_eeg_channel_selector, frequencies, timewin, method, phase}; S.help = {'Perform time-frequency analysis of epoched M/EEG data.'}; S.prog = @eeg_tf; S.vout = @vout_eeg_tf; S.modality = {'EEG'}; %========================================================================== function out = eeg_tf(job) % construct the S struct S = []; S.D = job.D{1}; S.channels = spm_cfg_eeg_channel_selector(job.channels); S.frequencies = job.frequencies; S.timewin = job.timewin; S.phase = job.phase; S.method = cell2mat(fieldnames(job.method)); S.settings = getfield(job.method, S.method); [Dtf, Dtph] = spm_eeg_tf(S); out.Dtf = Dtf; out.Dtfname = {Dtf.fname}; out.Dtph = Dtph; if ~isempty(Dtph) out.Dtphname = {Dtph.fname}; else out.Dtphname = {''}; end %========================================================================== function dep = vout_eeg_tf(job) % return dependencies dep(1) = cfg_dep; dep(1).sname = 'M/EEG time-frequency power dataset'; dep(1).src_output = substruct('.','Dtf'); % this can be entered into any evaluated input dep(1).tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'M/EEG time-frequency power dataset'; dep(2).src_output = substruct('.','Dtfname'); % this can be entered into any file selector dep(2).tgt_spec = cfg_findspec({{'filter','mat'}}); dep(3) = cfg_dep; dep(3).sname = 'M/EEG time-frequency phase dataset'; dep(3).src_output = substruct('.','Dtph'); % this can be entered into any evaluated input dep(3).tgt_spec = cfg_findspec({{'strtype','e'}}); dep(4) = cfg_dep; dep(4).sname = 'M/EEG time-frequency phase dataset'; dep(4).src_output = substruct('.','Dtphname'); % this can be entered into any file selector dep(4).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_cfg_ecat.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_ecat.m
2,223
utf_8
bf0ab8263e35bd042da8e4331a6ef6ba
function ecat = spm_cfg_ecat % SPM Configuration file for ECAT Import %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_ecat.m 3691 2010-01-20 17:08:30Z guillaume $ rev = '$Rev: 3691 $'; % --------------------------------------------------------------------- % data ECAT files % --------------------------------------------------------------------- data = cfg_files; data.tag = 'data'; data.name = 'ECAT files'; data.help = {'Select the ECAT files to convert.'}; data.filter = 'any'; data.ufilter = '.*v'; data.num = [1 Inf]; % --------------------------------------------------------------------- % ext Output image format % --------------------------------------------------------------------- ext = cfg_menu; ext.tag = 'ext'; ext.name = 'Output image format'; ext.help = {'Output files can be written as .img + .hdr, or the two can be combined into a .nii file.'}; ext.labels = { 'Two file (img+hdr) NIfTI' 'Single file (nii) NIfTI' }'; ext.values = { 'img' 'nii' }'; ext.def = @(val)spm_get_defaults('images.format', val{:}); % --------------------------------------------------------------------- % opts Options % --------------------------------------------------------------------- opts = cfg_branch; opts.tag = 'opts'; opts.name = 'Options'; opts.val = {ext }; opts.help = {'Conversion options'}; % --------------------------------------------------------------------- % ecat ECAT Import % --------------------------------------------------------------------- ecat = cfg_exbranch; ecat.tag = 'ecat'; ecat.name = 'ECAT Import'; ecat.val = {data opts }; ecat.help = {'ECAT 7 Conversion. ECAT 7 is the image data format used by the more recent CTI PET scanners.'}; ecat.prog = @convert_ecat; ecat.modality = {'PET'}; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function convert_ecat(job) for i=1:length(job.data), spm_ecat2nifti(job.data{i},job.opts); end; return;
github
philippboehmsturm/antx-master
spm_cfg_realignunwarp.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_realignunwarp.m
35,630
utf_8
1d4f758948fa9a2af3f66637e97f5b84
function realignunwarp = spm_cfg_realignunwarp % SPM Configuration file % automatically generated by the MATLABBATCH utility function GENCODE %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_realignunwarp.m 4152 2011-01-11 14:13:35Z volkmar $ rev = '$Rev: 4152 $'; % --------------------------------------------------------------------- % scans Images % --------------------------------------------------------------------- scans = cfg_files; scans.tag = 'scans'; scans.name = 'Images'; scans.help = { 'Select scans for this session. ' 'In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.' }'; scans.filter = 'image'; scans.ufilter = '.*'; scans.num = [1 Inf]; % --------------------------------------------------------------------- % pmscan Phase map (vdm* file) % --------------------------------------------------------------------- pmscan = cfg_files; pmscan.tag = 'pmscan'; pmscan.name = 'Phase map (vdm* file)'; pmscan.help = {'Select pre-calculated phase map, or leave empty for no phase correction. The vdm* file is assumed to be already in alignment with the first scan of the first session.'}; pmscan.filter = 'image'; pmscan.ufilter = '^vdm5_.*'; pmscan.num = [0 1]; pmscan.val = {''}; % --------------------------------------------------------------------- % data Session % --------------------------------------------------------------------- data = cfg_branch; data.tag = 'data'; data.name = 'Session'; data.val = {scans pmscan }; data.help = { 'Only add similar session data to a realign+unwarp branch, i.e., choose Data or Data+phase map for all sessions, but don''t use them interchangeably.' '' 'In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.' }'; % --------------------------------------------------------------------- % generic Data % --------------------------------------------------------------------- generic = cfg_repeat; generic.tag = 'generic'; generic.name = 'Data'; generic.help = {'Data sessions to unwarp.'}; generic.values = {data }; generic.num = [1 Inf]; % --------------------------------------------------------------------- % quality Quality % --------------------------------------------------------------------- quality = cfg_entry; quality.tag = 'quality'; quality.name = 'Quality'; quality.help = {'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.'}; quality.strtype = 'r'; quality.num = [1 1]; quality.extras = [0 1]; quality.def = @(val)spm_get_defaults('realign.estimate.quality', val{:}); % --------------------------------------------------------------------- % sep Separation % --------------------------------------------------------------------- sep = cfg_entry; sep.tag = 'sep'; sep.name = 'Separation'; sep.help = {'The separation (in mm) between the points sampled in the reference image. Smaller sampling distances gives more accurate results, but will be slower.'}; sep.strtype = 'e'; sep.num = [1 1]; sep.def = @(val)spm_get_defaults('realign.estimate.sep', val{:}); % --------------------------------------------------------------------- % fwhm Smoothing (FWHM) % --------------------------------------------------------------------- fwhm = cfg_entry; fwhm.tag = 'fwhm'; fwhm.name = 'Smoothing (FWHM)'; fwhm.help = { 'The FWHM of the Gaussian smoothing kernel (mm) applied to the images before estimating the realignment parameters.' '' ' * PET images typically use a 7 mm kernel.' '' ' * MRI images typically use a 5 mm kernel.' }'; fwhm.strtype = 'e'; fwhm.num = [1 1]; fwhm.def = @(val)spm_get_defaults('realign.estimate.fwhm', val{:}); % --------------------------------------------------------------------- % rtm Num Passes % --------------------------------------------------------------------- rtm = cfg_menu; rtm.tag = 'rtm'; rtm.name = 'Num Passes'; rtm.help = { 'Register to first: Images are registered to the first image in the series. Register to mean: A two pass procedure is used in order to register the images to the mean of the images after the first realignment.' '' ' * PET images are typically registered to the mean.' '' ' * MRI images are typically registered to the first image.' }'; rtm.labels = { 'Register to first' 'Register to mean' }'; rtm.values = {0 1}; rtm.def = @(val)spm_get_defaults('unwarp.estimate.rtm', val{:}); % --------------------------------------------------------------------- % einterp Interpolation % --------------------------------------------------------------------- einterp = cfg_menu; einterp.tag = 'einterp'; einterp.name = 'Interpolation'; einterp.help = {'The method by which the images are sampled when estimating the optimum transformation. Higher degree interpolation methods provide the better interpolation, but they are slower because they use more neighbouring voxels /* \cite{thevenaz00a,unser93a,unser93b}*/. '}; einterp.labels = { 'Nearest neighbour' 'Trilinear' '2nd Degree B-spline' '3rd Degree B-Spline' '4th Degree B-Spline' '5th Degree B-Spline' '6th Degree B-Spline' '7th Degree B-Spline' }'; einterp.values = {0 1 2 3 4 5 6 7}; einterp.def = @(val)spm_get_defaults('realign.estimate.interp', val{:}); % --------------------------------------------------------------------- % ewrap Wrapping % --------------------------------------------------------------------- ewrap = cfg_menu; ewrap.tag = 'ewrap'; ewrap.name = 'Wrapping'; ewrap.help = { 'These are typically: ' ['* No wrapping - for images that have already been ' ... 'spatially transformed.'] ['* Wrap in Y - for (un-resliced) MRI where phase ' ... 'encoding is in the Y direction (voxel space).'] }'; ewrap.labels = { 'No wrap' 'Wrap X' 'Wrap Y' 'Wrap X & Y' 'Wrap Z ' 'Wrap X & Z' 'Wrap Y & Z' 'Wrap X, Y & Z' }'; ewrap.values = {[0 0 0] [1 0 0] [0 1 0] [1 1 0] [0 0 1] [1 0 1] [0 1 1]... [1 1 1]}; ewrap.def = @(val)spm_get_defaults('realign.estimate.wrap', val{:}); % --------------------------------------------------------------------- % weight Weighting % --------------------------------------------------------------------- weight = cfg_files; weight.tag = 'weight'; weight.name = 'Weighting'; weight.val = {''}; weight.help = {'The option of providing a weighting image to weight each voxel of the reference image differently when estimating the realignment parameters. The weights are proportional to the inverses of the standard deviations. For example, when there is a lot of extra-brain motion - e.g., during speech, or when there are serious artifacts in a particular region of the images.'}; weight.filter = 'image'; weight.ufilter = '.*'; weight.num = [0 1]; % --------------------------------------------------------------------- % eoptions Estimation Options % --------------------------------------------------------------------- eoptions = cfg_branch; eoptions.tag = 'eoptions'; eoptions.name = 'Estimation Options'; eoptions.val = {quality sep fwhm rtm einterp ewrap weight }; eoptions.help = {'Various registration options that could be modified to improve the results. Whenever possible, the authors of SPM try to choose reasonable settings, but sometimes they can be improved.'}; % --------------------------------------------------------------------- % basfcn Basis Functions % --------------------------------------------------------------------- basfcn = cfg_menu; basfcn.tag = 'basfcn'; basfcn.name = 'Basis Functions'; basfcn.help = {'Number of basis functions to use for each dimension. If the third dimension is left out, the order for that dimension is calculated to yield a roughly equal spatial cut-off in all directions. Default: [12 12 *]'}; basfcn.labels = { '8x8x*' '10x10x*' '12x12x*' '14x14x*' }'; basfcn.values = {[8 8] [10 10] [12 12] [14 14]}; basfcn.def = @(val)spm_get_defaults('unwarp.estimate.basfcn', val{:}); % --------------------------------------------------------------------- % regorder Regularisation % --------------------------------------------------------------------- regorder = cfg_menu; regorder.tag = 'regorder'; regorder.name = 'Regularisation'; regorder.help = { 'Unwarp looks for the solution that maximises the likelihood (minimises the variance) while simultaneously maximising the smoothness of the estimated field (c.f. Lagrange multipliers). This parameter determines how to balance the compromise between these (i.e. the value of the multiplier). Test it on your own data (if you can be bothered) or go with the defaults. ' '' 'Regularisation of derivative fields is based on the regorder''th (spatial) derivative of the field. The choices are 0, 1, 2, or 3. Default: 1' }'; regorder.labels = { '0' '1' '2' '3' }'; regorder.values = {0 1 2 3}; regorder.def = @(val)spm_get_defaults('unwarp.estimate.regorder', val{:}); % --------------------------------------------------------------------- % lambda Reg. Factor % --------------------------------------------------------------------- lambda = cfg_menu; lambda.tag = 'lambda'; lambda.name = 'Reg. Factor'; lambda.help = {'Regularisation factor. Default: Medium.'}; lambda.labels = { 'A little' 'Medium' 'A lot' }'; lambda.values = {10000 100000 1000000}; lambda.def = @(val)spm_get_defaults('unwarp.estimate.regwgt', val{:}); % --------------------------------------------------------------------- % jm Jacobian deformations % --------------------------------------------------------------------- jm = cfg_menu; jm.tag = 'jm'; jm.name = 'Jacobian deformations'; jm.help = {'In the defaults there is also an option to include Jacobian intensity modulation when estimating the fields. "Jacobian intensity modulation" refers to the dilution/concentration of intensity that ensue as a consequence of the distortions. Think of a semi-transparent coloured rubber sheet that you hold against a white background. If you stretch a part of the sheet (induce distortions) you will see the colour fading in that particular area. In theory it is a brilliant idea to include also these effects when estimating the field (see e.g. Andersson et al, NeuroImage 20:870-888). In practice for this specific problem it is NOT a good idea. Default: No'}; jm.labels = { 'Yes' 'No' }'; jm.values = {1 0}; jm.def = @(val)spm_get_defaults('unwarp.estimate.jm', val{:}); % --------------------------------------------------------------------- % fot First-order effects % --------------------------------------------------------------------- fot = cfg_entry; fot.tag = 'fot'; fot.name = 'First-order effects'; fot.help = { 'Theoretically (ignoring effects of shimming) one would expect the field to depend only on subject out-of-plane rotations. Hence the default choice ("Pitch and Roll", i.e., [4 5]). Go with that unless you have very good reasons to do otherwise' '' 'Vector of first order effects to model. Movements to be modelled are referred to by number. 1= x translation; 2= y translation; 3= z translation 4 = x rotation, 5 = y rotation and 6 = z rotation.' '' 'To model pitch & roll enter: [4 5]' '' 'To model all movements enter: [1:6]' '' 'Otherwise enter a customised set of movements to model' }'; fot.strtype = 'e'; fot.num = [1 Inf]; fot.def = @(val)spm_get_defaults('unwarp.estimate.foe', val{:}); % --------------------------------------------------------------------- % sot Second-order effects % --------------------------------------------------------------------- sot = cfg_entry; sot.tag = 'sot'; sot.name = 'Second-order effects'; sot.help = { 'List of second order terms to model second derivatives of. This is entered as a vector of movement parameters similar to first order effects, or leave blank for NONE' '' 'Movements to be modelled are referred to by number:' '' '1= x translation; 2= y translation; 3= z translation 4 = x rotation, 5 = y rotation and 6 = z rotation.' '' 'To model the interaction of pitch & roll enter: [4 5]' '' 'To model all movements enter: [1:6]' '' 'The vector will be expanded into an n x 2 matrix of effects. For example [4 5] will be expanded to:' '' '[ 4 4' '' ' 4 5' '' ' 5 5 ]' }'; sot.strtype = 'e'; sot.num = [Inf Inf]; sot.def = @(val)spm_get_defaults('unwarp.estimate.soe', val{:}); % --------------------------------------------------------------------- % uwfwhm Smoothing for unwarp (FWHM) % --------------------------------------------------------------------- uwfwhm = cfg_entry; uwfwhm.tag = 'uwfwhm'; uwfwhm.name = 'Smoothing for unwarp (FWHM)'; uwfwhm.help = {'FWHM (mm) of smoothing filter applied to images prior to estimation of deformation fields.'}; uwfwhm.strtype = 'r'; uwfwhm.num = [1 1]; uwfwhm.def = @(val)spm_get_defaults('unwarp.estimate.fwhm', val{:}); % --------------------------------------------------------------------- % rem Re-estimate movement params % --------------------------------------------------------------------- rem = cfg_menu; rem.tag = 'rem'; rem.name = 'Re-estimate movement params'; rem.help = {'Re-estimation means that movement-parameters should be re-estimated at each unwarping iteration. Default: Yes.'}; rem.labels = { 'Yes' 'No' }'; rem.values = {1 0}; rem.def = @(val)spm_get_defaults('unwarp.estimate.rem', val{:}); % --------------------------------------------------------------------- % noi Number of Iterations % --------------------------------------------------------------------- noi = cfg_entry; noi.tag = 'noi'; noi.name = 'Number of Iterations'; noi.help = {'Maximum number of iterations. Default: 5.'}; noi.strtype = 'n'; noi.num = [1 1]; noi.def = @(val)spm_get_defaults('unwarp.estimate.noi', val{:}); % --------------------------------------------------------------------- % expround Taylor expansion point % --------------------------------------------------------------------- expround = cfg_menu; expround.tag = 'expround'; expround.name = 'Taylor expansion point'; expround.help = {'Point in position space to perform Taylor-expansion around. Choices are (''First'', ''Last'' or ''Average''). ''Average'' should (in principle) give the best variance reduction. If a field-map acquired before the time-series is supplied then expansion around the ''First'' MIGHT give a slightly better average geometric fidelity.'}; expround.labels = { 'Average' 'First' 'Last' }'; expround.values = { 'Average' 'First' 'Last' }'; expround.def = @(val)spm_get_defaults('unwarp.estimate.expround', val{:}); % --------------------------------------------------------------------- % uweoptions Unwarp Estimation Options % --------------------------------------------------------------------- uweoptions = cfg_branch; uweoptions.tag = 'uweoptions'; uweoptions.name = 'Unwarp Estimation Options'; uweoptions.val = {basfcn regorder lambda jm fot sot uwfwhm rem noi expround }; uweoptions.help = {'Various registration & unwarping estimation options.'}; % --------------------------------------------------------------------- % uwwhich Reslices images (unwarp)? % --------------------------------------------------------------------- uwwhich = cfg_menu; uwwhich.tag = 'uwwhich'; uwwhich.name = 'Resliced images (unwarp)?'; uwwhich.help = { 'All Images (1..n) ' ' This reslices and unwarps all the images. ' ' ' 'All Images + Mean Image ' ' In addition to reslicing the images, it also creates a mean of the resliced images.' }'; uwwhich.labels = { ' All Images (1..n)' ' All Images + Mean Image' }'; uwwhich.values = {[2 0] [2 1]}; uwwhich.def = @(val)spm_get_defaults('realign.write.which', val{:}); % --------------------------------------------------------------------- % rinterp Interpolation % --------------------------------------------------------------------- rinterp = cfg_menu; rinterp.tag = 'rinterp'; rinterp.name = 'Interpolation'; rinterp.help = {'The method by which the images are sampled when being written in a different space. Nearest Neighbour is fastest, but not recommended for image realignment. Bilinear Interpolation is probably OK for PET, but not so suitable for fMRI because higher degree interpolation generally gives better results/* \cite{thevenaz00a,unser93a,unser93b}*/. Although higher degree methods provide better interpolation, but they are slower because they use more neighbouring voxels.'}; rinterp.labels = { 'Nearest neighbour' 'Trilinear' '2nd Degree B-spline ' '3rd Degree B-Spline' '4th Degree B-Spline' '5th Degree B-Spline ' '6th Degree B-Spline' '7th Degree B-Spline' }'; rinterp.values = {0 1 2 3 4 5 6 7}; rinterp.def = @(val)spm_get_defaults('realign.write.interp', val{:}); % --------------------------------------------------------------------- % wrap Wrapping % --------------------------------------------------------------------- wrap = cfg_menu; wrap.tag = 'wrap'; wrap.name = 'Wrapping'; wrap.help = { 'These are typically: ' ['* No wrapping - for images that have already been ' ... 'spatially transformed.'] ['* Wrap in Y - for (un-resliced) MRI where phase ' ... 'encoding is in the Y direction (voxel space).'] }'; wrap.labels = { 'No wrap' 'Wrap X' 'Wrap Y' 'Wrap X & Y' 'Wrap Z ' 'Wrap X & Z' 'Wrap Y & Z' 'Wrap X, Y & Z' }'; wrap.values = {[0 0 0] [1 0 0] [0 1 0] [1 1 0] [0 0 1] [1 0 1] [0 1 1]... [1 1 1]}; wrap.def = @(val)spm_get_defaults('realign.write.wrap', val{:}); % --------------------------------------------------------------------- % mask Masking % --------------------------------------------------------------------- mask = cfg_menu; mask.tag = 'mask'; mask.name = 'Masking'; mask.help = {'Because of subject motion, different images are likely to have different patterns of zeros from where it was not possible to sample data. With masking enabled, the program searches through the whole time series looking for voxels which need to be sampled from outside the original images. Where this occurs, that voxel is set to zero for the whole set of images (unless the image format can represent NaN, in which case NaNs are used where possible).'}; mask.labels = { 'Mask images' 'Dont mask images' }'; mask.values = {1 0}; mask.def = @(val)spm_get_defaults('realign.write.mask', val{:}); % --------------------------------------------------------------------- % prefix Filename Prefix % --------------------------------------------------------------------- prefix = cfg_entry; prefix.tag = 'prefix'; prefix.name = 'Filename Prefix'; prefix.help = {'Specify the string to be prepended to the filenames of the smoothed image file(s). Default prefix is ''u''.'}; prefix.strtype = 's'; prefix.num = [1 Inf]; prefix.def = @(val)spm_get_defaults('unwarp.write.prefix', val{:}); % --------------------------------------------------------------------- % uwroptions Unwarp Reslicing Options % --------------------------------------------------------------------- uwroptions = cfg_branch; uwroptions.tag = 'uwroptions'; uwroptions.name = 'Unwarp Reslicing Options'; uwroptions.val = {uwwhich rinterp wrap mask prefix }; uwroptions.help = {'Various registration & unwarping estimation options.'}; % --------------------------------------------------------------------- % realignunwarp Realign & Unwarp % --------------------------------------------------------------------- realignunwarp = cfg_exbranch; realignunwarp.tag = 'realignunwarp'; realignunwarp.name = 'Realign & Unwarp'; realignunwarp.val = {generic eoptions uweoptions uwroptions }; realignunwarp.help = { 'Within-subject registration and unwarping of time series.' '' 'The realignment part of this routine realigns a time-series of images acquired from the same subject using a least squares approach and a 6 parameter (rigid body) spatial transformation. The first image in the list specified by the user is used as a reference to which all subsequent scans are realigned. The reference scan does not have to the the first chronologically and it may be wise to chose a "representative scan" in this role.' '' 'The aim is primarily to remove movement artefact in fMRI and PET time-series (or more generally longitudinal studies). ".mat" files are written for each of the input 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.' '' 'In the coregistration step, the sessions are first realigned to each other, by aligning the first scan from each session to the first scan of the first session. Then the images within each session are aligned to the first image of the session. The parameter estimation is performed this way because it is assumed (rightly or not) that there may be systematic differences in the images between sessions.' 'The paper/* \cite{ja_geometric}*/ is unfortunately a bit old now and describes none of the newer features. Hopefully we''ll have a second paper out any decade now.' '' 'See also spm_uw_estimate.m for a detailed description of the implementation. Even after realignment there is considerable variance in fMRI time series that covary with, and is most probably caused by, subject movements/* \cite{ja_geometric}*/. It is also the case that this variance is typically large compared to experimentally induced variance. Anyone interested can include the estimated movement parameters as covariates in the design matrix, and take a look at an F-contrast encompassing those columns. It is quite dramatic. The result is loss of sensitivity, and if movements are correlated to task specificity. I.e. we may mistake movement induced variance for true activations. The problem is well known, and several solutions have been suggested. A quite pragmatic (and conservative) solution is to include the estimated movement parameters (and possibly squared) as covariates in the design matrix. Since we typically have loads of degrees of freedom in fMRI we can usually afford this. The problems occur when movements are correlated with the task, since the strategy above will discard "good" and "bad" variance alike (i.e. remove also "true" activations.' '' 'The "covariate" strategy described above was predicated on a model where variance was assumed to be caused by "spin history" effects, but will work pretty much equally good/bad regardless of what the true underlying cause is. Others have assumed that the residual variance is caused mainly by errors introduced by the interpolation kernel in the resampling step of the realignment. One has tried to solve this through higher order resampling (huge Sinc kernels, or k-space resampling). Unwarp is based on a different hypothesis regarding the residual variance. EPI images are not particularly faithful reproductions of the object, and in particular there are severe geometric distortions in regions where there is an air-tissue interface (e.g. orbitofrontal cortex and the anterior medial temporal lobes). In these areas in particular the observed image is a severely warped version of reality, much like a funny mirror at a fair ground. When one moves in front of such a mirror ones image will distort in different ways and ones head may change from very elongated to seriously flattened. If we were to take digital snapshots of the reflection at these different positions it is rather obvious that realignment will not suffice to bring them into a common space.' '' 'The situation is similar with EPI images, and an image collected for a given subject position will not be identical to that collected at another. We call this effect susceptibility-by-movement interaction. Unwarp is predicated on the assumption that the susceptibility-by- movement interaction is responsible for a sizable part of residual movement related variance.' '' 'Assume that we know how the deformations change when the subject changes position (i.e. we know the derivatives of the deformations with respect to subject position). That means that for a given time series and a given set of subject movements we should be able to predict the "shape changes" in the object and the ensuing variance in the time series. It also means that, in principle, we should be able to formulate the inverse problem, i.e. given the observed variance (after realignment) and known (estimated) movements we should be able to estimate how deformations change with subject movement. We have made an attempt at formulating such an inverse model, and at solving for the "derivative fields". A deformation field can be thought of as little vectors at each position in space showing how that particular location has been deflected. A "derivative field" is then the rate of change of those vectors with respect to subject movement. Given these "derivative fields" we should be able to remove the variance caused by the susceptibility-by-movement interaction. Since the underlying model is so restricted we would also expect experimentally induced variance to be preserved. Our experiments have also shown this to be true.' '' 'In theory it should be possible to estimate also the "static" deformation field, yielding an unwarped (to some true geometry) version of the time series. In practise that doesn''t really seem to work. Hence, the method deals only with residual movement related variance induced by the susceptibility-by-movement interaction. This means that the time-series will be undistorted to some "average distortion" state rather than to the true geometry. If one wants additionally to address the issue of anatomical fidelity one should combine Unwarp with a measured fieldmap.' '' 'The description above can be thought of in terms of a Taylor expansion of the field as a function of subject movement. Unwarp alone will estimate the first (and optionally second, see below) order terms of this expansion. It cannot estimate the zeroth order term (the distortions common to all scans in the time series) since that doesn''t introduce (almost) any variance in the time series. The measured fieldmap takes the role of the zeroth order term. Refer to the FieldMap toolbox and the documents FieldMap.man and FieldMap_principles.man for a description of how to obtain fieldmaps in the format expected by Unwarp.' '' 'If we think of the field as a function of subject movement it should in principle be a function of six variables since rigid body movement has six degrees of freedom. However, the physics of the problem tells us that the field should not depend on translations nor on rotation in a plane perpendicular to the magnetic flux. Hence it should in principle be sufficient to model the field as a function of out-of-plane rotations (i.e. pitch and roll). One can object to this in terms of the effects of shimming (object no longer immersed in a homogenous field) that introduces a dependence on all movement parameters. In addition SPM/Unwarp cannot really tell if the transversal slices it is being passed are really perpendicular to the flux or not. In practice it turns out thought that it is never (at least we haven''t seen any case) necessary to include more than Pitch and Roll. This is probably because the individual movement parameters are typically highly correlated anyway, which in turn is probably because most heads that we scan are attached to a neck around which rotations occur. On the subject of Taylor expansion we should mention that there is the option to use a second-order expansion (through the defaults) interface. This implies estimating also the rate-of-change w.r.t. to some movement parameter of the rate-of-change of the field w.r.t. some movement parameter (colloquially known as a second derivative). It can be quite interesting to watch (and it is amazing that it is possible) but rarely helpful/necessary.' '' 'In the defaults there is also an option to include Jacobian intensity modulation when estimating the fields. "Jacobian intensity modulation" refers to the dilution/concentration of intensity that ensue as a consequence of the distortions. Think of a semi-transparent coloured rubber sheet that you hold against a white background. If you stretch a part of the sheet (induce distortions) you will see the colour fading in that particular area. In theory it is a brilliant idea to include also these effects when estimating the field (see e.g. Andersson et al, NeuroImage 20:870-888). In practice for this specific problem it is NOT a good idea.' '' 'It should be noted that this is a method intended to correct data afflicted by a particular problem. If there is little movement in your data to begin with this method will do you little good. If on the other hand there is appreciable movement in your data (>1deg) it will remove some of that unwanted variance. If, in addition, movements are task related it will do so without removing all your "true" activations. The method attempts to minimise total (across the image volume) variance in the data set. It should be realised that while (for small movements) a rather limited portion of the total variance is removed, the susceptibility-by-movement interaction effects are quite localised to "problem" areas. Hence, for a subset of voxels in e.g. frontal-medial and orbitofrontal cortices and parts of the temporal lobes the reduction can be quite dramatic (>90). The advantages of using Unwarp will also depend strongly on the specifics of the scanner and sequence by which your data has been acquired. When using the latest generation scanners distortions are typically quite small, and distortion-by-movement interactions consequently even smaller. A small check list in terms of distortions is ' 'a) Fast gradients->short read-out time->small distortions ' 'b) Low field (i.e. <3T)->small field changes->small distortions ' 'c) Low res (64x64)->short read-out time->small distortions ' 'd) SENSE/SMASH->short read-out time->small distortions ' 'If you can tick off all points above chances are you have minimal distortions to begin with and you can say "sod Unwarp" (but not to our faces!).' }'; realignunwarp.prog = @spm_run_realignunwarp; realignunwarp.vout = @vout_rureslice; realignunwarp.modality = { 'PET' 'FMRI' 'VBM' }'; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function dep = vout_rureslice(job) for k=1:numel(job.data) cdep(1) = cfg_dep; cdep(1).sname = sprintf('Unwarp Params Variable (Sess %d)', k); cdep(1).src_output = substruct('.','sess', '()',{k}, '.','ds'); cdep(1).tgt_spec = cfg_findspec({{'class','cfg_entry'},{'strtype','e'}}); cdep(2) = cfg_dep; cdep(2).sname = sprintf('Unwarp Params File (Sess %d)', k); cdep(2).src_output = substruct('.','sess', '()',{k}, '.','dsfile'); cdep(2).tgt_spec = cfg_findspec({{'filter','any','strtype','e'}}); if job.uwroptions.uwwhich(1) == 2 cdep(3) = cfg_dep; cdep(3).sname = sprintf('Unwarped Images (Sess %d)', k); cdep(3).src_output = substruct('.','sess', '()',{k}, '.','uwrfiles'); cdep(3).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end; if k == 1 dep = cdep; else dep = [dep cdep]; end; end; if job.uwroptions.uwwhich(2), dep(end+1) = cfg_dep; dep(end).sname = 'Unwarped Mean Image'; dep(end).src_output = substruct('.','meanuwr'); dep(end).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}}); end;
github
philippboehmsturm/antx-master
spm_cfg_eeg_downsample.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_downsample.m
1,627
utf_8
b15f0a9d9a0b53425bd6ba4bc8d7a13e
function S = spm_cfg_eeg_downsample % configuration file for M/EEG downsampling %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: spm_cfg_eeg_downsample.m 3881 2010-05-07 21:02:57Z vladimir $ rev = '$Rev: 3881 $'; D = cfg_files; D.tag = 'D'; D.name = 'File Name'; D.filter = 'mat'; D.num = [1 1]; D.help = {'Select the M/EEG mat file.'}; fsample_new = cfg_entry; fsample_new.tag = 'fsample_new'; fsample_new.name = 'New sampling rate'; fsample_new.strtype = 'r'; fsample_new.num = [1 1]; fsample_new.help = {'Input the new sampling rate [Hz].'}; S = cfg_exbranch; S.tag = 'downsample'; S.name = 'M/EEG Downsampling'; S.val = {D fsample_new}; S.help = {'Downsample EEG/MEG data.'}; S.prog = @eeg_downsample; S.vout = @vout_eeg_downsample; S.modality = {'EEG'}; function out = eeg_downsample(job) % construct the S struct S.D = job.D{1}; S.fsample_new = job.fsample_new; out.D = spm_eeg_downsample(S); out.Dfname = {fullfile(out.D.path, out.D.fname)}; function dep = vout_eeg_downsample(job) % Output is always in field "D", no matter how job is structured dep = cfg_dep; dep.sname = 'Downsampled data'; % reference field "D" from output dep.src_output = substruct('.','D'); % this can be entered into any evaluated input dep.tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Downsampled Datafile'; % reference field "Dfname" from output dep(2).src_output = substruct('.','Dfname'); % this can be entered into any file selector dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_latex_cfg.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_latex_cfg.m
6,676
utf_8
a47b123dac969fa8a766913b882670a1
function spm_latex_cfg(c) % Convert a job configuration tree into a series of LaTeX documents %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id: spm_latex_cfg.m 3934 2010-06-17 14:58:25Z guillaume $ if ~nargin, c = spm_cfg; end if nargin && ischar(c), clean_latex_compile; return; end fp = fopen('spm_manual.tex','w'); fprintf(fp,'\\documentclass[a4paper,titlepage]{book}\n'); fprintf(fp,'\\usepackage{epsfig,amsmath,pifont,moreverb,minitoc}\n'); fprintf(fp,'%s\n%s\n%s\n%s\n%s\n%s\n%s\n',... '\usepackage[colorlinks=true,',... 'pdfpagemode=UseOutlines,',... 'pdftitle={SPM Manual},','pdfauthor={The SPM Team},',... 'pdfsubject={Statistical Parametric Mapping},',... 'pdfkeywords={neuroimaging, MRI, PET, EEG, MEG, SPM}',... ']{hyperref}'); fprintf(fp,'\\pagestyle{headings}\n\\bibliographystyle{plain}\n\n'); fprintf(fp,'\\hoffset=15mm\n\\voffset=-5mm\n'); fprintf(fp,'\\oddsidemargin=0mm\n\\evensidemargin=0mm\n\\topmargin=0mm\n'); fprintf(fp,'\\headheight=12pt\n\\headsep=10mm\n\\textheight=240mm\n\\textwidth=148mm\n'); fprintf(fp,'\\marginparsep=5mm\n\\marginparwidth=21mm\n\\footskip=10mm\n\n'); fprintf(fp,'\\title{\\huge{SPM Manual}}\n'); fprintf(fp,'\\author{The FIL Methods Group (and honorary members)}\n'); fprintf(fp,'\\begin{document}\n'); fprintf(fp,'\\maketitle\n'); fprintf(fp,'\\dominitoc\\tableofcontents\n\n'); fprintf(fp,'\\newpage\n\\section*{The SPM User Interface}\n'); write_help(c,fp); for i=1:numel(c.values), % this is always false, and each cfg_item has a tag %if isfield(c.values{i},'tag'), part(c.values{i},fp); %end; end; %fprintf(fp,'\\parskip=0mm\n\\bibliography{methods_macros,methods_group,external}\n\\end{document}\n\n'); fprintf(fp,'\\parskip=0mm\n'); bibcstr = get_bib(fullfile(spm('dir'),'man','biblio')); tbxlist = dir(fullfile(spm('dir'),'toolbox')); for k = 1:numel(tbxlist) if tbxlist(k).isdir, bibcstr=[bibcstr(:); get_bib(fullfile(spm('dir'),'toolbox', ... tbxlist(k).name))]; end; end; bibcstr = strcat(bibcstr,','); bibstr = strcat(bibcstr{:}); fprintf(fp,'\\bibliography{%s}\n',bibstr(1:end-1)); fprintf(fp,'\\end{document}\n\n'); fclose(fp); return; %========================================================================== function part(c,fp) % this is always false, and each cfg_item has a tag %if isstruct(c) && isfield(c,'tag'), fprintf(fp,'\\part{%s}\n',texify(c.name)); % write_help(c,fp); if isa(c,'cfg_repeat')||isa(c,'cfg_choice')||isa(c,'cfg_menu'), for i=1:numel(c.values), %if isfield(c.values{i},'tag'), fprintf(fp,'\\include{%s}\n',c.values{i}.tag); chapter(c.values{i}); %end; end; end; %if isfield(c,'val'), for i=1:numel(c.val), if isfield(c.val{i},'tag'), if chapter(c.val{i}), fprintf(fp,'\\include{%s}\n',c.val{i}.tag); end; end; end; %end; %end; return; %========================================================================== function sts = chapter(c) bn = c.tag; if strcmp(bn,'preproc') && ~isempty(strfind(c.name,'EEG')) bn = ['MEEG_' bn]; % fix for name clash with other 'preproc' end fp = fopen([bn '.tex'],'w'); if fp==-1, sts = false; return; end; fprintf(fp,'\\chapter{%s \\label{Chap:%s}}\n\\minitoc\n\n\\vskip 1.5cm\n\n',texify(c.name),c.tag); write_help(c,fp); switch class(c), case {'cfg_branch','cfg_exbranch'}, for i=1:numel(c.val), section(c.val{i},fp); end; case {'cfg_repeat','cfg_choice'}, for i=1:numel(c.values), section(c.values{i},fp); end; end; fclose(fp); sts = true; return; %========================================================================== function section(c,fp,lev) if nargin<3, lev = 1; end; sec = {'section','subsection','subsubsection','paragraph','subparagraph','textbf','textsc','textsl','textit'}; if lev<=length(sec), fprintf(fp,'\n\\%s{%s}\n',sec{lev},texify(c.name)); write_help(c,fp); switch class(c), case {'cfg_branch','cfg_exbranch'}, for i=1:numel(c.val), section(c.val{i},fp,lev+1); end; case {'cfg_repeat','cfg_choice'}, for i=1:numel(c.values), section(c.values{i},fp,lev+1); end; end; else warning(['Too many nested levels... ' c.name]); end; return; %========================================================================== function write_help(hlp,fp) if isa(hlp, 'cfg_item'), if ~isempty(hlp.help), hlp = hlp.help; else return; end; end; if iscell(hlp), for i=1:numel(hlp), write_help(hlp{i},fp); end; return; end; str = texify(hlp); fprintf(fp,'%s\n\n',str); return; %========================================================================== function str = texify(str0) st1 = strfind(str0,'/*'); en1 = strfind(str0,'*/'); st = []; en = []; for i=1:numel(st1), en1 = en1(en1>st1(i)); if ~isempty(en1), st = [st st1(i)]; en = [en en1(1)]; en1 = en1(2:end); end; end; str = []; pen = 1; for i=1:numel(st), str = [str clean_latex(str0(pen:st(i)-1)) str0(st(i)+2:en(i)-1)]; pen = en(i)+2; end; str = [str clean_latex(str0(pen:numel(str0)))]; return; %========================================================================== function str = clean_latex(str) str = strrep(str,'$','\$'); str = strrep(str,'&','\&'); str = strrep(str,'^','\^'); str = strrep(str,'_','\_'); str = strrep(str,'#','\#'); %str = strrep(str,'\','$\\$'); str = strrep(str,'|','$|$'); str = strrep(str,'>','$>$'); str = strrep(str,'<','$<$'); return; %========================================================================== function bibcstr = get_bib(bibdir) biblist = dir(fullfile(bibdir,'*.bib')); bibcstr={}; for k = 1:numel(biblist) [p n e v] = spm_fileparts(biblist(k).name); bibcstr{k} = fullfile(bibdir,n); end %========================================================================== function clean_latex_compile p = fullfile(spm('Dir'),'man'); [f, d] = spm_select('FPlist',p,'.*\.aux$'); f = strvcat(f, spm_select('FPlist',p,'.*\.tex$')); f = strvcat(f, spm_select('FPlist',p,'^manual\..*$')); f(strcmp(cellstr(f),fullfile(spm('Dir'),'man','manual.tex')),:) = []; f(strcmp(cellstr(f),fullfile(spm('Dir'),'man','manual.pdf')),:) = []; for i=1:size(d,1) f = strvcat(f, spm_select('FPlist',deblank(d(i,:)),'.*\.aux$')); end f(strcmp(cellstr(f),filesep),:) = []; disp(f); pause for i=1:size(f,1) spm_unlink(deblank(f(i,:))); end
github
philippboehmsturm/antx-master
spm_cfg_eeg_convert.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_convert.m
7,130
utf_8
9bf1bea2b0e3690b8d396162b76d4d33
function S = spm_cfg_eeg_convert % configuration file for data conversion %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % Stefan Kiebel % $Id: spm_cfg_eeg_convert.m 3881 2010-05-07 21:02:57Z vladimir $ dataset = cfg_files; dataset.tag = 'dataset'; dataset.name = 'File Name'; dataset.filter = 'any'; dataset.num = [1 1]; dataset.help = {'Select data set file.'}; timewindow = cfg_entry; timewindow.tag = 'timing'; timewindow.name = 'Timing'; timewindow.strtype = 'r'; timewindow.num = [1 2]; timewindow.help = {'start and end of epoch [ms]'}; readall = cfg_const; readall.tag = 'readall'; readall.name = 'Read all'; readall.val = {1}; read = cfg_choice; read.tag = 'read'; read.name = 'Continuous'; read.values = {timewindow, readall}; read.val = {readall}; usetrials = cfg_const; usetrials.tag = 'usetrials'; usetrials.name = 'Trials defined in data'; usetrials.val = {1}; trlfile = cfg_files; trlfile.tag = 'trlfile'; trlfile.name = 'Trial File'; trlfile.filter = 'mat'; trlfile.num = [1 1]; conditionlabel = cfg_entry; conditionlabel.tag = 'conditionlabel'; conditionlabel.name = 'Condition label'; conditionlabel.strtype = 's'; eventtype = cfg_entry; eventtype.tag = 'eventtype'; eventtype.name = 'Event type'; eventtype.strtype = 's'; eventvalue = cfg_entry; eventvalue.tag = 'eventvalue'; eventvalue.name = 'Event value'; eventvalue.strtype = 'e'; trialdef = cfg_branch; trialdef.tag = 'trialdef'; trialdef.name = 'Trial'; trialdef.val = {conditionlabel, eventtype, eventvalue}; define1 = cfg_repeat; define1.tag = 'unused'; define1.name = 'Trial definitions'; define1.values = {trialdef}; define = cfg_branch; define.tag = 'define'; define.name = 'Define trial'; define.val = {timewindow define1}; trials = cfg_choice; trials.tag = 'trials'; trials.name = 'Epoched'; trials.values = {usetrials trlfile define}; continuous = cfg_choice; continuous.tag = 'continuous'; continuous.name = 'Reading mode'; continuous.values = {read trials}; continuous.val = {read}; continuous.help = {'Select whether you want to convert to continuous or epoched data.'}; chanall = cfg_const; chanall.tag = 'chanall'; chanall.name = 'All'; chanall.val = {1}; chanmeg = cfg_const; chanmeg.tag = 'chanmeg'; chanmeg.name = 'MEG'; chanmeg.val = {1}; chaneeg = cfg_const; chaneeg.tag = 'chaneeg'; chaneeg.name = 'EEG'; chaneeg.val = {1}; chanfile = cfg_files; chanfile.tag = 'chanfile'; chanfile.name = 'Channel file'; chanfile.filter = 'mat'; chanfile.num = [1 1]; channels = cfg_choice; channels.tag = 'channels'; channels.name = 'Channel selection'; channels.values = {chanall,chanmeg,chaneeg,chanfile}; channels.val = {chanall}; outfile = cfg_entry; outfile.tag = 'outfile'; outfile.name = 'Output filename'; outfile.strtype = 's'; outfile.num = [0 inf]; outfile.val = {''}; outfile.help = {'Choose filename. Leave empty to add ''spm8_'' to the input file name.'}; datatype = cfg_menu; datatype.tag = 'datatype'; datatype.name = 'Data type'; datatype.labels = {'float32-le','float64-le'}; datatype.val = {'float32-le'}; datatype.values = {'float32-le','float64-le'}; datatype.help = {'Determine data type to save data in.'}; eventpadding = cfg_entry; eventpadding.tag = 'eventpadding'; eventpadding.name = 'Event padding'; eventpadding.strtype = 'r'; eventpadding.val = {0}; eventpadding.num = [1 1]; eventpadding.help = {'in sec - the additional time period around each trial',... 'for which the events are saved with the trial (to let the',... 'user keep and use for analysis events which are outside',... 'trial borders). Default - 0'}; blocksize = cfg_entry; blocksize.tag = 'blocksize'; blocksize.name = 'Block size'; blocksize.strtype = 'r'; blocksize.val = {3276800}; blocksize.num = [1 1]; blocksize.help = {'size of blocks used internally to split large files default ~100Mb'}; checkboundary = cfg_menu; checkboundary.tag = 'checkboundary'; checkboundary.name = 'Check boundary'; checkboundary.labels = {'Check boundaries', 'Don''t check boundaries'}; checkboundary.val = {1}; checkboundary.values = {1,0}; checkboundary.help = {'1 - check if there are breaks in the file and do not read',... 'across those breaks (default).',... '0 - ignore breaks (not recommended)'}; inputformat = cfg_entry; inputformat.tag = 'inputformat'; inputformat.name = 'Input data format'; inputformat.strtype = 's'; inputformat.val = {'autodetect'}; inputformat.num = [1 inf]; inputformat.help = {'Force the reader to assume a particular data format (usually not necessary)'}; S = cfg_exbranch; S.tag = 'convert'; S.name = 'M/EEG Conversion'; S.val = {dataset continuous channels outfile datatype eventpadding blocksize checkboundary inputformat}; S.help = {'Converts EEG/MEG data.'}; S.prog = @eeg_convert; S.vout = @vout_eeg_convert; S.modality = {'EEG'}; function out = eeg_convert(job) % construct the S struct S.dataset = job.dataset{1}; S.continuous = job.continuous; S.channels = job.channels; if ~isempty(job.outfile) S.outfile = job.outfile; end S.datatype = job.datatype; S.eventpadding = job.eventpadding; S.blocksize = job.blocksize; S.checkboundary = job.checkboundary; if ~isequal(job.inputformat, 'autodetect') S.inputformat = job.inputformat; end if isfield(S.continuous, 'read') S.continuous = 1; if isfield(job.continuous.read, 'timing') S.timewindow = job.continuous.read.timing; end else if isfield(S.continuous.trials, 'usetrials') S.usetrials = S.continuous.trials.usetrials; end if isfield(S.continuous.trials, 'trlfile') S.trlfile = char(S.continuous.trials.trlfile); S.usetrials = 0; end if isfield(S.continuous.trials, 'define') S.trialdef = S.continuous.trials.define.trialdef; S.pretrig = S.continuous.trials.define.timing(1); S.posttrig = S.continuous.trials.define.timing(2); S.reviewtrials = 0; S.save = 0; S.usetrials = 0; [S.trl, S.conditionlabel] = spm_eeg_definetrial(S); end S.continuous = 0; end if isfield(S.channels, 'chanmeg') S.channels = 'MEG'; elseif isfield(S.channels, 'chaneeg') S.channels = 'EEG'; elseif isfield(S.channels, 'chanall') S.channels = 'all'; elseif isfield(S.channels, 'chanfile') S.chanfile = S.channels.chanfile{1}; S.channels = 'file'; end S.save = 0; S.review = 0; S = spm_eeg_channelselection(S); S = rmfield(S, 'save'); S = rmfield(S, 'review'); out.D = spm_eeg_convert(S); out.Dfname = {fullfile(out.D.path, out.D.fname)}; function dep = vout_eeg_convert(job) % Output is always in field "D", no matter how job is structured dep = cfg_dep; dep.sname = 'Converted M/EEG Data'; % reference field "D" from output dep.src_output = substruct('.','D'); % this can be entered into any evaluated input dep.tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Converted Datafile'; % reference field "Dfname" from output dep(2).src_output = substruct('.','Dfname'); % this can be entered into any file selector dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_cfg_cat.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_cat.m
2,707
utf_8
51b661dca39a9275dd0e770ae9c3cc6c
function cat = spm_cfg_cat % SPM Configuration file for 3D to 4D volumes conversion %__________________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % John Ashburner % $Id: spm_cfg_cat.m 3613 2009-12-04 18:47:59Z guillaume $ %-------------------------------------------------------------------------- % vols 3D Volumes %-------------------------------------------------------------------------- vols = cfg_files; vols.tag = 'vols'; vols.name = '3D Volumes'; vols.help = {'Select the volumes to concatenate'}; vols.filter = 'image'; vols.ufilter = '.*'; vols.num = [1 Inf]; %-------------------------------------------------------------------------- % dtype Data Type %-------------------------------------------------------------------------- dtype = cfg_menu; dtype.tag = 'dtype'; dtype.name = 'Data Type'; dtype.help = {'Data-type of output image. SAME indicates the same datatype as the original images.'}; dtype.labels = {'SAME' 'UINT8 - unsigned char' 'INT16 - signed short' 'INT32 - signed int' 'FLOAT32 - single prec. float' 'FLOAT64 - double prec. float'}'; dtype.values = {0 spm_type('uint8') spm_type('int16') spm_type('int32') spm_type('float32') spm_type('float64')}; dtype.val = {spm_type('int16')}; % to match previous behaviour %-------------------------------------------------------------------------- % name Output Filename %-------------------------------------------------------------------------- name = cfg_entry; name.tag = 'name'; name.name = 'Output Filename'; name.help = {'Specify the name of the output 4D volume file.' 'A ''.nii'' extension will be added if not specified.'}'; name.strtype = 's'; name.num = [1 Inf]; name.val = {'4D.nii'}; %-------------------------------------------------------------------------- % cat 3D to 4D File Conversion %-------------------------------------------------------------------------- cat = cfg_exbranch; cat.tag = 'cat'; cat.name = '3D to 4D File Conversion'; cat.val = {vols name dtype}; cat.help = {'Concatenate a number of 3D volumes into a single 4D file.'}; cat.prog = @spm_run_cat; cat.vout = @vout; %========================================================================== function dep = vout(varargin) % 4D output file will be saved in a struct with field .mergedfile dep(1) = cfg_dep; dep(1).sname = 'Concatenated 4D Volume'; dep(1).src_output = substruct('.','mergedfile'); dep(1).tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_minc.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_minc.m
3,433
utf_8
db7b8cb0f154a59326a8d72eafdb6d94
function minc = spm_cfg_minc % SPM Configuration file for MINC Import %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_minc.m 3691 2010-01-20 17:08:30Z guillaume $ rev = '$Rev: 3691 $'; % --------------------------------------------------------------------- % data MINC files % --------------------------------------------------------------------- data = cfg_files; data.tag = 'data'; data.name = 'MINC files'; data.help = {'Select the MINC files to convert.'}; data.filter = 'mnc'; data.ufilter = '.*'; data.num = [1 Inf]; % --------------------------------------------------------------------- % dtype Data Type % --------------------------------------------------------------------- dtype = cfg_menu; dtype.tag = 'dtype'; dtype.name = 'Data Type'; dtype.help = {'Data-type of output images. Note that the number of bits used determines the accuracy, and the amount of disk space needed.'}; dtype.labels = { 'UINT8 - unsigned char' 'INT16 - signed short' 'INT32 - signed int' 'FLOAT32 - single prec. float' 'FLOAT64 - double prec. float' }'; dtype.values = {spm_type('uint8') spm_type('int16') spm_type('int32') ... spm_type('float32') spm_type('float64')}; dtype.val = {spm_type('int16')}; % --------------------------------------------------------------------- % ext Output image format % --------------------------------------------------------------------- ext = cfg_menu; ext.tag = 'ext'; ext.name = 'Output image format'; ext.help = {'Output files can be written as .img + .hdr, or the two can be combined into a .nii file.'}; ext.labels = { 'Two file (img+hdr) NIfTI' 'Single file (nii) NIfTI' }'; ext.values = { 'img' 'nii' }'; ext.def = @(val)spm_get_defaults('images.format', val{:}); % --------------------------------------------------------------------- % opts Options % --------------------------------------------------------------------- opts = cfg_branch; opts.tag = 'opts'; opts.name = 'Options'; opts.val = {dtype ext }; opts.help = {'Conversion options'}; % --------------------------------------------------------------------- % minc MINC Import % --------------------------------------------------------------------- minc = cfg_exbranch; minc.tag = 'minc'; minc.name = 'MINC Import'; minc.val = {data opts }; minc.help = {'MINC Conversion. MINC is the image data format used for exchanging data within the ICBM community, and the format used by the MNI software tools. It is based on NetCDF, but due to be superceded by a new version relatively soon. MINC is no longer supported for reading images into SPM, so MINC files need to be converted to NIFTI format in order to use them. See http://www.bic.mni.mcgill.ca/software/ for more information.'}; minc.prog = @spm_run_minc; minc.vout = @vout; %------------------------------------------------------------------------ %------------------------------------------------------------------------ function dep = vout(job) dep = cfg_dep; dep.sname = 'Converted Images'; dep.src_output = substruct('.','files'); dep.tgt_spec = cfg_findspec({{'filter','image','strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_eeg_tf_rescale.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_eeg_tf_rescale.m
6,005
utf_8
692deed1fb1ca3d56ae284ba0ae3850b
function S = spm_cfg_eeg_tf_rescale % configuration file for rescaling spectrograms %__________________________________________________________________________ % Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging % Will Penny % $Id: spm_cfg_eeg_tf_rescale.m 4287 2011-04-04 13:55:54Z vladimir $ %-------------------------------------------------------------------------- % D %-------------------------------------------------------------------------- D = cfg_files; D.tag = 'D'; D.name = 'File Name'; D.filter = 'mat'; D.num = [1 1]; D.help = {'Select the M/EEG mat file.'}; %-------------------------------------------------------------------------- % Db %-------------------------------------------------------------------------- Db = cfg_files; Db.tag = 'Db'; Db.name = 'External baseline dataset'; Db.filter = 'mat'; Db.num = [0 1]; Db.val = {[]}; Db.help = {'Select the baseline M/EEG mat file. Leave empty to use the input dataset'}; %-------------------------------------------------------------------------- % Sbaseline %-------------------------------------------------------------------------- Sbaseline = cfg_entry; Sbaseline.tag = 'Sbaseline'; Sbaseline.name = 'Baseline'; Sbaseline.help = {'Start and stop of baseline [ms].'}; Sbaseline.strtype = 'e'; Sbaseline.num = [1 2]; %-------------------------------------------------------------------------- % baseline %-------------------------------------------------------------------------- baseline = cfg_branch; baseline.tag = 'baseline'; baseline.name = 'Baseline'; baseline.help = {'Baseline parameters.'}; baseline.val = {Sbaseline, Db}; %-------------------------------------------------------------------------- % method_logr %-------------------------------------------------------------------------- method_logr = cfg_branch; method_logr.tag = 'LogR'; method_logr.name = 'Log Ratio'; method_logr.val = {baseline}; method_logr.help = {'Log Ratio.'}; %-------------------------------------------------------------------------- % method_diff %-------------------------------------------------------------------------- method_diff = cfg_branch; method_diff.tag = 'Diff'; method_diff.name = 'Difference'; method_diff.val = {baseline}; method_diff.help = {'Difference.'}; %-------------------------------------------------------------------------- % method_rel %-------------------------------------------------------------------------- method_rel = cfg_branch; method_rel.tag = 'Rel'; method_rel.name = 'Relative'; method_rel.val = {baseline}; method_rel.help = {'Relative.'}; %-------------------------------------------------------------------------- % method_zscore %-------------------------------------------------------------------------- method_zscore = cfg_branch; method_zscore.tag = 'Zscore'; method_zscore.name = 'Zscore'; method_zscore.val = {baseline}; method_zscore.help = {'Z score'}; %-------------------------------------------------------------------------- % method_log %-------------------------------------------------------------------------- method_log = cfg_const; method_log.tag = 'Log'; method_log.name = 'Log'; method_log.val = {1}; method_log.help = {'Log.'}; %-------------------------------------------------------------------------- % method_sqrt %-------------------------------------------------------------------------- method_sqrt = cfg_const; method_sqrt.tag = 'Sqrt'; method_sqrt.name = 'Sqrt'; method_sqrt.val = {1}; method_sqrt.help = {'Square Root.'}; %-------------------------------------------------------------------------- % method %-------------------------------------------------------------------------- method = cfg_choice; method.tag = 'method'; method.name = 'Rescale method'; method.val = {method_logr}; method.help = {'Select the rescale method.'}; method.values = {method_logr method_diff method_rel method_zscore method_log method_sqrt}; %-------------------------------------------------------------------------- % S %-------------------------------------------------------------------------- S = cfg_exbranch; S.tag = 'rescale'; S.name = 'M/EEG Time-Frequency Rescale'; S.val = {D, method}; S.help = {'Rescale (avg) spectrogram with nonlinear and/or difference operator.' 'For ''Log'' and ''Sqrt'', these functions are applied to spectrogram.' 'For ''LogR'', ''Rel'' and ''Diff'' this function computes power in the baseline.' 'p_b and outputs:' '(i) p-p_b for ''Diff''' '(ii) 100*(p-p_b)/p_b for ''Rel''' '(iii) log (p/p_b) for ''LogR'''}'; S.prog = @eeg_tf_rescale; S.vout = @vout_eeg_tf_rescale; S.modality = {'EEG'}; %========================================================================== function out = eeg_tf_rescale(job) % construct the S struct S.D = job.D{1}; S.tf.method = fieldnames(job.method); S.tf.method = S.tf.method{1}; switch lower(S.tf.method) case {'logr','diff', 'rel', 'zscore'} S.tf.Sbaseline = 1e-3*job.method.(S.tf.method).baseline.Sbaseline; if ~(isempty(job.method.(S.tf.method).baseline.Db) || isequal(job.method.(S.tf.method).baseline.Db, {''})) S.tf.Db = job.method.(S.tf.method).baseline.Db{1}; end case {'log', 'sqrt'} end out.D = spm_eeg_tf_rescale(S); out.Dfname = {fullfile(out.D.path,out.D.fname)}; %========================================================================== function dep = vout_eeg_tf_rescale(job) % return dependencies dep(1) = cfg_dep; dep(1).sname = 'Rescaled TF Data'; dep(1).src_output = substruct('.','D'); dep(1).tgt_spec = cfg_findspec({{'strtype','e'}}); dep(2) = cfg_dep; dep(2).sname = 'Rescaled TF Datafile'; dep(2).src_output = substruct('.','Dfname'); dep(2).tgt_spec = cfg_findspec({{'filter','mat'}});
github
philippboehmsturm/antx-master
spm_cfg_fmri_data.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_fmri_data.m
3,059
utf_8
12045b3c567f606b6bfd8daba94e14d2
function fmri_data = spm_cfg_fmri_data % SPM Configuration file % automatically generated by the MATLABBATCH utility function GENCODE %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_fmri_data.m 1517 2008-04-29 15:46:08Z volkmar $ rev = '$Rev: 1517 $'; % --------------------------------------------------------------------- % scans Scans % --------------------------------------------------------------------- scans = cfg_files; scans.tag = 'scans'; scans.name = 'Scans'; scans.help = {'Select the fMRI scans for this session. They must all have the same image dimensions, orientation, voxel size etc.'}; scans.filter = 'image'; scans.ufilter = '.*'; scans.num = [1 Inf]; % --------------------------------------------------------------------- % spmmat Select SPM.mat % --------------------------------------------------------------------- spmmat = cfg_files; spmmat.tag = 'spmmat'; spmmat.name = 'Select SPM.mat'; spmmat.help = {'Select the SPM.mat file containing the specified design matrix.'}; spmmat.filter = 'mat'; spmmat.ufilter = '.*'; spmmat.num = [1 1]; % --------------------------------------------------------------------- % mask Explicit mask % --------------------------------------------------------------------- mask = cfg_files; mask.tag = 'mask'; mask.name = 'Explicit mask'; mask.val{1} = {''}; mask.help = {'Specify an image for explicitly masking the analysis. A sensible option here is to use a segmention of structural images to specify a within-brain mask. If you select that image as an explicit mask then only those voxels in the brain will be analysed. This both speeds the estimation and restricts SPMs/PPMs to within-brain voxels. Alternatively, if such structural images are unavailble or no masking is required, then leave this field empty.'}; mask.filter = 'image'; mask.ufilter = '.*'; mask.num = [0 1]; % --------------------------------------------------------------------- % fmri_data fMRI data specification % --------------------------------------------------------------------- fmri_data = cfg_exbranch; fmri_data.tag = 'fmri_data'; fmri_data.name = 'fMRI data specification'; fmri_data.val = {scans spmmat mask }; fmri_data.help = {'Select the data and optional explicit mask for a specified design'}; fmri_data.prog = @spm_run_fmri_data; fmri_data.vout = @vout_stats; fmri_data.modality = {'FMRI'}; %------------------------------------------------------------------------- %------------------------------------------------------------------------- function dep = vout_stats(job) dep(1) = cfg_dep; dep(1).sname = 'SPM.mat File'; dep(1).src_output = substruct('.','spmmat'); dep(1).tgt_spec = cfg_findspec({{'filter','mat','strtype','e'}}); %dep(2) = cfg_dep; %dep(2).sname = 'SPM Variable'; %dep(2).src_output = substruct('.','spmvar'); %dep(2).tgt_spec = cfg_findspec({{'strtype','e'}});
github
philippboehmsturm/antx-master
spm_cfg_movefile.m
.m
antx-master/freiburgLight/matlab/spm8/config/spm_cfg_movefile.m
2,778
utf_8
3aed73b31c1eefbf725dd13633890907
function movefile = spm_cfg_movefile % SPM Configuration file for move file function %_______________________________________________________________________ % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging % $Id: spm_cfg_movefile.m 1827 2008-06-16 13:54:37Z guillaume $ % ---------------------------------------------------------------------- % srcfiles Files to move % ---------------------------------------------------------------------- srcfiles = cfg_files; srcfiles.tag = 'srcfiles'; srcfiles.name = 'Files to move'; srcfiles.help = {'Select files to move.'}; srcfiles.filter = '.*'; srcfiles.ufilter = '.*'; srcfiles.num = [0 Inf]; % ---------------------------------------------------------------------- % targetdir Target directory % ---------------------------------------------------------------------- targetdir = cfg_files; targetdir.tag = 'targetdir'; targetdir.name = 'Target directory'; targetdir.help = {'Select target directory.'}; targetdir.filter = 'dir'; targetdir.ufilter = '.*'; targetdir.num = [1 1]; % ---------------------------------------------------------------------- % movefile Move Files (Deprecated) % ---------------------------------------------------------------------- movefile = cfg_exbranch; movefile.tag = 'movefile'; movefile.name = 'Move Files (Deprecated)'; movefile.val = {srcfiles targetdir }; movefile.help = { 'This module is deprecated and has been moved to BasicIO.' 'Jobs which are ready to run may continue using it, but the module inputs can not be changed via GUI. Please switch to the BasicIO module instead.' '' 'This facilty allows to move files in a batch. Note that moving files will not make them disappear from file selection lists. Therefore one has to be careful not to select the original files after they have been programmed to be moved.' '' 'If image files (.*img or .*nii) are selected, corresponding hdr or mat files will be moved as well, if they exist.' }; movefile.prog = @my_movefile; movefile.hidden = true; %======================================================================= function my_movefile(varargin) job = varargin{1}; for k = 1:numel(job.srcfiles) [p n e v] = spm_fileparts(job.srcfiles{k}); if strncmp(e,'.img',4)||strncmp(e,'.nii',4) try_movefile(fullfile(p,[n e]),job.targetdir{1}); try_movefile(fullfile(p,[n '.mat']),job.targetdir{1}); try_movefile(fullfile(p,[n '.hdr']),job.targetdir{1}); else try_movefile(job.srcfiles{k},job.targetdir{1}); end end %======================================================================= function try_movefile(src,dest) % silently try to move files try movefile(src,dest); end